type
stringclasses
1 value
dataset
stringclasses
1 value
input
stringlengths
75
160k
instruction
stringlengths
117
171
output
stringlengths
88
168k
Inversion-Mutation
megadiff
"public void loadMapFile(File resourceFile) throws FileNotFoundException { myScanner = new Scanner(resourceFile); loadTitle(); try { loadPlayers(); loadSize(); loadTileIndex(); } catch (MapNotMatchException e) { // TODO Auto-generated catch block e.printStackTrace(); } loadTerrainIndex(); loadTiles(); loadTerrains(); loadResources(); myScanner.close(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "loadMapFile"
"public void loadMapFile(File resourceFile) throws FileNotFoundException { myScanner = new Scanner(resourceFile); loadTitle(); try { loadPlayers(); loadSize(); } catch (MapNotMatchException e) { // TODO Auto-generated catch block e.printStackTrace(); } <MASK>loadTileIndex();</MASK> loadTerrainIndex(); loadTiles(); loadTerrains(); loadResources(); myScanner.close(); }"
Inversion-Mutation
megadiff
"public void getOut() { // clean request pad from adder Pad upstreamPeer = sink.getPeer(); upstreamPeer.setBlocked(true); this.setState(State.NULL); System.out.println("Remove from parent bin " + ((Bin) this.getParent()).remove(this)); upstreamPeer.getParentElement().releaseRequestPad(upstreamPeer); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getOut"
"public void getOut() { // clean request pad from adder Pad upstreamPeer = sink.getPeer(); upstreamPeer.setBlocked(true); System.out.println("Remove from parent bin " + ((Bin) this.getParent()).remove(this)); <MASK>this.setState(State.NULL);</MASK> upstreamPeer.getParentElement().releaseRequestPad(upstreamPeer); }"
Inversion-Mutation
megadiff
"public Element transferManageItems(Element resources, String courseId, File resoucesDir, int item_ref_num) throws Exception { String fromUploadsColl = Entity.SEPARATOR+"private"+ REFERENCE_ROOT+ Entity.SEPARATOR+courseId+Entity.SEPARATOR+"uploads"+Entity.SEPARATOR; List fromContextList = meleteCHService.getMemberNamesCollection(fromUploadsColl); if ((fromContextList != null)&&(fromContextList.size() > 0)) { List meleteResourceList = sectionDB.getAllMeleteResourcesOfCourse(courseId); if ((meleteResourceList != null)&&(meleteResourceList.size() > 0)) { fromContextList.removeAll(meleteResourceList); } if ((fromContextList != null)&&(fromContextList.size() > 0)) { ListIterator repIt = fromContextList.listIterator(); while (repIt != null && repIt.hasNext()) { String content_resource_id = (String) repIt.next(); ArrayList content_data = new ArrayList(); logger.debug("calling secContent from create section"); Element resource = resources.addElement("resource"); resource.addAttribute("identifier","MANAGERESOURCE"+ item_ref_num); resource.addAttribute("type ","webcontent"); resource.addAttribute("adlcp:scormType","asset"); byte[] content_data1 =setContentResourceData(content_resource_id,content_data); String sectionFileName = (String)content_data.get(0); if(((String)content_data.get(2)).equals(getMeleteCHService().MIME_TYPE_LINK)) { String linkData = new String(content_data1); if(linkData.startsWith(ServerConfigurationService.getServerUrl()) && linkData.indexOf("/access/content/group")!= -1) { String link_resource_id = meleteUtil.replace(linkData,ServerConfigurationService.getServerUrl()+"/access/content",""); // read resource and create a file ArrayList link_content = new ArrayList(); byte[] linkdata =setContentResourceData(link_resource_id, link_content); if(linkdata == null) {continue;} if(!((String)link_content.get(2)).equals(getMeleteCHService().MIME_TYPE_LINK)) { logger.debug("link resource points to site res item as file. Include file in zip"); // Site resource item is file and not URL String resfileName = Validator.escapeResourceName((String)link_content.get(0)); File resfile = new File(resoucesDir+ "/"+ resfileName); createFileFromContent(linkdata, resfile.getAbsolutePath()); Element file = resource.addElement("file"); file.addAttribute("href", "resources/"+ resfileName); } } // resource will always point to link location otherwise it changes type to upload on import resource.addAttribute("href", linkData); } else { Element file = resource.addElement("file"); String fileName = Validator.escapeResourceName(sectionFileName); if (fileName.startsWith("module_")) { int und_index = fileName.indexOf("_",7); fileName = fileName.substring(und_index+1, fileName.length()); } file.addAttribute("href", "resources/"+ fileName); resource.addAttribute("href", "resources/"+ fileName); //create the file File resfile = new File(resoucesDir+ "/"+ fileName); createFileFromContent(content_data1, resfile.getAbsolutePath()); } item_ref_num++; }//End while repIt } } return resources; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "transferManageItems"
"public Element transferManageItems(Element resources, String courseId, File resoucesDir, int item_ref_num) throws Exception { String fromUploadsColl = Entity.SEPARATOR+"private"+ REFERENCE_ROOT+ Entity.SEPARATOR+courseId+Entity.SEPARATOR+"uploads"+Entity.SEPARATOR; List fromContextList = meleteCHService.getMemberNamesCollection(fromUploadsColl); if ((fromContextList != null)&&(fromContextList.size() > 0)) { List meleteResourceList = sectionDB.getAllMeleteResourcesOfCourse(courseId); if ((meleteResourceList != null)&&(meleteResourceList.size() > 0)) { fromContextList.removeAll(meleteResourceList); if ((fromContextList != null)&&(fromContextList.size() > 0)) { ListIterator repIt = fromContextList.listIterator(); while (repIt != null && repIt.hasNext()) { String content_resource_id = (String) repIt.next(); ArrayList content_data = new ArrayList(); logger.debug("calling secContent from create section"); Element resource = resources.addElement("resource"); resource.addAttribute("identifier","MANAGERESOURCE"+ item_ref_num); resource.addAttribute("type ","webcontent"); resource.addAttribute("adlcp:scormType","asset"); byte[] content_data1 =setContentResourceData(content_resource_id,content_data); String sectionFileName = (String)content_data.get(0); if(((String)content_data.get(2)).equals(getMeleteCHService().MIME_TYPE_LINK)) { String linkData = new String(content_data1); if(linkData.startsWith(ServerConfigurationService.getServerUrl()) && linkData.indexOf("/access/content/group")!= -1) { String link_resource_id = meleteUtil.replace(linkData,ServerConfigurationService.getServerUrl()+"/access/content",""); // read resource and create a file ArrayList link_content = new ArrayList(); byte[] linkdata =setContentResourceData(link_resource_id, link_content); if(linkdata == null) {continue;<MASK>}</MASK> if(!((String)link_content.get(2)).equals(getMeleteCHService().MIME_TYPE_LINK)) { logger.debug("link resource points to site res item as file. Include file in zip"); // Site resource item is file and not URL String resfileName = Validator.escapeResourceName((String)link_content.get(0)); File resfile = new File(resoucesDir+ "/"+ resfileName); createFileFromContent(linkdata, resfile.getAbsolutePath()); Element file = resource.addElement("file"); file.addAttribute("href", "resources/"+ resfileName); <MASK>}</MASK> <MASK>}</MASK> // resource will always point to link location otherwise it changes type to upload on import resource.addAttribute("href", linkData); <MASK>}</MASK> else { Element file = resource.addElement("file"); String fileName = Validator.escapeResourceName(sectionFileName); if (fileName.startsWith("module_")) { int und_index = fileName.indexOf("_",7); fileName = fileName.substring(und_index+1, fileName.length()); <MASK>}</MASK> file.addAttribute("href", "resources/"+ fileName); resource.addAttribute("href", "resources/"+ fileName); //create the file File resfile = new File(resoucesDir+ "/"+ fileName); createFileFromContent(content_data1, resfile.getAbsolutePath()); <MASK>}</MASK> item_ref_num++; <MASK>}</MASK>//End while repIt <MASK>}</MASK> <MASK>}</MASK> <MASK>}</MASK> return resources; <MASK>}</MASK>"
Inversion-Mutation
megadiff
"@Override protected void createAndShowGUI() { System.setProperty("apple.laf.useScreenMenuBar", "true"); super.createAndShowGUI(); trayIcon.removeActionListener(settingsListener); try { OSXAdapter.setAboutHandler(this, AwtGatewayTray.class.getDeclaredMethod("about", (Class[]) null)); OSXAdapter.setPreferencesHandler(this, AwtGatewayTray.class.getDeclaredMethod("preferences", (Class[]) null)); OSXAdapter.setQuitHandler(this, OSXAwtGatewayTray.class.getDeclaredMethod("quit", (Class[]) null)); } catch (Exception e) { DavGatewayTray.error(new BundleMessage("LOG_ERROR_LOADING_OSXADAPTER"), e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createAndShowGUI"
"@Override protected void createAndShowGUI() { System.setProperty("apple.laf.useScreenMenuBar", "true"); <MASK>trayIcon.removeActionListener(settingsListener);</MASK> super.createAndShowGUI(); try { OSXAdapter.setAboutHandler(this, AwtGatewayTray.class.getDeclaredMethod("about", (Class[]) null)); OSXAdapter.setPreferencesHandler(this, AwtGatewayTray.class.getDeclaredMethod("preferences", (Class[]) null)); OSXAdapter.setQuitHandler(this, OSXAwtGatewayTray.class.getDeclaredMethod("quit", (Class[]) null)); } catch (Exception e) { DavGatewayTray.error(new BundleMessage("LOG_ERROR_LOADING_OSXADAPTER"), e); } }"
Inversion-Mutation
megadiff
"public OntologyParser(ParserInvocation parserInvocation) throws OntologyParserException { super(); log.info("executor ..."); this.parserInvocation = parserInvocation; if (!parserInvocation.valid()) throw new OntologyParserException(this.parserInvocation.getParserLog()); this.sourceOwlManager = OWLManager.createOWLOntologyManager(); //this.sourceOwlManager.setSilentMissingImportsHandling(true); if (this.parserInvocation.getInputRepositoryFolder() != null) { File rooDirectory = new File(this.parserInvocation.getInputRepositoryFolder()); this.sourceOwlManager.addIRIMapper(new AutoIRIMapper(rooDirectory, true)); } this.targetOwlManager = OWLManager.createOWLOntologyManager(); //this.targetOwlManager.setSilentMissingImportsHandling(true); log.info("executor created"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "OntologyParser"
"public OntologyParser(ParserInvocation parserInvocation) throws OntologyParserException { super(); log.info("executor ..."); if (!parserInvocation.valid()) throw new OntologyParserException(this.parserInvocation.getParserLog()); <MASK>this.parserInvocation = parserInvocation;</MASK> this.sourceOwlManager = OWLManager.createOWLOntologyManager(); //this.sourceOwlManager.setSilentMissingImportsHandling(true); if (this.parserInvocation.getInputRepositoryFolder() != null) { File rooDirectory = new File(this.parserInvocation.getInputRepositoryFolder()); this.sourceOwlManager.addIRIMapper(new AutoIRIMapper(rooDirectory, true)); } this.targetOwlManager = OWLManager.createOWLOntologyManager(); //this.targetOwlManager.setSilentMissingImportsHandling(true); log.info("executor created"); }"
Inversion-Mutation
megadiff
"public void showWarningBar(String warning) { if (warningBar_ == null) { warningBar_ = new InfoBar(InfoBar.WARNING, new ClickHandler() { @Override public void onClick(ClickEvent event) { hideWarningBar(); } }); } warningBar_.setText(warning); panel_.insertNorth(warningBar_, warningBar_.getHeight(), null); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "showWarningBar"
"public void showWarningBar(String warning) { if (warningBar_ == null) { warningBar_ = new InfoBar(InfoBar.WARNING, new ClickHandler() { @Override public void onClick(ClickEvent event) { hideWarningBar(); } }); <MASK>panel_.insertNorth(warningBar_, warningBar_.getHeight(), null);</MASK> } warningBar_.setText(warning); }"
Inversion-Mutation
megadiff
"public net.ivoa.SkyNode.MetaTable[] tables() throws java.rmi.RemoteException { Connection conn = null; DBInterface dbi = null; String []catalogNamesArray = null; String []tableNamesArray = null; List<String> catalogTableNamesList = null; List<String> catalogTableDescriptionsList = null; /** TODO * I should append the table description to the catalog description */ try { conn = DBConnection.getPooledPerUserConnection(); dbi = new DBInterface(conn); catalogNamesArray = dbi.getCatalogNames(); catalogTableNamesList = new ArrayList<String>(); catalogTableDescriptionsList = new ArrayList<String>(); for(String cat: Arrays.asList(catalogNamesArray)) { tableNamesArray = dbi.getTableNames(cat); String catalogDescription = dbi.getCatalogDescription(cat); for (String tab: Arrays.asList(tableNamesArray)) { catalogTableNamesList.add(cat+"."+tab); catalogTableDescriptionsList.add(catalogDescription); } } } catch(SQLException e) { logger.error("Caught an exception... ", e); DBInterface.close(dbi, conn); throw new java.rmi.RemoteException(e.getMessage()); } DBInterface.close(dbi, conn); net.ivoa.SkyNode.MetaTable[] metaTableArray = new net.ivoa.SkyNode.MetaTable[catalogTableNamesList.size()]; int i=0; Iterator<String> it = catalogTableDescriptionsList.iterator(); for (String s: catalogTableNamesList) { net.ivoa.SkyNode.MetaTable mt = new net.ivoa.SkyNode.MetaTable(); mt.setName(s); mt.setDescription(it.next()); metaTableArray[i++]=mt; } /* TODO * Insert the logic here */ return metaTableArray; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "tables"
"public net.ivoa.SkyNode.MetaTable[] tables() throws java.rmi.RemoteException { Connection conn = null; DBInterface dbi = null; String []catalogNamesArray = null; String []tableNamesArray = null; List<String> catalogTableNamesList = null; List<String> catalogTableDescriptionsList = null; /** TODO * I should append the table description to the catalog description */ try { conn = DBConnection.getPooledPerUserConnection(); dbi = new DBInterface(conn); catalogNamesArray = dbi.getCatalogNames(); catalogTableNamesList = new ArrayList<String>(); catalogTableDescriptionsList = new ArrayList<String>(); for(String cat: Arrays.asList(catalogNamesArray)) { tableNamesArray = dbi.getTableNames(cat); String catalogDescription = dbi.getCatalogDescription(cat); for (String tab: Arrays.asList(tableNamesArray)) { catalogTableNamesList.add(cat+"."+tab); catalogTableDescriptionsList.add(catalogDescription); } } } catch(SQLException e) { logger.error("Caught an exception... ", e); DBInterface.close(dbi, conn); throw new java.rmi.RemoteException(e.getMessage()); } DBInterface.close(dbi, conn); <MASK>net.ivoa.SkyNode.MetaTable mt = new net.ivoa.SkyNode.MetaTable();</MASK> net.ivoa.SkyNode.MetaTable[] metaTableArray = new net.ivoa.SkyNode.MetaTable[catalogTableNamesList.size()]; int i=0; Iterator<String> it = catalogTableDescriptionsList.iterator(); for (String s: catalogTableNamesList) { mt.setName(s); mt.setDescription(it.next()); metaTableArray[i++]=mt; } /* TODO * Insert the logic here */ return metaTableArray; }"
Inversion-Mutation
megadiff
"private void deleteDigitalObject(Connection connection, String pid) throws SQLException { logFinest("Entered DefaultDOReplicator.deleteDigitalObject"); Statement st=null; Statement st2=null; ResultSet results=null; try { st=connection.createStatement(); // // READ // logFinest("Checking do table for " + pid + "..."); results=logAndExecuteQuery(st, "SELECT doDbID FROM " + "do WHERE doPID='" + pid + "'"); if (!results.next()) { // must not be a digitalobject...exit early logFinest(pid + " wasn't found in do table..." + "skipping deletion as such."); return; } int dbid=results.getInt("doDbID"); results.close(); logFinest(pid + " was found in do table (DBID=" + dbid + ")"); logFinest("Getting dissDbID(s) from doDissAssoc " + "table..."); HashSet dissIds=new HashSet(); HashSet dissIdsInUse = new HashSet(); results=logAndExecuteQuery(st, "SELECT dissDbID from " + "doDissAssoc WHERE doDbID=" + dbid); while (results.next()) { dissIds.add(new Integer(results.getInt("dissDbID"))); } results.close(); HashSet bMechIds = new HashSet(); logFinest("Getting dissDbID(s) from doDissAssoc " + "table unique to this object..."); Iterator iterator = dissIds.iterator(); while (iterator.hasNext()) { Integer id = (Integer)iterator.next(); logFinest("Getting occurrences of dissDbID(s) in " + "doDissAssoc table..."); results=logAndExecuteQuery(st, "SELECT COUNT(*) from " + "doDissAssoc WHERE dissDbID=" + id); while (results.next()) { Integer i1 = new Integer(results.getInt("COUNT(*)")); if ( i1.intValue() > 1 ) { //dissIds.remove(id); // A dissDbID that occurs more than once indicates that the // disseminator is used by other objects. In this case, we // do not want to remove the disseminator from the diss // table so keep track of this dissDbID. dissIdsInUse.add(id); } else { ResultSet rs = null; logFinest("Getting associated bMechDbID(s) that are unique " + "for this object in diss table..."); st2 = connection.createStatement(); rs=logAndExecuteQuery(st2, "SELECT bMechDbID from " + "diss WHERE dissDbID=" + id); while (rs.next()) { bMechIds.add(new Integer(rs.getInt("bMechDbID"))); } rs.close(); st2.close(); } } results.close(); } iterator = dissIdsInUse.iterator(); // Remove disseminator ids of those disseminators that were in // use by one or more other objects to prevent them from being // removed from the disseminator table in following code section. while (iterator.hasNext() ) { Integer id = (Integer)iterator.next(); dissIds.remove(id); } logFinest("Found " + dissIds.size() + " dissDbID(s)."); logFinest("Getting bMechDbIDs matching dsBindMapDbID(s) from dsBind " + "table..."); logFinest("Getting dsBindMapDbID(s) from dsBind " + "table..."); //HashSet bmapIds=new HashSet(); //results=logAndExecuteQuery(st, "SELECT dsBindMapDbID FROM " // + "dsBind WHERE doDbID=" + dbid); //while (results.next()) { // bmapIds.add(new Integer(results.getInt("dsBindMapDbID"))); //} //results.close(); //logFinest("Found " + bmapIds.size() + " dsBindMapDbID(s)."); // // WRITE // int rowCount; logFinest("Attempting row deletion from do table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM do " + "WHERE doDbID=" + dbid); logFinest("Deleted " + rowCount + " row(s)."); logFinest("Attempting row deletion from doDissAssoc " + "table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM " + "doDissAssoc WHERE doDbID=" + dbid); logFinest("Deleted " + rowCount + " row(s)."); logFinest("Attempting row deletion from dsBind table.."); rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBind " + "WHERE doDbID=" + dbid); logFinest("Deleted " + rowCount + " row(s)."); logFinest("Attempting row deletion from diss table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM diss WHERE " + inIntegerSetWhereConditionString("dissDbID", dissIds)); logFinest("Deleted " + rowCount + " row(s)."); logFinest("Attempting row deletion from dsBindMap " + "table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap " + "WHERE " + inIntegerSetWhereConditionString( // "dsBindMapDbID", bmapIds)); "bMechDbID", bMechIds)); logFinest("Deleted " + rowCount + " row(s)."); } finally { if (results != null) results.close(); if (st!=null) st.close(); if (st2!=null) st2.close(); logFinest("Exiting DefaultDOReplicator.deleteDigitalObject"); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "deleteDigitalObject"
"private void deleteDigitalObject(Connection connection, String pid) throws SQLException { logFinest("Entered DefaultDOReplicator.deleteDigitalObject"); Statement st=null; Statement st2=null; ResultSet results=null; try { st=connection.createStatement(); <MASK>st2 = connection.createStatement();</MASK> // // READ // logFinest("Checking do table for " + pid + "..."); results=logAndExecuteQuery(st, "SELECT doDbID FROM " + "do WHERE doPID='" + pid + "'"); if (!results.next()) { // must not be a digitalobject...exit early logFinest(pid + " wasn't found in do table..." + "skipping deletion as such."); return; } int dbid=results.getInt("doDbID"); results.close(); logFinest(pid + " was found in do table (DBID=" + dbid + ")"); logFinest("Getting dissDbID(s) from doDissAssoc " + "table..."); HashSet dissIds=new HashSet(); HashSet dissIdsInUse = new HashSet(); results=logAndExecuteQuery(st, "SELECT dissDbID from " + "doDissAssoc WHERE doDbID=" + dbid); while (results.next()) { dissIds.add(new Integer(results.getInt("dissDbID"))); } results.close(); HashSet bMechIds = new HashSet(); logFinest("Getting dissDbID(s) from doDissAssoc " + "table unique to this object..."); Iterator iterator = dissIds.iterator(); while (iterator.hasNext()) { Integer id = (Integer)iterator.next(); logFinest("Getting occurrences of dissDbID(s) in " + "doDissAssoc table..."); results=logAndExecuteQuery(st, "SELECT COUNT(*) from " + "doDissAssoc WHERE dissDbID=" + id); while (results.next()) { Integer i1 = new Integer(results.getInt("COUNT(*)")); if ( i1.intValue() > 1 ) { //dissIds.remove(id); // A dissDbID that occurs more than once indicates that the // disseminator is used by other objects. In this case, we // do not want to remove the disseminator from the diss // table so keep track of this dissDbID. dissIdsInUse.add(id); } else { ResultSet rs = null; logFinest("Getting associated bMechDbID(s) that are unique " + "for this object in diss table..."); rs=logAndExecuteQuery(st2, "SELECT bMechDbID from " + "diss WHERE dissDbID=" + id); while (rs.next()) { bMechIds.add(new Integer(rs.getInt("bMechDbID"))); } rs.close(); st2.close(); } } results.close(); } iterator = dissIdsInUse.iterator(); // Remove disseminator ids of those disseminators that were in // use by one or more other objects to prevent them from being // removed from the disseminator table in following code section. while (iterator.hasNext() ) { Integer id = (Integer)iterator.next(); dissIds.remove(id); } logFinest("Found " + dissIds.size() + " dissDbID(s)."); logFinest("Getting bMechDbIDs matching dsBindMapDbID(s) from dsBind " + "table..."); logFinest("Getting dsBindMapDbID(s) from dsBind " + "table..."); //HashSet bmapIds=new HashSet(); //results=logAndExecuteQuery(st, "SELECT dsBindMapDbID FROM " // + "dsBind WHERE doDbID=" + dbid); //while (results.next()) { // bmapIds.add(new Integer(results.getInt("dsBindMapDbID"))); //} //results.close(); //logFinest("Found " + bmapIds.size() + " dsBindMapDbID(s)."); // // WRITE // int rowCount; logFinest("Attempting row deletion from do table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM do " + "WHERE doDbID=" + dbid); logFinest("Deleted " + rowCount + " row(s)."); logFinest("Attempting row deletion from doDissAssoc " + "table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM " + "doDissAssoc WHERE doDbID=" + dbid); logFinest("Deleted " + rowCount + " row(s)."); logFinest("Attempting row deletion from dsBind table.."); rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBind " + "WHERE doDbID=" + dbid); logFinest("Deleted " + rowCount + " row(s)."); logFinest("Attempting row deletion from diss table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM diss WHERE " + inIntegerSetWhereConditionString("dissDbID", dissIds)); logFinest("Deleted " + rowCount + " row(s)."); logFinest("Attempting row deletion from dsBindMap " + "table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap " + "WHERE " + inIntegerSetWhereConditionString( // "dsBindMapDbID", bmapIds)); "bMechDbID", bMechIds)); logFinest("Deleted " + rowCount + " row(s)."); } finally { if (results != null) results.close(); if (st!=null) st.close(); if (st2!=null) st2.close(); logFinest("Exiting DefaultDOReplicator.deleteDigitalObject"); } }"
Inversion-Mutation
megadiff
"public void handle(ChannelHandlerContext ctx, MessageEvent e) throws Exception { NettyResponseFuture<?> future = NettyResponseFuture.class.cast(ctx.getAttachment()); WebSocketUpgradeHandler h = WebSocketUpgradeHandler.class.cast(future.getAsyncHandler()); Request request = future.getRequest(); if (e.getMessage() instanceof HttpResponse) { HttpResponse response = (HttpResponse) e.getMessage(); HttpResponseStatus s = new ResponseStatus(future.getURI(), response, NettyAsyncHttpProvider.this); HttpResponseHeaders responseHeaders = new ResponseHeaders(future.getURI(), response, NettyAsyncHttpProvider.this); FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(h).request(request).responseStatus(s).responseHeaders(responseHeaders).build(); for (ResponseFilter asyncFilter : config.getResponseFilters()) { try { fc = asyncFilter.filter(fc); if (fc == null) { throw new NullPointerException("FilterContext is null"); } } catch (FilterException efe) { abort(future, efe); } } // The handler may have been wrapped. future.setAsyncHandler(fc.getAsyncHandler()); // The request has changed if (fc.replayRequest()) { replayRequest(future, fc, response, ctx); return; } future.setHttpResponse(response); if (redirect(request, future, response, ctx)) return; final org.jboss.netty.handler.codec.http.HttpResponseStatus status = new org.jboss.netty.handler.codec.http.HttpResponseStatus(101, "Web Socket Protocol Handshake"); final boolean validStatus = response.getStatus().equals(status); final boolean validUpgrade = response.getHeader(HttpHeaders.Names.UPGRADE) != null; String c = response.getHeader(HttpHeaders.Names.CONNECTION); if (c == null) { c = response.getHeader("connection"); } final boolean validConnection = c == null ? false : c.equalsIgnoreCase(HttpHeaders.Values.UPGRADE); s = new ResponseStatus(future.getURI(), response, NettyAsyncHttpProvider.this); final boolean statusReceived = h.onStatusReceived(s) == STATE.UPGRADE; if (!statusReceived) { h.onClose(new NettyWebSocket(ctx.getChannel()), 1002, "Bad response status " + response.getStatus().getCode()); future.done(null); return; } if (!validStatus || !validUpgrade || !validConnection) { throw new IOException("Invalid handshake response"); } String accept = response.getHeader("Sec-WebSocket-Accept"); String key = WebSocketUtil.getAcceptKey(future.getNettyRequest().getHeader(WEBSOCKET_KEY)); if (accept == null || !accept.equals(key)) { throw new IOException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, key)); } ctx.getPipeline().get(HttpResponseDecoder.class).replace("ws-decoder", new WebSocket08FrameDecoder(false, false)); if (h.onHeadersReceived(responseHeaders) == STATE.CONTINUE) { h.onSuccess(new NettyWebSocket(ctx.getChannel())); } ctx.getPipeline().replace("http-encoder", "ws-encoder", new WebSocket08FrameEncoder(true)); future.done(null); } else if (e.getMessage() instanceof WebSocketFrame) { final WebSocketFrame frame = (WebSocketFrame) e.getMessage(); if (frame instanceof TextWebSocketFrame) { pendingOpcode = OPCODE_TEXT; } else if (frame instanceof BinaryWebSocketFrame) { pendingOpcode = OPCODE_BINARY; } HttpChunk webSocketChunk = new HttpChunk() { private ChannelBuffer content; // @Override public boolean isLast() { return false; } // @Override public ChannelBuffer getContent() { return content; } // @Override public void setContent(ChannelBuffer content) { this.content = content; } }; if (frame.getBinaryData() != null) { webSocketChunk.setContent(ChannelBuffers.wrappedBuffer(frame.getBinaryData())); ResponseBodyPart rp = new ResponseBodyPart(future.getURI(), null, NettyAsyncHttpProvider.this, webSocketChunk, true); h.onBodyPartReceived(rp); NettyWebSocket webSocket = NettyWebSocket.class.cast(h.onCompleted()); if (webSocket != null) { if (pendingOpcode == OPCODE_BINARY) { webSocket.onBinaryFragment(rp.getBodyPartBytes(), frame.isFinalFragment()); } else { webSocket.onTextFragment(frame.getBinaryData().toString(UTF8), frame.isFinalFragment()); } if (CloseWebSocketFrame.class.isAssignableFrom(frame.getClass())) { try { webSocket.onClose(CloseWebSocketFrame.class.cast(frame).getStatusCode(), CloseWebSocketFrame.class.cast(frame).getReasonText()); } catch (Throwable t) { // Swallow any exception that may comes from a Netty version released before 3.4.0 log.trace("", t); } } } else { log.debug("UpgradeHandler returned a null NettyWebSocket "); } } } else { log.error("Invalid attachment {}", ctx.getAttachment()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handle"
"public void handle(ChannelHandlerContext ctx, MessageEvent e) throws Exception { NettyResponseFuture<?> future = NettyResponseFuture.class.cast(ctx.getAttachment()); WebSocketUpgradeHandler h = WebSocketUpgradeHandler.class.cast(future.getAsyncHandler()); Request request = future.getRequest(); if (e.getMessage() instanceof HttpResponse) { HttpResponse response = (HttpResponse) e.getMessage(); HttpResponseStatus s = new ResponseStatus(future.getURI(), response, NettyAsyncHttpProvider.this); HttpResponseHeaders responseHeaders = new ResponseHeaders(future.getURI(), response, NettyAsyncHttpProvider.this); FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(h).request(request).responseStatus(s).responseHeaders(responseHeaders).build(); for (ResponseFilter asyncFilter : config.getResponseFilters()) { try { fc = asyncFilter.filter(fc); if (fc == null) { throw new NullPointerException("FilterContext is null"); } } catch (FilterException efe) { abort(future, efe); } } // The handler may have been wrapped. future.setAsyncHandler(fc.getAsyncHandler()); // The request has changed if (fc.replayRequest()) { replayRequest(future, fc, response, ctx); return; } future.setHttpResponse(response); if (redirect(request, future, response, ctx)) return; final org.jboss.netty.handler.codec.http.HttpResponseStatus status = new org.jboss.netty.handler.codec.http.HttpResponseStatus(101, "Web Socket Protocol Handshake"); final boolean validStatus = response.getStatus().equals(status); final boolean validUpgrade = response.getHeader(HttpHeaders.Names.UPGRADE) != null; String c = response.getHeader(HttpHeaders.Names.CONNECTION); if (c == null) { c = response.getHeader("connection"); } final boolean validConnection = c == null ? false : c.equalsIgnoreCase(HttpHeaders.Values.UPGRADE); s = new ResponseStatus(future.getURI(), response, NettyAsyncHttpProvider.this); final boolean statusReceived = h.onStatusReceived(s) == STATE.UPGRADE; if (!statusReceived) { h.onClose(new NettyWebSocket(ctx.getChannel()), 1002, "Bad response status " + response.getStatus().getCode()); future.done(null); return; } if (!validStatus || !validUpgrade || !validConnection) { throw new IOException("Invalid handshake response"); } String accept = response.getHeader("Sec-WebSocket-Accept"); String key = WebSocketUtil.getAcceptKey(future.getNettyRequest().getHeader(WEBSOCKET_KEY)); if (accept == null || !accept.equals(key)) { throw new IOException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, key)); } if (h.onHeadersReceived(responseHeaders) == STATE.CONTINUE) { h.onSuccess(new NettyWebSocket(ctx.getChannel())); } <MASK>ctx.getPipeline().get(HttpResponseDecoder.class).replace("ws-decoder", new WebSocket08FrameDecoder(false, false));</MASK> ctx.getPipeline().replace("http-encoder", "ws-encoder", new WebSocket08FrameEncoder(true)); future.done(null); } else if (e.getMessage() instanceof WebSocketFrame) { final WebSocketFrame frame = (WebSocketFrame) e.getMessage(); if (frame instanceof TextWebSocketFrame) { pendingOpcode = OPCODE_TEXT; } else if (frame instanceof BinaryWebSocketFrame) { pendingOpcode = OPCODE_BINARY; } HttpChunk webSocketChunk = new HttpChunk() { private ChannelBuffer content; // @Override public boolean isLast() { return false; } // @Override public ChannelBuffer getContent() { return content; } // @Override public void setContent(ChannelBuffer content) { this.content = content; } }; if (frame.getBinaryData() != null) { webSocketChunk.setContent(ChannelBuffers.wrappedBuffer(frame.getBinaryData())); ResponseBodyPart rp = new ResponseBodyPart(future.getURI(), null, NettyAsyncHttpProvider.this, webSocketChunk, true); h.onBodyPartReceived(rp); NettyWebSocket webSocket = NettyWebSocket.class.cast(h.onCompleted()); if (webSocket != null) { if (pendingOpcode == OPCODE_BINARY) { webSocket.onBinaryFragment(rp.getBodyPartBytes(), frame.isFinalFragment()); } else { webSocket.onTextFragment(frame.getBinaryData().toString(UTF8), frame.isFinalFragment()); } if (CloseWebSocketFrame.class.isAssignableFrom(frame.getClass())) { try { webSocket.onClose(CloseWebSocketFrame.class.cast(frame).getStatusCode(), CloseWebSocketFrame.class.cast(frame).getReasonText()); } catch (Throwable t) { // Swallow any exception that may comes from a Netty version released before 3.4.0 log.trace("", t); } } } else { log.debug("UpgradeHandler returned a null NettyWebSocket "); } } } else { log.error("Invalid attachment {}", ctx.getAttachment()); } }"
Inversion-Mutation
megadiff
"private void createMultiFieldCombo(Composite composite, GridData gd) { toolkit.createLabel(composite, "Multiple field constraint"); final Combo combo = new Combo(composite, SWT.READ_ONLY); combo.setLayoutData(gd); combo.add("..."); combo.add("All of (And)"); combo.add("Any of (Or)"); combo.setData("All of (And)", CompositeFieldConstraint.COMPOSITE_TYPE_AND); combo.setData("Any of (Or)", CompositeFieldConstraint.COMPOSITE_TYPE_OR); combo.select(0); combo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (combo.getSelectionIndex() == 0) { return; } CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.compositeJunctionType = combo.getText(); constraint.addConstraint( comp ); modeller.reloadLhs(); modeller.setDirty(true); close(); } }); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createMultiFieldCombo"
"private void createMultiFieldCombo(Composite composite, GridData gd) { toolkit.createLabel(composite, "Multiple field constraint"); final Combo combo = new Combo(composite, SWT.READ_ONLY); combo.setLayoutData(gd); combo.add("..."); combo.add("All of (And)"); combo.add("Any of (Or)"); combo.setData("All of (And)", CompositeFieldConstraint.COMPOSITE_TYPE_AND); combo.setData("Any of (Or)", CompositeFieldConstraint.COMPOSITE_TYPE_OR); combo.select(0); combo.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (combo.getSelectionIndex() == 0) { return; } CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.compositeJunctionType = combo.getText(); constraint.addConstraint( comp ); <MASK>modeller.setDirty(true);</MASK> modeller.reloadLhs(); close(); } }); }"
Inversion-Mutation
megadiff
"public void handleEvent(Event event) { if (combo.getSelectionIndex() == 0) { return; } CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.compositeJunctionType = combo.getText(); constraint.addConstraint( comp ); modeller.reloadLhs(); modeller.setDirty(true); close(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleEvent"
"public void handleEvent(Event event) { if (combo.getSelectionIndex() == 0) { return; } CompositeFieldConstraint comp = new CompositeFieldConstraint(); comp.compositeJunctionType = combo.getText(); constraint.addConstraint( comp ); <MASK>modeller.setDirty(true);</MASK> modeller.reloadLhs(); close(); }"
Inversion-Mutation
megadiff
"public BlueMaggot() { GameState.getInstance().init(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setPreferredSize(new Dimension(GameState.getInstance().getWidth(), GameState.getInstance().getHeight() + 28)); setFocusable(true); setResizable(false); layeredPane.setBounds(0, 0, GameState.getInstance().getWidth(), GameState.getInstance().getHeight()); layeredPane.setOpaque(false); game = new blueMaggot.Game(this); menuTitle = new MenuTitle(game, this); menuOptions = new MenuOptions(game); menuOptionsLan = new MenuOptionsLan(game); menuAbout = new MenuAbout(game); menuScore = new MenuScoreBoard(game); menuLevelSelect = new MenuLevelSelect(game); menuBackground = new MenuBackground(menuTitle); menuKeys = new MenuKeys(game); gamePanel = new JPanel(); gamePanel.setBackground(Color.DARK_GRAY); layeredPane.add(gamePanel, new Integer(0)); layeredPane.add(menuBackground, new Integer(9)); layeredPane.add(menuTitle, new Integer(10)); layeredPane.add(menuOptions, new Integer(11)); layeredPane.add(menuOptionsLan, new Integer(11)); layeredPane.add(menuLevelSelect, new Integer(11)); layeredPane.add(menuAbout, new Integer(11)); layeredPane.add(menuKeys, new Integer(11)); layeredPane.add(menuScore, new Integer(12)); inputReal.resetLan(); try { inputReal.readConfig(); System.out.println("reading keybinds from config"); } catch (Exception e) { System.out.println("no config found, setting defaults"); } for (MenuField menuField : MenuField.menuFields) { menuField.reset(); } add(layeredPane); pack(); setLocationRelativeTo(null); setVisible(true); repaint(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "BlueMaggot"
"public BlueMaggot() { GameState.getInstance().init(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setPreferredSize(new Dimension(GameState.getInstance().getWidth(), GameState.getInstance().getHeight() + 28)); setFocusable(true); setResizable(false); layeredPane.setBounds(0, 0, GameState.getInstance().getWidth(), GameState.getInstance().getHeight()); layeredPane.setOpaque(false); game = new blueMaggot.Game(this); menuTitle = new MenuTitle(game, this); menuOptions = new MenuOptions(game); menuOptionsLan = new MenuOptionsLan(game); menuAbout = new MenuAbout(game); menuScore = new MenuScoreBoard(game); menuLevelSelect = new MenuLevelSelect(game); menuBackground = new MenuBackground(menuTitle); menuKeys = new MenuKeys(game); gamePanel = new JPanel(); gamePanel.setBackground(Color.DARK_GRAY); layeredPane.add(gamePanel, new Integer(0)); layeredPane.add(menuBackground, new Integer(9)); layeredPane.add(menuTitle, new Integer(10)); layeredPane.add(menuOptions, new Integer(11)); layeredPane.add(menuOptionsLan, new Integer(11)); layeredPane.add(menuLevelSelect, new Integer(11)); layeredPane.add(menuAbout, new Integer(11)); layeredPane.add(menuKeys, new Integer(11)); layeredPane.add(menuScore, new Integer(12)); try { inputReal.readConfig(); System.out.println("reading keybinds from config"); } catch (Exception e) { <MASK>inputReal.resetLan();</MASK> System.out.println("no config found, setting defaults"); } for (MenuField menuField : MenuField.menuFields) { menuField.reset(); } add(layeredPane); pack(); setLocationRelativeTo(null); setVisible(true); repaint(); }"
Inversion-Mutation
megadiff
"private void processTax(AuctionEvent auctionEvent) { Auction auction = auctionEvent.getAuction(); OfflinePlayer owner = auction.getOwner(); String ecoWorld = auction.getWorldGroup().getWorlds().get(0).getName(); double taxAmount; if(auctionEvent instanceof AuctionStartEvent) { taxAmount = auction.getStartTax(); } else if (auctionEvent instanceof AuctionEndEvent) { taxAmount = auction.getEndTax(); } else return; if(taxAmount != 0) { economy.withdrawPlayer(owner.getName(), ecoWorld, taxAmount); if(auctionSettings.useTaxAccount()) { economy.depositPlayer(auctionSettings.getTaxAccount(), taxAmount); } if(owner.isOnline()) { Locale locale = localeHandler.getLocale(owner.getPlayer()); owner.getPlayer().sendMessage(String.format(locale.getMessage("Auction.tax"), taxAmount)); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processTax"
"private void processTax(AuctionEvent auctionEvent) { Auction auction = auctionEvent.getAuction(); OfflinePlayer owner = auction.getOwner(); String ecoWorld = auction.getWorldGroup().getWorlds().get(0).getName(); <MASK>Locale locale = localeHandler.getLocale(owner.getPlayer());</MASK> double taxAmount; if(auctionEvent instanceof AuctionStartEvent) { taxAmount = auction.getStartTax(); } else if (auctionEvent instanceof AuctionEndEvent) { taxAmount = auction.getEndTax(); } else return; if(taxAmount != 0) { economy.withdrawPlayer(owner.getName(), ecoWorld, taxAmount); if(auctionSettings.useTaxAccount()) { economy.depositPlayer(auctionSettings.getTaxAccount(), taxAmount); } if(owner.isOnline()) { owner.getPlayer().sendMessage(String.format(locale.getMessage("Auction.tax"), taxAmount)); } } }"
Inversion-Mutation
megadiff
"@SuppressWarnings("deprecation") protected void installActionInternal(KernelControllerContext context) throws Throwable { KernelController controller = (KernelController) context.getController(); Kernel kernel = controller.getKernel(); KernelConfigurator configurator = kernel.getConfigurator(); BeanMetaData metaData = context.getBeanMetaData(); BeanInfo info = context.getBeanInfo(); final Joinpoint joinPoint = configurator.getConstructorJoinPoint(info, metaData.getConstructor(), metaData); Object object = dispatchJoinPoint(context, joinPoint); if (object == null) throw new IllegalStateException("Instantiate joinpoint returned a null object: " + joinPoint); context.setTarget(object); try { if (info == null) { info = configurator.getBeanInfo(object.getClass(), metaData.getAccessMode()); context.setBeanInfo(info); // update class scope with class info KernelMetaDataRepository repository = kernel.getMetaDataRepository(); // remove old context repository.removeMetaData(context); // create new scope key ScopeInfo scopeInfo = context.getScopeInfo(); ScopeKey scopeKey = new ScopeKey(scopeInfo.getScope().getScopes()); scopeKey.addScope(CommonLevels.CLASS, info.getClassInfo().getType()); scopeInfo.setScope(scopeKey); // re-register repository.addMetaData(context); // handle custom annotations applyAnnotations(context); } DependencyInfo dependencyInfo = context.getDependencyInfo(); if (dependencyInfo != null && dependencyInfo.isAutowireCandidate()) controller.addInstantiatedContext(context); } catch (Throwable t) { uninstall(context); throw t; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "installActionInternal"
"@SuppressWarnings("deprecation") protected void installActionInternal(KernelControllerContext context) throws Throwable { KernelController controller = (KernelController) context.getController(); Kernel kernel = controller.getKernel(); KernelConfigurator configurator = kernel.getConfigurator(); BeanMetaData metaData = context.getBeanMetaData(); BeanInfo info = context.getBeanInfo(); final Joinpoint joinPoint = configurator.getConstructorJoinPoint(info, metaData.getConstructor(), metaData); Object object = dispatchJoinPoint(context, joinPoint); if (object == null) throw new IllegalStateException("Instantiate joinpoint returned a null object: " + joinPoint); context.setTarget(object); try { if (info == null) { info = configurator.getBeanInfo(object.getClass(), metaData.getAccessMode()); context.setBeanInfo(info); // update class scope with class info <MASK>ScopeInfo scopeInfo = context.getScopeInfo();</MASK> KernelMetaDataRepository repository = kernel.getMetaDataRepository(); // remove old context repository.removeMetaData(context); // create new scope key ScopeKey scopeKey = new ScopeKey(scopeInfo.getScope().getScopes()); scopeKey.addScope(CommonLevels.CLASS, info.getClassInfo().getType()); scopeInfo.setScope(scopeKey); // re-register repository.addMetaData(context); // handle custom annotations applyAnnotations(context); } DependencyInfo dependencyInfo = context.getDependencyInfo(); if (dependencyInfo != null && dependencyInfo.isAutowireCandidate()) controller.addInstantiatedContext(context); } catch (Throwable t) { uninstall(context); throw t; } }"
Inversion-Mutation
megadiff
"protected boolean installInterestFilter(StructuredViewer viewer) { if (viewer == null) { MylarStatusHandler.log("The viewer to install InterestFilter is null", this); return false; } try { viewer.getControl().setRedraw(false); previousFilters.addAll(Arrays.asList(viewer.getFilters())); List<Class> excludedFilters = getPreservedFilters(); for (ViewerFilter filter : previousFilters) { if (!excludedFilters.contains(filter.getClass())) { try { viewer.removeFilter(filter); } catch (Throwable t) { MylarStatusHandler.fail(t, "Failed to remove filter: " + filter, false); } } } viewer.addFilter(interestFilter); viewer.getControl().setRedraw(true); return true; } catch (Throwable t) { MylarStatusHandler.fail(t, "Could not install viewer filter on: " + prefId, false); } return false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "installInterestFilter"
"protected boolean installInterestFilter(StructuredViewer viewer) { if (viewer == null) { MylarStatusHandler.log("The viewer to install InterestFilter is null", this); return false; } try { viewer.getControl().setRedraw(false); <MASK>viewer.addFilter(interestFilter);</MASK> previousFilters.addAll(Arrays.asList(viewer.getFilters())); List<Class> excludedFilters = getPreservedFilters(); for (ViewerFilter filter : previousFilters) { if (!excludedFilters.contains(filter.getClass())) { try { viewer.removeFilter(filter); } catch (Throwable t) { MylarStatusHandler.fail(t, "Failed to remove filter: " + filter, false); } } } viewer.getControl().setRedraw(true); return true; } catch (Throwable t) { MylarStatusHandler.fail(t, "Could not install viewer filter on: " + prefId, false); } return false; }"
Inversion-Mutation
megadiff
"@Override public void deploy() { DeploymentInfo deploymentInfo = originalDeployment.clone(); deploymentInfo.validate(); final DeploymentImpl deployment = new DeploymentImpl(deploymentInfo); this.deployment = deployment; final ServletContextImpl servletContext = new ServletContextImpl(servletContainer, deployment); deployment.setServletContext(servletContext); final List<ThreadSetupAction> setup = new ArrayList<ThreadSetupAction>(); setup.add(new ContextClassLoaderSetupAction(deploymentInfo.getClassLoader())); setup.addAll(deploymentInfo.getThreadSetupActions()); final CompositeThreadSetupAction threadSetupAction = new CompositeThreadSetupAction(setup); deployment.setThreadSetupAction(threadSetupAction); ThreadSetupAction.Handle handle = threadSetupAction.setup(null); try { final ApplicationListeners listeners = createListeners(); deployment.setApplicationListeners(listeners); //first run the SCI's for (final ServletContainerInitializerInfo sci : deploymentInfo.getServletContainerInitializers()) { final InstanceHandle<? extends ServletContainerInitializer> instance = sci.getInstanceFactory().createInstance(); try { instance.getInstance().onStartup(sci.getHandlesTypes(), servletContext); } finally { instance.release(); } } initializeErrorPages(deployment, deploymentInfo); initializeMimeMappings(deployment, deploymentInfo); initializeTempDir(servletContext, deploymentInfo); listeners.contextInitialized(); //run ServletPathMatches matches = setupServletChains(servletContext, threadSetupAction, listeners); deployment.setServletPaths(matches); HttpHandler wrappedHandlers = ServletDispatchingHandler.INSTANCE; wrappedHandlers = wrapHandlers(wrappedHandlers, deploymentInfo.getInnerHandlerChainWrappers()); HttpHandler securityHandler = setupSecurityHandlers(wrappedHandlers); wrappedHandlers = new PredicateHandler(DispatcherTypePredicate.REQUEST, securityHandler, wrappedHandlers); wrappedHandlers = wrapHandlers(wrappedHandlers, deploymentInfo.getOuterHandlerChainWrappers()); final ServletInitialHandler servletInitialHandler = new ServletInitialHandler(matches, wrappedHandlers, deployment.getThreadSetupAction(), servletContext); deployment.setServletHandler(servletInitialHandler); } catch (Exception e) { throw new RuntimeException(e); } finally { handle.tearDown(); } state = State.DEPLOYED; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "deploy"
"@Override public void deploy() { DeploymentInfo deploymentInfo = originalDeployment.clone(); deploymentInfo.validate(); final DeploymentImpl deployment = new DeploymentImpl(deploymentInfo); this.deployment = deployment; final ServletContextImpl servletContext = new ServletContextImpl(servletContainer, deployment); deployment.setServletContext(servletContext); final List<ThreadSetupAction> setup = new ArrayList<ThreadSetupAction>(); setup.add(new ContextClassLoaderSetupAction(deploymentInfo.getClassLoader())); setup.addAll(deploymentInfo.getThreadSetupActions()); final CompositeThreadSetupAction threadSetupAction = new CompositeThreadSetupAction(setup); deployment.setThreadSetupAction(threadSetupAction); ThreadSetupAction.Handle handle = threadSetupAction.setup(null); try { final ApplicationListeners listeners = createListeners(); deployment.setApplicationListeners(listeners); //first run the SCI's for (final ServletContainerInitializerInfo sci : deploymentInfo.getServletContainerInitializers()) { final InstanceHandle<? extends ServletContainerInitializer> instance = sci.getInstanceFactory().createInstance(); try { instance.getInstance().onStartup(sci.getHandlesTypes(), servletContext); } finally { instance.release(); } } <MASK>listeners.contextInitialized();</MASK> initializeErrorPages(deployment, deploymentInfo); initializeMimeMappings(deployment, deploymentInfo); initializeTempDir(servletContext, deploymentInfo); //run ServletPathMatches matches = setupServletChains(servletContext, threadSetupAction, listeners); deployment.setServletPaths(matches); HttpHandler wrappedHandlers = ServletDispatchingHandler.INSTANCE; wrappedHandlers = wrapHandlers(wrappedHandlers, deploymentInfo.getInnerHandlerChainWrappers()); HttpHandler securityHandler = setupSecurityHandlers(wrappedHandlers); wrappedHandlers = new PredicateHandler(DispatcherTypePredicate.REQUEST, securityHandler, wrappedHandlers); wrappedHandlers = wrapHandlers(wrappedHandlers, deploymentInfo.getOuterHandlerChainWrappers()); final ServletInitialHandler servletInitialHandler = new ServletInitialHandler(matches, wrappedHandlers, deployment.getThreadSetupAction(), servletContext); deployment.setServletHandler(servletInitialHandler); } catch (Exception e) { throw new RuntimeException(e); } finally { handle.tearDown(); } state = State.DEPLOYED; }"
Inversion-Mutation
megadiff
"private RemoteViews getExpandedView(RemoteViews remote, Status status, Bitmap art) { setupCommonViews(remote, status, art); remote.setViewVisibility(R.id.control_prev, View.VISIBLE); remote.setOnClickPendingIntent(R.id.control_prev, server.status().command.playback.pendingPrevious()); if(status == null || status.isStopped() || server.getAuthority() == null) { resetText(remote, R.id.text1, R.id.text2); return remote; } String fileName = status.getTrack().getName() != null ? status.getTrack().getName() : status.getTrack().getTitle(); Media track = parseMedia(status, fileName); String text2 = TextUtils.isEmpty(track.getMediaSecondText()) ? File.baseName(fileName) : track.getMediaSecondText(); remote.setTextViewText(R.id.title, track.getMediaHeading()); remote.setTextViewText(R.id.text1, track.getMediaFirstText()); remote.setTextViewText(R.id.text2, text2); return remote; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getExpandedView"
"private RemoteViews getExpandedView(RemoteViews remote, Status status, Bitmap art) { setupCommonViews(remote, status, art); remote.setOnClickPendingIntent(R.id.control_prev, server.status().command.playback.pendingPrevious()); if(status == null || status.isStopped() || server.getAuthority() == null) { resetText(remote, R.id.text1, R.id.text2); return remote; } String fileName = status.getTrack().getName() != null ? status.getTrack().getName() : status.getTrack().getTitle(); Media track = parseMedia(status, fileName); String text2 = TextUtils.isEmpty(track.getMediaSecondText()) ? File.baseName(fileName) : track.getMediaSecondText(); remote.setTextViewText(R.id.title, track.getMediaHeading()); remote.setTextViewText(R.id.text1, track.getMediaFirstText()); remote.setTextViewText(R.id.text2, text2); <MASK>remote.setViewVisibility(R.id.control_prev, View.VISIBLE);</MASK> return remote; }"
Inversion-Mutation
megadiff
"public int doStartTag() throws JspException { httpRequest = (HttpServletRequest) pageContext.getRequest(); requestContainer = ChannelUtilities.getRequestContainer(httpRequest); responseContainer = ChannelUtilities.getResponseContainer(httpRequest); urlBuilder = UrlBuilderFactory.getUrlBuilder(); msgBuilder = MessageBuilderFactory.getMessageBuilder(); currTheme=ThemesManager.getCurrentTheme(requestContainer); if(currTheme==null)currTheme=ThemesManager.getDefaultTheme(); TracerSingleton.log(SpagoBIConstants.NAME_MODULE, TracerSingleton.DEBUG, "ScriptWizardTag::doStartTag:: invocato"); RequestContainer aRequestContainer = RequestContainer.getRequestContainer(); SessionContainer aSessionContainer = aRequestContainer.getSessionContainer(); SessionContainer permanentSession = aSessionContainer.getPermanentContainer(); IEngUserProfile userProfile = (IEngUserProfile)permanentSession.getAttribute(IEngUserProfile.ENG_USER_PROFILE); boolean isable = false; try { isable = userProfile.isAbleToExecuteAction(SpagoBIConstants.LOVS_MANAGEMENT); } catch (EMFInternalError e) { // TODO Auto-generated catch block e.printStackTrace(); } if (isable){ isreadonly = false; readonly = ""; disabled = ""; } StringBuffer output = new StringBuffer(); String lanuageScriptLabel = msgBuilder.getMessage("SBISet.ListDataSet.languageScript", "messages", httpRequest); String scriptLabel = msgBuilder.getMessage("SBIDev.scriptWiz.scriptLbl", "messages", httpRequest); output.append("<table width='100%' cellspacing='0' border='0'>\n"); output.append(" <tr>\n"); output.append(" <td class='titlebar_level_2_text_section' style='vertical-align:middle;'>\n"); output.append(" &nbsp;&nbsp;&nbsp;"+ msgBuilder.getMessage("SBIDev.scriptWiz.wizardTitle", "messages", httpRequest) +"\n"); output.append(" </td>\n"); output.append(" <td class='titlebar_level_2_empty_section'>&nbsp;</td>\n"); output.append(" <td class='titlebar_level_2_button_section'>\n"); output.append(" <a style='text-decoration:none;' href='javascript:opencloseScriptWizardInfo()'> \n"); output.append(" <img width='22px' height='22px'\n"); output.append(" src='" + urlBuilder.getResourceLinkByTheme(httpRequest, "/img/info22.jpg",currTheme)+"'\n"); output.append(" name='info'\n"); output.append(" alt='"+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"'\n"); output.append(" title='"+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"'/>\n"); output.append(" </a>\n"); output.append(" </td>\n"); String urlImgProfAttr = urlBuilder.getResourceLinkByTheme(httpRequest, "/img/profileAttributes22.jpg",currTheme); output.append(generateProfAttrTitleSection(urlImgProfAttr)); output.append(" </tr>\n"); output.append("</table>\n"); output.append("<br/>\n"); output.append("<div class='div_detail_area_forms_lov'>\n"); //LANGUAGE SCRIPT COMBO output.append(" <div class='div_detail_label_lov'>\n"); output.append(" <span class='portlet-form-field-label'>\n"); output.append(lanuageScriptLabel); output.append(" </span>\n"); output.append(" </div>\n"); output.append(" <div class='div_detail_form'>\n"); output.append(" <select style='width:180px;' class='portlet-form-input-field' name='LANGUAGESCRIPT' id='LANGUAGESCRIPT' >\n"); try { List scriptLanguageList = DAOFactory.getDomainDAO().loadListDomainsByType(DataSetConstants.SCRIPT_TYPE); if(scriptLanguageList != null){ for(int i=0; i< scriptLanguageList.size(); i++){ Domain domain = (Domain)scriptLanguageList.get(i); String name = domain.getValueName(); name = StringEscapeUtils.escapeHtml(name); String value = domain.getValueCd(); value = StringEscapeUtils.escapeHtml(value); String selected=""; if(languageScript.equalsIgnoreCase(value)){ selected="selected='selected'"; } output.append("<option value='"+value+"' label='"+value+"' "+selected+">"); output.append(name); output.append("</option>"); } } } catch (Throwable e) { e.printStackTrace(); } /* Map engineNames=ScriptUtilities.getEngineFactoriesNames(); for(Iterator it=engineNames.keySet().iterator();it.hasNext();){ String engName=(String)it.next(); String alias=(String)engineNames.get(engName); alias = StringEscapeUtils.escapeHtml(alias); selected=""; if(languageScript.equalsIgnoreCase(alias)){ selected="selected='selected'"; } String aliasName=ScriptUtilities.bindAliasEngine(alias); output.append("<option value='"+alias+"' label='"+alias+"' "+selected+">"); output.append(aliasName); output.append("</option>"); } */ output.append("</select>"); output.append("</div>"); // FINE LANGUAGE SCRIPT output.append(" <div class='div_detail_label_lov'>\n"); output.append(" <span class='portlet-form-field-label'>\n"); output.append(scriptLabel); output.append(" </span>\n"); output.append(" </div>\n"); output.append(" <div style='height:110px;' class='div_detail_form'>\n"); output.append(" <textarea style='height:100px;' "+disabled+" class='portlet-text-area-field' name='SCRIPT' onchange='setLovProviderModified(true);' cols='50'>" + script + "</textarea>\n"); output.append(" </div>\n"); output.append(" <div class='div_detail_label_lov'>\n"); output.append(" &nbsp;\n"); output.append(" </div>\n"); // fine DETAIL AREA FORMS output.append("</div>\n"); output.append("<script>\n"); output.append(" var infowizardscriptopen = false;\n"); output.append(" var winSWT = null;\n"); output.append(" function opencloseScriptWizardInfo() {\n"); output.append(" if(!infowizardscriptopen){\n"); output.append(" infowizardscriptopen = true;"); output.append(" openScriptWizardInfo();\n"); output.append(" }\n"); output.append(" }\n"); output.append(" function openScriptWizardInfo(){\n"); output.append(" if(winSWT==null) {\n"); output.append(" winSWT = new Window('winSWTInfo', {className: \"alphacube\", title:\""+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"\",width:680, height:150, destroyOnClose: false});\n"); output.append(" winSWT.setContent('scriptwizardinfodiv', true, false);\n"); output.append(" winSWT.showCenter(false);\n"); output.append(" winSWT.setLocation(40,50);\n"); output.append(" } else {\n"); output.append(" winSWT.showCenter(false);\n"); output.append(" }\n"); output.append(" }\n"); output.append(" observerSWT = { onClose: function(eventName, win) {\n"); output.append(" if (win == winSWT) {\n"); output.append(" infowizardscriptopen = false;"); output.append(" }\n"); output.append(" }\n"); output.append(" }\n"); output.append(" Windows.addObserver(observerSWT);\n"); output.append("</script>\n"); output.append("<div id='scriptwizardinfodiv' style='display:none;'>\n"); output.append(msgBuilder.getMessageTextFromResource("it/eng/spagobi/commons/presentation/tags/info/scriptwizardinfo", httpRequest)); output.append("</div>\n"); try { pageContext.getOut().print(output.toString()); } catch (Exception ex) { TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.CRITICAL, "ScriptWizardTag::doStartTag::", ex); throw new JspException(ex.getMessage()); } return SKIP_BODY; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doStartTag"
"public int doStartTag() throws JspException { httpRequest = (HttpServletRequest) pageContext.getRequest(); requestContainer = ChannelUtilities.getRequestContainer(httpRequest); responseContainer = ChannelUtilities.getResponseContainer(httpRequest); urlBuilder = UrlBuilderFactory.getUrlBuilder(); msgBuilder = MessageBuilderFactory.getMessageBuilder(); currTheme=ThemesManager.getCurrentTheme(requestContainer); if(currTheme==null)currTheme=ThemesManager.getDefaultTheme(); TracerSingleton.log(SpagoBIConstants.NAME_MODULE, TracerSingleton.DEBUG, "ScriptWizardTag::doStartTag:: invocato"); RequestContainer aRequestContainer = RequestContainer.getRequestContainer(); SessionContainer aSessionContainer = aRequestContainer.getSessionContainer(); SessionContainer permanentSession = aSessionContainer.getPermanentContainer(); IEngUserProfile userProfile = (IEngUserProfile)permanentSession.getAttribute(IEngUserProfile.ENG_USER_PROFILE); boolean isable = false; try { isable = userProfile.isAbleToExecuteAction(SpagoBIConstants.LOVS_MANAGEMENT); } catch (EMFInternalError e) { // TODO Auto-generated catch block e.printStackTrace(); } if (isable){ isreadonly = false; readonly = ""; disabled = ""; } StringBuffer output = new StringBuffer(); String lanuageScriptLabel = msgBuilder.getMessage("SBISet.ListDataSet.languageScript", "messages", httpRequest); String scriptLabel = msgBuilder.getMessage("SBIDev.scriptWiz.scriptLbl", "messages", httpRequest); output.append("<table width='100%' cellspacing='0' border='0'>\n"); output.append(" <tr>\n"); output.append(" <td class='titlebar_level_2_text_section' style='vertical-align:middle;'>\n"); output.append(" &nbsp;&nbsp;&nbsp;"+ msgBuilder.getMessage("SBIDev.scriptWiz.wizardTitle", "messages", httpRequest) +"\n"); output.append(" </td>\n"); output.append(" <td class='titlebar_level_2_empty_section'>&nbsp;</td>\n"); output.append(" <td class='titlebar_level_2_button_section'>\n"); output.append(" <a style='text-decoration:none;' href='javascript:opencloseScriptWizardInfo()'> \n"); output.append(" <img width='22px' height='22px'\n"); output.append(" src='" + urlBuilder.getResourceLinkByTheme(httpRequest, "/img/info22.jpg",currTheme)+"'\n"); output.append(" name='info'\n"); output.append(" alt='"+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"'\n"); output.append(" title='"+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"'/>\n"); output.append(" </a>\n"); output.append(" </td>\n"); String urlImgProfAttr = urlBuilder.getResourceLinkByTheme(httpRequest, "/img/profileAttributes22.jpg",currTheme); output.append(generateProfAttrTitleSection(urlImgProfAttr)); output.append(" </tr>\n"); output.append("</table>\n"); output.append("<br/>\n"); output.append("<div class='div_detail_area_forms_lov'>\n"); //LANGUAGE SCRIPT COMBO output.append(" <div class='div_detail_label_lov'>\n"); output.append(" <span class='portlet-form-field-label'>\n"); output.append(lanuageScriptLabel); output.append(" </span>\n"); output.append(" </div>\n"); output.append(" <div class='div_detail_form'>\n"); output.append(" <select style='width:180px;' class='portlet-form-input-field' name='LANGUAGESCRIPT' id='LANGUAGESCRIPT' >\n"); <MASK>String selected="";</MASK> try { List scriptLanguageList = DAOFactory.getDomainDAO().loadListDomainsByType(DataSetConstants.SCRIPT_TYPE); if(scriptLanguageList != null){ for(int i=0; i< scriptLanguageList.size(); i++){ Domain domain = (Domain)scriptLanguageList.get(i); String name = domain.getValueName(); name = StringEscapeUtils.escapeHtml(name); String value = domain.getValueCd(); value = StringEscapeUtils.escapeHtml(value); if(languageScript.equalsIgnoreCase(value)){ selected="selected='selected'"; } output.append("<option value='"+value+"' label='"+value+"' "+selected+">"); output.append(name); output.append("</option>"); } } } catch (Throwable e) { e.printStackTrace(); } /* Map engineNames=ScriptUtilities.getEngineFactoriesNames(); for(Iterator it=engineNames.keySet().iterator();it.hasNext();){ String engName=(String)it.next(); String alias=(String)engineNames.get(engName); alias = StringEscapeUtils.escapeHtml(alias); selected=""; if(languageScript.equalsIgnoreCase(alias)){ selected="selected='selected'"; } String aliasName=ScriptUtilities.bindAliasEngine(alias); output.append("<option value='"+alias+"' label='"+alias+"' "+selected+">"); output.append(aliasName); output.append("</option>"); } */ output.append("</select>"); output.append("</div>"); // FINE LANGUAGE SCRIPT output.append(" <div class='div_detail_label_lov'>\n"); output.append(" <span class='portlet-form-field-label'>\n"); output.append(scriptLabel); output.append(" </span>\n"); output.append(" </div>\n"); output.append(" <div style='height:110px;' class='div_detail_form'>\n"); output.append(" <textarea style='height:100px;' "+disabled+" class='portlet-text-area-field' name='SCRIPT' onchange='setLovProviderModified(true);' cols='50'>" + script + "</textarea>\n"); output.append(" </div>\n"); output.append(" <div class='div_detail_label_lov'>\n"); output.append(" &nbsp;\n"); output.append(" </div>\n"); // fine DETAIL AREA FORMS output.append("</div>\n"); output.append("<script>\n"); output.append(" var infowizardscriptopen = false;\n"); output.append(" var winSWT = null;\n"); output.append(" function opencloseScriptWizardInfo() {\n"); output.append(" if(!infowizardscriptopen){\n"); output.append(" infowizardscriptopen = true;"); output.append(" openScriptWizardInfo();\n"); output.append(" }\n"); output.append(" }\n"); output.append(" function openScriptWizardInfo(){\n"); output.append(" if(winSWT==null) {\n"); output.append(" winSWT = new Window('winSWTInfo', {className: \"alphacube\", title:\""+msgBuilder.getMessage("SBIDev.scriptWiz.showSintax", "messages", httpRequest)+"\",width:680, height:150, destroyOnClose: false});\n"); output.append(" winSWT.setContent('scriptwizardinfodiv', true, false);\n"); output.append(" winSWT.showCenter(false);\n"); output.append(" winSWT.setLocation(40,50);\n"); output.append(" } else {\n"); output.append(" winSWT.showCenter(false);\n"); output.append(" }\n"); output.append(" }\n"); output.append(" observerSWT = { onClose: function(eventName, win) {\n"); output.append(" if (win == winSWT) {\n"); output.append(" infowizardscriptopen = false;"); output.append(" }\n"); output.append(" }\n"); output.append(" }\n"); output.append(" Windows.addObserver(observerSWT);\n"); output.append("</script>\n"); output.append("<div id='scriptwizardinfodiv' style='display:none;'>\n"); output.append(msgBuilder.getMessageTextFromResource("it/eng/spagobi/commons/presentation/tags/info/scriptwizardinfo", httpRequest)); output.append("</div>\n"); try { pageContext.getOut().print(output.toString()); } catch (Exception ex) { TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.CRITICAL, "ScriptWizardTag::doStartTag::", ex); throw new JspException(ex.getMessage()); } return SKIP_BODY; }"
Inversion-Mutation
megadiff
"public void execute(Connection conn) { try { PreparedStatement s = conn.prepareStatement(query); if (params != null) { for (ISetter setter : params) { s = setter.set(s); } } for (PreparedStatementExecutionItem ei : executionItems) s = ei.addToBatch(s); if (query.toLowerCase().startsWith("select")) { resultSet = s.executeQuery(); } else { if (executionItems.isEmpty()) s.execute(); else s.executeBatch(); s.close(); } } catch (SQLException e) { System.err.println("===> Batch start"); this.print(); for (PreparedStatementExecutionItem ei : this.executionItems) ei.print(); System.err.println("===> Batch end"); e.printStackTrace(); } for (PreparedStatementExecutionItem ei : executionItems) ei.wasExecuted = true; wasExecuted = true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute"
"public void execute(Connection conn) { try { PreparedStatement s = conn.prepareStatement(query); if (params != null) { for (ISetter setter : params) { s = setter.set(s); } } for (PreparedStatementExecutionItem ei : executionItems) s = ei.addToBatch(s); if (query.toLowerCase().startsWith("select")) { resultSet = s.executeQuery(); } else { if (executionItems.isEmpty()) s.execute(); else s.executeBatch(); } <MASK>s.close();</MASK> } catch (SQLException e) { System.err.println("===> Batch start"); this.print(); for (PreparedStatementExecutionItem ei : this.executionItems) ei.print(); System.err.println("===> Batch end"); e.printStackTrace(); } for (PreparedStatementExecutionItem ei : executionItems) ei.wasExecuted = true; wasExecuted = true; }"
Inversion-Mutation
megadiff
"@Test public void testLogMonitorController() { sleep(3000); logMonitorController.enableVerbose(false); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < 100; i++) { buffer.append("===================================="); } CoreLogger.LOGGER.info(buffer.toString()); CoreLogger.LOGGER.info("Core Logger"); LOGGER.debug("TEST TEST"); sleep(1000); //if logMonitorController.enableVerbose(false), it will check system setting. boolean isDebug = config.getSystemProperties().getPropertyBoolean("verbose", false); if (!isDebug) { assertThat(getLastMessage(), not(containsString("TEST TEST"))); } CoreLogger.LOGGER.info("Core Logger"); sleep(1000); assertThat(getLastMessage(), containsString("Core Logger")); logMonitorController.enableVerbose(true); LOGGER.debug("TEST TEST"); sleep(3000); assertThat(getLastMessage(), containsString("TEST TEST")); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testLogMonitorController"
"@Test public void testLogMonitorController() { logMonitorController.enableVerbose(false); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < 100; i++) { buffer.append("===================================="); } CoreLogger.LOGGER.info(buffer.toString()); CoreLogger.LOGGER.info("Core Logger"); <MASK>sleep(3000);</MASK> LOGGER.debug("TEST TEST"); sleep(1000); //if logMonitorController.enableVerbose(false), it will check system setting. boolean isDebug = config.getSystemProperties().getPropertyBoolean("verbose", false); if (!isDebug) { assertThat(getLastMessage(), not(containsString("TEST TEST"))); } CoreLogger.LOGGER.info("Core Logger"); sleep(1000); assertThat(getLastMessage(), containsString("Core Logger")); logMonitorController.enableVerbose(true); LOGGER.debug("TEST TEST"); <MASK>sleep(3000);</MASK> assertThat(getLastMessage(), containsString("TEST TEST")); }"
Inversion-Mutation
megadiff
"public int getTotal() { int amount = 0; for (Subpot pot : subpots) { amount += pot.getTotal(); // Add restAmount here, since Subpot does not know number of members amount += (members.size() - pot.cases.size()) * pot.restAmount; } amount += tip; return amount; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getTotal"
"public int getTotal() { int amount = 0; for (Subpot pot : subpots) { amount += pot.getTotal(); // Add restAmount here, since Subpot does not know number of members amount += (members.size() - pot.cases.size()) * pot.restAmount; <MASK>amount += tip;</MASK> } return amount; }"
Inversion-Mutation
megadiff
"@Override public void handleMessage(Message msg) { BluetoothAudioGateway.IncomingConnectionInfo info = (BluetoothAudioGateway.IncomingConnectionInfo)msg.obj; int type = BluetoothHandsfree.TYPE_UNKNOWN; switch(msg.what) { case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION: type = BluetoothHandsfree.TYPE_HEADSET; break; case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION: type = BluetoothHandsfree.TYPE_HANDSFREE; break; } Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) + ") connection from " + info.mRemoteDevice + "on channel " + info.mRfcommChan); int priority = BluetoothHeadset.PRIORITY_OFF; HeadsetBase headset; try { priority = mBinder.getPriority(info.mRemoteDevice); } catch (RemoteException e) {} if (priority <= BluetoothHeadset.PRIORITY_OFF) { Log.i(TAG, "Rejecting incoming connection because priority = " + priority); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); return; } switch (mState) { case BluetoothHeadset.STATE_DISCONNECTED: // headset connecting us, lets join mRemoteDevice = info.mRemoteDevice; setState(BluetoothHeadset.STATE_CONNECTING); headset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget(); break; case BluetoothHeadset.STATE_CONNECTING: if (!info.mRemoteDevice.equals(mRemoteDevice)) { // different headset, ignoring Log.i(TAG, "Already attempting connect to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); } // If we are here, we are in danger of a race condition // incoming rfcomm connection, but we are also attempting an // outgoing connection. Lets try and interrupt the outgoing // connection. Log.i(TAG, "Incoming and outgoing connections to " + info.mRemoteDevice + ". Cancel outgoing connection."); if (mConnectThread != null) { mConnectThread.interrupt(); } // Now continue with new connection, including calling callback mHeadset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; setState(BluetoothHeadset.STATE_CONNECTED, BluetoothHeadset.RESULT_SUCCESS); mBtHandsfree.connectHeadset(mHeadset, mHeadsetType); // Make sure that old outgoing connect thread is dead. if (mConnectThread != null) { try { // TODO: Don't block in the main thread Log.w(TAG, "Block in main thread to join stale outgoing connection thread"); mConnectThread.join(); } catch (InterruptedException e) { Log.e(TAG, "Connection cancelled twice eh?", e); } mConnectThread = null; } if (DBG) log("Successfully used incoming connection, and cancelled outgoing " + " connection"); break; case BluetoothHeadset.STATE_CONNECTED: Log.i(TAG, "Already connected to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); break; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleMessage"
"@Override public void handleMessage(Message msg) { BluetoothAudioGateway.IncomingConnectionInfo info = (BluetoothAudioGateway.IncomingConnectionInfo)msg.obj; int type = BluetoothHandsfree.TYPE_UNKNOWN; switch(msg.what) { case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION: type = BluetoothHandsfree.TYPE_HEADSET; break; case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION: type = BluetoothHandsfree.TYPE_HANDSFREE; break; } Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) + ") connection from " + info.mRemoteDevice + "on channel " + info.mRfcommChan); int priority = BluetoothHeadset.PRIORITY_OFF; HeadsetBase headset; try { priority = mBinder.getPriority(info.mRemoteDevice); } catch (RemoteException e) {} if (priority <= BluetoothHeadset.PRIORITY_OFF) { Log.i(TAG, "Rejecting incoming connection because priority = " + priority); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); return; } switch (mState) { case BluetoothHeadset.STATE_DISCONNECTED: // headset connecting us, lets join <MASK>setState(BluetoothHeadset.STATE_CONNECTING);</MASK> mRemoteDevice = info.mRemoteDevice; headset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget(); break; case BluetoothHeadset.STATE_CONNECTING: if (!info.mRemoteDevice.equals(mRemoteDevice)) { // different headset, ignoring Log.i(TAG, "Already attempting connect to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); } // If we are here, we are in danger of a race condition // incoming rfcomm connection, but we are also attempting an // outgoing connection. Lets try and interrupt the outgoing // connection. Log.i(TAG, "Incoming and outgoing connections to " + info.mRemoteDevice + ". Cancel outgoing connection."); if (mConnectThread != null) { mConnectThread.interrupt(); } // Now continue with new connection, including calling callback mHeadset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; setState(BluetoothHeadset.STATE_CONNECTED, BluetoothHeadset.RESULT_SUCCESS); mBtHandsfree.connectHeadset(mHeadset, mHeadsetType); // Make sure that old outgoing connect thread is dead. if (mConnectThread != null) { try { // TODO: Don't block in the main thread Log.w(TAG, "Block in main thread to join stale outgoing connection thread"); mConnectThread.join(); } catch (InterruptedException e) { Log.e(TAG, "Connection cancelled twice eh?", e); } mConnectThread = null; } if (DBG) log("Successfully used incoming connection, and cancelled outgoing " + " connection"); break; case BluetoothHeadset.STATE_CONNECTED: Log.i(TAG, "Already connected to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); break; } }"
Inversion-Mutation
megadiff
"public void destroy() { // the following doesn't fully clean up (maybe because of Java3D?) WindowManager wm = (WindowManager) getManager(WindowManager.class); wm.hideWindows(); setVisible(false); wm.disposeWindows(); StateManager sm = (StateManager) getManager(StateManager.class); sm.destroy(); instanceServer.stop(); dispose(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "destroy"
"public void destroy() { // the following doesn't fully clean up (maybe because of Java3D?) WindowManager wm = (WindowManager) getManager(WindowManager.class); wm.hideWindows(); <MASK>wm.disposeWindows();</MASK> setVisible(false); StateManager sm = (StateManager) getManager(StateManager.class); sm.destroy(); instanceServer.stop(); dispose(); }"
Inversion-Mutation
megadiff
"private void selectableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_selectableMouseClicked if (evt.getClickCount() >= 2) { // Double click or faster DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectable.getLastSelectedPathComponent(); if (node != null) { String nodeInfo = (String) node.getUserObject(); if (node.isLeaf()) { Debug.println("Adding a: " + nodeInfo); furnitureTypeController.select(nodeInfo); } updateSelected(); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "selectableMouseClicked"
"private void selectableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_selectableMouseClicked if (evt.getClickCount() >= 2) { // Double click or faster DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectable.getLastSelectedPathComponent(); if (node != null) { String nodeInfo = (String) node.getUserObject(); <MASK>Debug.println("Adding a: " + nodeInfo);</MASK> if (node.isLeaf()) { furnitureTypeController.select(nodeInfo); } updateSelected(); } } }"
Inversion-Mutation
megadiff
"private SimpleFieldSet handleGetIdentitiesByScore(final SimpleFieldSet params) throws InvalidParameterException, UnknownIdentityException { final String treeOwnerID = params.get("TreeOwner"); final String selection = getMandatoryParameter(params, "Selection"); final String context = getMandatoryParameter(params, "Context"); final String selectString = selection.trim(); int select = 0; // TODO: decide about the default value if (selectString.equals("+")) select = 1; else if (selectString.equals("-")) select = -1; else if (selectString.equals("0")) select = 0; else throw new InvalidParameterException("Unhandled selection value (" + select + ")"); final SimpleFieldSet sfs = new SimpleFieldSet(true); sfs.putOverwrite("Message", "Identities"); synchronized(mWoT) { final OwnIdentity treeOwner = treeOwnerID != null ? mWoT.getOwnIdentityByID(treeOwnerID) : null; final ObjectSet<Score> result = mWoT.getIdentitiesByScore(treeOwner, select); final boolean getAll = context.equals(""); for(int i = 0; result.hasNext(); ) { final Score score = result.next(); if(getAll || score.getTarget().hasContext(context)) { final Identity identity = score.getTarget(); sfs.putOverwrite("Identity" + i, identity.getID()); sfs.putOverwrite("RequestURI" + i, identity.getRequestURI().toString()); sfs.putOverwrite("Nickname" + i, identity.getNickname() != null ? identity.getNickname() : ""); int contextCounter = 0; for (String identityContext: identity.getContexts()) { sfs.putOverwrite("Contexts" + i + ".Context" + contextCounter++, identityContext); } int propertiesCounter = 0; for (Entry<String, String> property : identity.getProperties().entrySet()) { sfs.putOverwrite("Properties" + i + ".Property" + propertiesCounter + ".Name", property.getKey()); sfs.putOverwrite("Properties" + i + ".Property" + propertiesCounter++ + ".Value", property.getValue()); } // TODO: Allow the client to select what data he wants ++i; } } } return sfs; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleGetIdentitiesByScore"
"private SimpleFieldSet handleGetIdentitiesByScore(final SimpleFieldSet params) throws InvalidParameterException, UnknownIdentityException { final String treeOwnerID = params.get("TreeOwner"); final String selection = getMandatoryParameter(params, "Selection"); final String context = getMandatoryParameter(params, "Context"); final String selectString = selection.trim(); int select = 0; // TODO: decide about the default value if (selectString.equals("+")) select = 1; else if (selectString.equals("-")) select = -1; else if (selectString.equals("0")) select = 0; else throw new InvalidParameterException("Unhandled selection value (" + select + ")"); final SimpleFieldSet sfs = new SimpleFieldSet(true); sfs.putOverwrite("Message", "Identities"); synchronized(mWoT) { final OwnIdentity treeOwner = treeOwnerID != null ? mWoT.getOwnIdentityByID(treeOwnerID) : null; final ObjectSet<Score> result = mWoT.getIdentitiesByScore(treeOwner, select); final boolean getAll = context.equals(""); for(int i = 0; result.hasNext(); ) { final Score score = result.next(); if(getAll || score.getTarget().hasContext(context)) { final Identity identity = score.getTarget(); sfs.putOverwrite("Identity" + i, identity.getID()); sfs.putOverwrite("RequestURI" + i, identity.getRequestURI().toString()); sfs.putOverwrite("Nickname" + i, identity.getNickname() != null ? identity.getNickname() : ""); <MASK>++i;</MASK> int contextCounter = 0; for (String identityContext: identity.getContexts()) { sfs.putOverwrite("Contexts" + i + ".Context" + contextCounter++, identityContext); } int propertiesCounter = 0; for (Entry<String, String> property : identity.getProperties().entrySet()) { sfs.putOverwrite("Properties" + i + ".Property" + propertiesCounter + ".Name", property.getKey()); sfs.putOverwrite("Properties" + i + ".Property" + propertiesCounter++ + ".Value", property.getValue()); } // TODO: Allow the client to select what data he wants } } } return sfs; }"
Inversion-Mutation
megadiff
"public String rewriteResourceURL(String path, String resourcebase) { String resourceURL = null; if (!URLUtil.isAbsolute(path) && path.charAt(0) != '/') { if (isContextURL(path)) { resourceURL = rewriteContextURL(path); } else { resourceURL = viewstatehandler.encodeResourceURL(resourcebase + path); } resourceURL = StringUtils.cleanPath(resourceURL); } if (Logger.log.isDebugEnabled()) { Logger.log.debug("getResourceURL returning " + resourceURL + " for path " + path); } return resourceURL; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "rewriteResourceURL"
"public String rewriteResourceURL(String path, String resourcebase) { String resourceURL = null; if (!URLUtil.isAbsolute(path) && path.charAt(0) != '/') { if (isContextURL(path)) { resourceURL = rewriteContextURL(path); } else { resourceURL = viewstatehandler.encodeResourceURL(resourcebase + path); } } <MASK>resourceURL = StringUtils.cleanPath(resourceURL);</MASK> if (Logger.log.isDebugEnabled()) { Logger.log.debug("getResourceURL returning " + resourceURL + " for path " + path); } return resourceURL; }"
Inversion-Mutation
megadiff
"public boolean send(Object data, boolean close) throws IOException { if (closedRan.get()) { return false; } if (isWebSocket()) { if (data instanceof Map) { // only get the :body if map Object tmp = ((Map<Keyword, Object>) data).get(BODY); if (tmp != null) { // save contains(BODY) && get(BODY) data = tmp; } } if (data instanceof String) { // null is not allowed write(WSEncoder.encode(OPCODE_TEXT, ((String) data).getBytes(UTF_8))); } else if (data instanceof byte[]) { write(WSEncoder.encode(OPCODE_BINARY, (byte[]) data)); } else if (data instanceof InputStream) { DynamicBytes bytes = readAll((InputStream) data); write(WSEncoder.encode(OPCODE_BINARY, bytes.get(), bytes.length())); } else if (data != null) { // ignore null throw new IllegalArgumentException( "only accept string, byte[], InputStream, get" + data); } if (close) { serverClose(1000); } } else { if (isHeaderSent) { writeChunk(data, close); } else { isHeaderSent = true; firstWrite(data, close); } } return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "send"
"public boolean send(Object data, boolean close) throws IOException { if (closedRan.get()) { return false; } if (isWebSocket()) { if (data instanceof Map) { // only get the :body if map Object tmp = ((Map<Keyword, Object>) data).get(BODY); if (tmp != null) { // save contains(BODY) && get(BODY) data = tmp; } } if (data instanceof String) { // null is not allowed write(WSEncoder.encode(OPCODE_TEXT, ((String) data).getBytes(UTF_8))); } else if (data instanceof byte[]) { write(WSEncoder.encode(OPCODE_BINARY, (byte[]) data)); } else if (data instanceof InputStream) { DynamicBytes bytes = readAll((InputStream) data); write(WSEncoder.encode(OPCODE_BINARY, bytes.get(), bytes.length())); } else if (data != null) { // ignore null throw new IllegalArgumentException( "only accept string, byte[], InputStream, get" + data); } if (close) { serverClose(1000); } } else { if (isHeaderSent) { writeChunk(data, close); } else { <MASK>firstWrite(data, close);</MASK> isHeaderSent = true; } } return true; }"
Inversion-Mutation
megadiff
"protected void tearDown() throws Exception { this.region.close(); super.tearDown(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "tearDown"
"protected void tearDown() throws Exception { <MASK>super.tearDown();</MASK> this.region.close(); }"
Inversion-Mutation
megadiff
"protected RelNode toLenientRel( RelOptCluster cluster, RelNode child, RelDataType targetRowType, RelDataType srcRowType) { ArrayList<RexNode> rexNodeList = new ArrayList(); RexBuilder rexBuilder = cluster.getRexBuilder(); FarragoWarningQueue warningQueue = getPreparingStmt().getStmtValidator().getWarningQueue(); String objectName = this.localName[this.localName.length-1]; HashMap<String, RelDataType> srcMap = new HashMap(); for (RelDataTypeField srcField : srcRowType.getFieldList()) { srcMap.put(srcField.getName(), srcField.getType()); } ArrayList<String> allTargetFields = new ArrayList(); int index = 0; for (RelDataTypeField targetField : targetRowType.getFieldList()) { allTargetFields.add(targetField.getName()); RelDataType type; if ((type = srcMap.get(targetField.getName())) != null) { if (type != targetField.getType()) { // field type cast warningQueue.postWarning( FarragoResource.instance().TypeChangeWarning.ex( objectName, targetField.getName(), type.toString(), targetField.getType().toString())); } rexNodeList.add(new RexInputRef(index, targetField.getType())); } else { // field in target not in child // check if type-incompatibility between source and target if ((type = srcMap.get(targetField.getName())) != null) { warningQueue.postWarning(FarragoResource.instance(). IncompatibleTypeChangeWarning.ex( objectName, targetField.getName(), type.toString(), targetField.getType().toString())); } else { // field in target has been deleted in source RelDataType targetType = targetField.getType(); rexNodeList.add( rexBuilder.makeCast( targetType, rexBuilder.constantNull())); warningQueue.postWarning( FarragoResource.instance().DeletedFieldWarning.ex( objectName, targetField.getName())); } } index++; } // check if data source has added fields for (String srcField : srcMap.keySet()) { if (!allTargetFields.contains(srcField)) { warningQueue.postWarning( FarragoResource.instance().AddedFieldWarning.ex( objectName, srcField)); } } // create a new RelNode. RelNode calcRel = CalcRel.createProject( child, rexNodeList, null); return RelOptUtil.createCastRel( calcRel, targetRowType, true); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "toLenientRel"
"protected RelNode toLenientRel( RelOptCluster cluster, RelNode child, RelDataType targetRowType, RelDataType srcRowType) { ArrayList<RexNode> rexNodeList = new ArrayList(); RexBuilder rexBuilder = cluster.getRexBuilder(); FarragoWarningQueue warningQueue = getPreparingStmt().getStmtValidator().getWarningQueue(); String objectName = this.localName[this.localName.length-1]; HashMap<String, RelDataType> srcMap = new HashMap(); for (RelDataTypeField srcField : srcRowType.getFieldList()) { srcMap.put(srcField.getName(), srcField.getType()); } ArrayList<String> allTargetFields = new ArrayList(); for (RelDataTypeField targetField : targetRowType.getFieldList()) { <MASK>int index = 0;</MASK> allTargetFields.add(targetField.getName()); RelDataType type; if ((type = srcMap.get(targetField.getName())) != null) { if (type != targetField.getType()) { // field type cast warningQueue.postWarning( FarragoResource.instance().TypeChangeWarning.ex( objectName, targetField.getName(), type.toString(), targetField.getType().toString())); } rexNodeList.add(new RexInputRef(index, targetField.getType())); } else { // field in target not in child // check if type-incompatibility between source and target if ((type = srcMap.get(targetField.getName())) != null) { warningQueue.postWarning(FarragoResource.instance(). IncompatibleTypeChangeWarning.ex( objectName, targetField.getName(), type.toString(), targetField.getType().toString())); } else { // field in target has been deleted in source RelDataType targetType = targetField.getType(); rexNodeList.add( rexBuilder.makeCast( targetType, rexBuilder.constantNull())); warningQueue.postWarning( FarragoResource.instance().DeletedFieldWarning.ex( objectName, targetField.getName())); } } index++; } // check if data source has added fields for (String srcField : srcMap.keySet()) { if (!allTargetFields.contains(srcField)) { warningQueue.postWarning( FarragoResource.instance().AddedFieldWarning.ex( objectName, srcField)); } } // create a new RelNode. RelNode calcRel = CalcRel.createProject( child, rexNodeList, null); return RelOptUtil.createCastRel( calcRel, targetRowType, true); }"
Inversion-Mutation
megadiff
"public static Test suite() { TestSuite suite = new TestSuite("Test for org.eclipse.mylyn.tests"); StatusHandler.addStatusHandler(new TestingStatusNotifier()); // ResourcesUiBridgePlugin.getDefault().setResourceMonitoringEnabled(false); // TODO: the order of these tests might still matter, but shouldn't // $JUnit-BEGIN$ suite.addTest(AllContextTests.suite()); suite.addTest(AllJavaTests.suite()); suite.addTest(AllMonitorTests.suite()); suite.addTest(AllIntegrationTests.suite()); suite.addTest(AllIdeTests.suite()); suite.addTest(AllTasksTests.suite()); suite.addTest(AllResourcesTests.suite()); suite.addTest(AllBugzillaTests.suite()); suite.addTest(AllMiscTests.suite()); suite.addTest(AllJiraTests.suite()); suite.addTest(AllTracTests.suite()); suite.addTestSuite(WebClientUtilTest.class); suite.addTestSuite(SslProtocolSocketFactoryTest.class); // $JUnit-END$ return suite; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "suite"
"public static Test suite() { TestSuite suite = new TestSuite("Test for org.eclipse.mylyn.tests"); StatusHandler.addStatusHandler(new TestingStatusNotifier()); // ResourcesUiBridgePlugin.getDefault().setResourceMonitoringEnabled(false); // TODO: the order of these tests might still matter, but shouldn't // $JUnit-BEGIN$ suite.addTest(AllJavaTests.suite()); suite.addTest(AllMonitorTests.suite()); suite.addTest(AllIntegrationTests.suite()); <MASK>suite.addTest(AllContextTests.suite());</MASK> suite.addTest(AllIdeTests.suite()); suite.addTest(AllTasksTests.suite()); suite.addTest(AllResourcesTests.suite()); suite.addTest(AllBugzillaTests.suite()); suite.addTest(AllMiscTests.suite()); suite.addTest(AllJiraTests.suite()); suite.addTest(AllTracTests.suite()); suite.addTestSuite(WebClientUtilTest.class); suite.addTestSuite(SslProtocolSocketFactoryTest.class); // $JUnit-END$ return suite; }"
Inversion-Mutation
megadiff
"private static void printUsage() { System.err.println("Utility to push analysis results to LIMS"); System.err.println(); System.err.println("Usage. Specify the following commannd line parameters :"); System.err.println(); System.err.println("DBName NewState FCLaneBarcode Key=value..."); System.err.println(" DBName : LIMS database name"); System.err.println(" NewState : New result state"); System.err.print(" e.g. ANALYSIS_FINISHED, SEQUENCE_FINISHED, "); System.err.println("UNIQUE_PERCENT_FINISHED, CAPTURE_FINISHED"); System.err.println(" FCLaneBarcode : Flowcell Lane barcode"); System.err.println(" e.g. 70EMPAAXX-5-ID01"); System.err.print(" Key=value : Collection of key value pairs to be uploaded"); System.err.println(" as results to LIMS"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "printUsage"
"private static void printUsage() { System.err.println("Utility to push analysis results to LIMS"); System.err.println(); System.err.println("Usage. Specify the following commannd line parameters :"); System.err.println(); System.err.println("DBName NewState FCLaneBarcode Key=value..."); System.err.println(" DBName : LIMS database name"); System.err.println(" NewState : New result state"); System.err.print(" e.g. ANALYSIS_FINISHED, SEQUENCE_FINISHED, "); System.err.println(" FCLaneBarcode : Flowcell Lane barcode"); System.err.println(" e.g. 70EMPAAXX-5-ID01"); <MASK>System.err.println("UNIQUE_PERCENT_FINISHED, CAPTURE_FINISHED");</MASK> System.err.print(" Key=value : Collection of key value pairs to be uploaded"); System.err.println(" as results to LIMS"); }"
Inversion-Mutation
megadiff
"public void renderToSheet(SpriteSheet sheet, PaletteResource pal, int sx, int sy) { this.sheet = sheet; sheetX = sx; sheetY = sy; try { int bits = 0; int val = 0; int pos = 0; int pixel = 0; if (direction == ImageDirection.LEFT_RIGHT) { int xoffs = 8 / bpp - 1; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x += 8 / bpp) { val = decompressed.get(pos) & 0xff; xoffs = 8 / bpp - 1; bits = 8; while (x + xoffs >= width) { xoffs--; val >>= bpp; bits -= bpp; } while (bits > 0) { pixel = val & ((1 << bpp) - 1); val >>= bpp; bits -= bpp; sheet.drawPixel(xoffs + sx + x, sy + y, pal.r.get(pixel) .byteValue(), pal.g.get(pixel) .byteValue(), pal.b.get(pixel).byteValue()); xoffs--; } pos++; } } } else { int xoffs = 8 / bpp - 1; for (int x = 0; x < width; x += 8 / bpp) { val = decompressed.get(pos) & 0xff; bits = 8; for (int y = 0; y < height && xoffs >= 0;) { while (x + xoffs >= width) { xoffs--; val >>= bpp; bits -= bpp; } pixel = val & ((1 << bpp) - 1); val >>= bpp; bits -= bpp; sheet.drawPixel(xoffs + sx + x, sy + y, pal.r .get(pixel) .byteValue(), pal.g.get(pixel).byteValue(), pal.b.get(pixel).byteValue()); xoffs--; if (bits == 0) { pos++; val = decompressed.get(pos) & 0xff; bits = 8; y++; xoffs = 8 / bpp - 1; } } } } } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } System.out.println("Allocated at " + sx + ", " + sy); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "renderToSheet"
"public void renderToSheet(SpriteSheet sheet, PaletteResource pal, int sx, int sy) { this.sheet = sheet; sheetX = sx; sheetY = sy; try { int bits = 0; int val = 0; int pos = 0; int pixel = 0; if (direction == ImageDirection.LEFT_RIGHT) { int xoffs = 8 / bpp - 1; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x += 8 / bpp) { val = decompressed.get(pos) & 0xff; xoffs = 8 / bpp - 1; bits = 8; while (x + xoffs >= width) { xoffs--; val >>= bpp; bits -= bpp; } while (bits > 0) { pixel = val & ((1 << bpp) - 1); val >>= bpp; bits -= bpp; sheet.drawPixel(xoffs + sx + x, sy + y, pal.r.get(pixel) .byteValue(), pal.g.get(pixel) .byteValue(), pal.b.get(pixel).byteValue()); xoffs--; } <MASK>pos++;</MASK> } } } else { int xoffs = 8 / bpp - 1; for (int x = 0; x < width; x += 8 / bpp) { val = decompressed.get(pos) & 0xff; bits = 8; for (int y = 0; y < height && xoffs >= 0;) { while (x + xoffs >= width) { xoffs--; val >>= bpp; bits -= bpp; } pixel = val & ((1 << bpp) - 1); val >>= bpp; bits -= bpp; sheet.drawPixel(xoffs + sx + x, sy + y, pal.r .get(pixel) .byteValue(), pal.g.get(pixel).byteValue(), pal.b.get(pixel).byteValue()); xoffs--; if (bits == 0) { val = decompressed.get(pos) & 0xff; bits = 8; <MASK>pos++;</MASK> y++; xoffs = 8 / bpp - 1; } } } } } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } System.out.println("Allocated at " + sx + ", " + sy); }"
Inversion-Mutation
megadiff
"public boolean send(Object data, boolean close) throws IOException { if (closedRan.get()) { return false; } if (isWebSocket()) { if (data instanceof Map) { // only get the :body if map Object tmp = ((Map<Keyword, Object>) data).get(BODY); if (tmp != null) { // save contains(BODY) && get(BODY) data = tmp; } } if (data instanceof String) { // null is not allowed write(WSEncoder.encode(OPCODE_TEXT, ((String) data).getBytes(UTF_8))); } else if (data instanceof byte[]) { write(WSEncoder.encode(OPCODE_BINARY, (byte[]) data)); } else if (data instanceof InputStream) { DynamicBytes bytes = readAll((InputStream) data); write(WSEncoder.encode(OPCODE_BINARY, bytes.get(), bytes.length())); } else if (data != null) { // ignore null throw new IllegalArgumentException( "only accept string, byte[], InputStream, get" + data); } if (close) { serverClose(1000); } } else { if (isHeaderSent) { writeChunk(data, close); } else { isHeaderSent = true; firstWrite(data, close); } } return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "send"
"public boolean send(Object data, boolean close) throws IOException { if (closedRan.get()) { return false; } if (isWebSocket()) { if (data instanceof Map) { // only get the :body if map Object tmp = ((Map<Keyword, Object>) data).get(BODY); if (tmp != null) { // save contains(BODY) && get(BODY) data = tmp; } } if (data instanceof String) { // null is not allowed write(WSEncoder.encode(OPCODE_TEXT, ((String) data).getBytes(UTF_8))); } else if (data instanceof byte[]) { write(WSEncoder.encode(OPCODE_BINARY, (byte[]) data)); } else if (data instanceof InputStream) { DynamicBytes bytes = readAll((InputStream) data); write(WSEncoder.encode(OPCODE_BINARY, bytes.get(), bytes.length())); } else if (data != null) { // ignore null throw new IllegalArgumentException( "only accept string, byte[], InputStream, get" + data); } if (close) { serverClose(1000); } } else { if (isHeaderSent) { writeChunk(data, close); } else { <MASK>firstWrite(data, close);</MASK> isHeaderSent = true; } } return true; }"
Inversion-Mutation
megadiff
"private void createProject() { // get the target and try to resolve it. int targetId = mSdkCommandLine.getParamTargetId(); IAndroidTarget[] targets = mSdkManager.getTargets(); if (targetId < 1 || targetId > targets.length) { errorAndExit("Target id is not valid. Use '%s list targets' to get the target ids.", SdkConstants.androidCmdName()); } IAndroidTarget target = targets[targetId - 1]; ProjectCreator creator = new ProjectCreator(mSdkFolder, mSdkCommandLine.isVerbose() ? OutputLevel.VERBOSE : mSdkCommandLine.isSilent() ? OutputLevel.SILENT : OutputLevel.NORMAL, mSdkLog); String projectDir = getProjectLocation(mSdkCommandLine.getParamLocationPath()); String projectName = mSdkCommandLine.getParamName(); String packageName = mSdkCommandLine.getParamProjectPackage(); String activityName = mSdkCommandLine.getParamProjectActivity(); if (projectName != null && !ProjectCreator.RE_PROJECT_NAME.matcher(projectName).matches()) { errorAndExit( "Project name '%1$s' contains invalid characters.\nAllowed characters are: %2$s", projectName, ProjectCreator.CHARS_PROJECT_NAME); return; } if (activityName != null && !ProjectCreator.RE_ACTIVITY_NAME.matcher(activityName).matches()) { errorAndExit( "Activity name '%1$s' contains invalid characters.\nAllowed characters are: %2$s", activityName, ProjectCreator.CHARS_ACTIVITY_NAME); return; } if (packageName != null && !ProjectCreator.RE_PACKAGE_NAME.matcher(packageName).matches()) { errorAndExit( "Package name '%1$s' contains invalid characters.\n" + "A package name must be constitued of two Java identifiers.\n" + "Each identifier allowed characters are: %2$s", packageName, ProjectCreator.CHARS_PACKAGE_NAME); return; } creator.createProject(projectDir, projectName, packageName, activityName, target, false /* isTestProject*/); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createProject"
"private void createProject() { // get the target and try to resolve it. int targetId = mSdkCommandLine.getParamTargetId(); IAndroidTarget[] targets = mSdkManager.getTargets(); if (targetId < 1 || targetId > targets.length) { errorAndExit("Target id is not valid. Use '%s list targets' to get the target ids.", SdkConstants.androidCmdName()); } IAndroidTarget target = targets[targetId - 1]; ProjectCreator creator = new ProjectCreator(mSdkFolder, mSdkCommandLine.isVerbose() ? OutputLevel.VERBOSE : mSdkCommandLine.isSilent() ? OutputLevel.SILENT : OutputLevel.NORMAL, mSdkLog); String projectDir = getProjectLocation(mSdkCommandLine.getParamLocationPath()); String projectName = mSdkCommandLine.getParamName(); String packageName = mSdkCommandLine.getParamProjectPackage(); String activityName = mSdkCommandLine.getParamProjectActivity(); if (projectName != null && !ProjectCreator.RE_PROJECT_NAME.matcher(projectName).matches()) { errorAndExit( "Project name '%1$s' contains invalid characters.\nAllowed characters are: %2$s", projectName, ProjectCreator.CHARS_PROJECT_NAME); return; } if (activityName != null && !ProjectCreator.RE_ACTIVITY_NAME.matcher(activityName).matches()) { errorAndExit( "Activity name '%1$s' contains invalid characters.\nAllowed characters are: %2$s", <MASK>activityName,</MASK> ProjectCreator.CHARS_ACTIVITY_NAME); return; } if (packageName != null && !ProjectCreator.RE_PACKAGE_NAME.matcher(packageName).matches()) { errorAndExit( "Package name '%1$s' contains invalid characters.\n" + "A package name must be constitued of two Java identifiers.\n" + "Each identifier allowed characters are: %2$s", packageName, ProjectCreator.CHARS_PACKAGE_NAME); return; } creator.createProject(projectDir, projectName, <MASK>activityName,</MASK> packageName, target, false /* isTestProject*/); }"
Inversion-Mutation
megadiff
"public void record(final Player player, final Event event) { final long occured = System.currentTimeMillis(); this.last.put(player, occured); if (this.countObservers() == 0) return; this.setChanged(); this.notifyObservers(new PlayerEvent(player, event, occured)); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "record"
"public void record(final Player player, final Event event) { final long occured = System.currentTimeMillis(); this.last.put(player, occured); <MASK>this.setChanged();</MASK> if (this.countObservers() == 0) return; this.notifyObservers(new PlayerEvent(player, event, occured)); }"
Inversion-Mutation
megadiff
"@Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (bundle == null) return; Object[] pdus = (Object[]) bundle.get("pdus"); DBHelper helper = new DBHelper(context); for (int i = 0; i < pdus.length; i++) { SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdus[i]); SmsNotification notif = SmsParser.parse( sms.getDisplayOriginatingAddress(), sms.getDisplayMessageBody()); if (notif != null) { helper.saveCard(notif.card, notif.card, notif.balance); helper.addNotification(notif); } } CardListActivity.prepareCardsInfo(helper, helper.getCards()); helper.close(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onReceive"
"@Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (bundle == null) return; Object[] pdus = (Object[]) bundle.get("pdus"); DBHelper helper = new DBHelper(context); for (int i = 0; i < pdus.length; i++) { SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdus[i]); SmsNotification notif = SmsParser.parse( sms.getDisplayOriginatingAddress(), sms.getDisplayMessageBody()); if (notif != null) { helper.saveCard(notif.card, notif.card, notif.balance); helper.addNotification(notif); } } <MASK>helper.close();</MASK> CardListActivity.prepareCardsInfo(helper, helper.getCards()); }"
Inversion-Mutation
megadiff
"protected MaskedTextBox(TextBox textBox, Formatter formatter) { String id = textBox.getElement().getId(); if (id == null || id.length() == 0) { textBox.getElement().setId(generateNewId()); } this.textBox = textBox; this.textBox.setStyleName(DEFAULT_STYLE_NAME); setFormatter(formatter); initWidget(this.textBox); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "MaskedTextBox"
"protected MaskedTextBox(TextBox textBox, Formatter formatter) { String id = textBox.getElement().getId(); if (id == null || id.length() == 0) { textBox.getElement().setId(generateNewId()); } <MASK>setFormatter(formatter);</MASK> this.textBox = textBox; this.textBox.setStyleName(DEFAULT_STYLE_NAME); initWidget(this.textBox); }"
Inversion-Mutation
megadiff
"@Override protected String doInBackground(final Person whoAmI) { String serverResponse = null; try { final JSONObject boardJSON = board.makeJSON(); final String boardJSONString = boardJSON.toString(); final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair(ServerUtilities.POST_DATA_USER_CREATOR, whoAmI.getIdAsString())); nameValuePairs.add(new BasicNameValuePair(ServerUtilities.POST_DATA_BOARD, boardJSONString)); nameValuePairs.add(new BasicNameValuePair(ServerUtilities.POST_DATA_USER_CHALLENGED, game.getPerson().getIdAsString())); nameValuePairs.add(new BasicNameValuePair(ServerUtilities.POST_DATA_NAME, game.getPerson().getName())); if (Utilities.verifyValidString(game.getId())) { nameValuePairs.add(new BasicNameValuePair(ServerUtilities.POST_DATA_GAME_ID, game.getId())); serverResponse = ServerUtilities.postToServer(ServerUtilities.ADDRESS_NEW_MOVE, nameValuePairs); } else { serverResponse = ServerUtilities.postToServer(ServerUtilities.ADDRESS_NEW_GAME, nameValuePairs); } } catch (final IOException e) { Log.e(LOG_TAG, "JSONException error in AsyncSendMove - doInBackground()!", e); } catch (final JSONException e) { Log.e(LOG_TAG, "IOException error in AsyncSendMove - doInBackground()!", e); } return serverResponse; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doInBackground"
"@Override protected String doInBackground(final Person whoAmI) { String serverResponse = null; try { final JSONObject boardJSON = board.makeJSON(); final String boardJSONString = boardJSON.toString(); final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair(ServerUtilities.POST_DATA_USER_CREATOR, whoAmI.getIdAsString())); nameValuePairs.add(new BasicNameValuePair(ServerUtilities.POST_DATA_BOARD, boardJSONString)); nameValuePairs.add(new BasicNameValuePair(ServerUtilities.POST_DATA_USER_CHALLENGED, game.getPerson().getIdAsString())); if (Utilities.verifyValidString(game.getId())) { <MASK>nameValuePairs.add(new BasicNameValuePair(ServerUtilities.POST_DATA_NAME, game.getPerson().getName()));</MASK> nameValuePairs.add(new BasicNameValuePair(ServerUtilities.POST_DATA_GAME_ID, game.getId())); serverResponse = ServerUtilities.postToServer(ServerUtilities.ADDRESS_NEW_MOVE, nameValuePairs); } else { serverResponse = ServerUtilities.postToServer(ServerUtilities.ADDRESS_NEW_GAME, nameValuePairs); } } catch (final IOException e) { Log.e(LOG_TAG, "JSONException error in AsyncSendMove - doInBackground()!", e); } catch (final JSONException e) { Log.e(LOG_TAG, "IOException error in AsyncSendMove - doInBackground()!", e); } return serverResponse; }"
Inversion-Mutation
megadiff
"@Override public View getView(int position, View convertView, ViewGroup parent) { View res; final MagazineModel currentMagazine = magazine.get(position); if(convertView == null){ res = LayoutInflater.from(context).inflate(R.layout.magazine_list_item, null); } else { res = convertView; } TextView title = (TextView)res.findViewById(R.id.item_title); TextView subtitle = (TextView)res.findViewById(R.id.item_subtitle); ImageView thumbnail = (ImageView)res.findViewById(R.id.item_thumbnail); title.setText(currentMagazine.getTitle()); subtitle.setText(currentMagazine.getSubtitle()); String imagePath = currentMagazine.getPngPath(); thumbnail.setImageBitmap(BitmapFactory.decodeFile(imagePath)); /** * downloadOrReadButton - this button can be "Download button" or "Read button" */ Button downloadOrReadButton = (Button)res.findViewById(R.id.item_button_one); /** * sampleOrDeleteButton - this button can be "Delete button" or "Sample button" */ Button sampleOrDeleteButton = (Button)res.findViewById(R.id.item_button_two); if (currentMagazine.isDownloaded()) { // Read case downloadOrReadButton.setText(context.getResources().getString( R.string.read)); downloadOrReadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { LibrelioApplication.startPDFActivity(context, currentMagazine.getPdfPath()); /*Intent intent = new Intent(context, DownloadActivity.class); intent.putExtra(DownloadActivity.FILE_NAME_KEY,currentMagazine.getFileName()); intent.putExtra(DownloadActivity.FILE_URL_KEY,currentMagazine.getPdfUrl()); intent.putExtra(DownloadActivity.FILE_PATH_KEY,currentMagazine.getPdfPath()); intent.putExtra(DownloadActivity.PNG_PATH_KEY,currentMagazine.getPngPath()); context.startActivity(intent);*/ } }); } else { // download case downloadOrReadButton.setText(context.getResources().getString( R.string.download)); downloadOrReadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(currentMagazine.isPaid()){ //Intent intent = new Intent("123"); //context.sendBroadcast(intent); Intent intent = new Intent(context,BillingActivity.class); intent.putExtra(DownloadActivity.FILE_NAME_KEY,currentMagazine.getFileName()); intent.putExtra(DownloadActivity.TITLE_KEY,currentMagazine.getTitle()); intent.putExtra(DownloadActivity.SUBTITLE_KEY,currentMagazine.getSubtitle()); context.startActivity(intent); } else { Intent intent = new Intent(context, DownloadActivity.class); intent.putExtra(DownloadActivity.FILE_NAME_KEY,currentMagazine.getFileName()); intent.putExtra(DownloadActivity.TITLE_KEY,currentMagazine.getTitle()); intent.putExtra(DownloadActivity.SUBTITLE_KEY,currentMagazine.getSubtitle()); intent.putExtra(DownloadActivity.IS_SAMPLE_KEY,false); intent.putExtra(DownloadActivity.ORIENTATION_KEY, context.getResources().getConfiguration().orientation); context.startActivity(intent); } } }); } // sampleOrDeleteButton.setVisibility(View.VISIBLE); if (!currentMagazine.isPaid() && !currentMagazine.isDownloaded()) { sampleOrDeleteButton.setVisibility(View.INVISIBLE); } else if (currentMagazine.isDownloaded()) { // delete case sampleOrDeleteButton.setText(context.getResources().getString( R.string.delete)); sampleOrDeleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { currentMagazine.delete(); } }); } else { // Sample case sampleOrDeleteButton.setText(context.getResources().getString( R.string.sample)); sampleOrDeleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { File sample = new File(currentMagazine.getSamplePath()); Log.d(TAG, "test: " + sample.exists() + " " + currentMagazine.isSampleDownloaded()); if (currentMagazine.isSampleDownloaded()) { LibrelioApplication.startPDFActivity(context, currentMagazine.getSamplePath()); } else { Intent intent = new Intent(context, DownloadActivity.class); intent.putExtra(DownloadActivity.FILE_NAME_KEY,currentMagazine.getFileName()); intent.putExtra(DownloadActivity.TITLE_KEY,currentMagazine.getTitle()); intent.putExtra(DownloadActivity.SUBTITLE_KEY,currentMagazine.getSubtitle()); intent.putExtra(DownloadActivity.ORIENTATION_KEY, context.getResources().getConfiguration().orientation); intent.putExtra(DownloadActivity.IS_SAMPLE_KEY,true); context.startActivity(intent); } } }); } return res; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getView"
"@Override public View getView(int position, View convertView, ViewGroup parent) { View res; final MagazineModel currentMagazine = magazine.get(position); if(convertView == null){ res = LayoutInflater.from(context).inflate(R.layout.magazine_list_item, null); } else { res = convertView; } TextView title = (TextView)res.findViewById(R.id.item_title); TextView subtitle = (TextView)res.findViewById(R.id.item_subtitle); ImageView thumbnail = (ImageView)res.findViewById(R.id.item_thumbnail); title.setText(currentMagazine.getTitle()); subtitle.setText(currentMagazine.getSubtitle()); String imagePath = currentMagazine.getPngPath(); thumbnail.setImageBitmap(BitmapFactory.decodeFile(imagePath)); /** * downloadOrReadButton - this button can be "Download button" or "Read button" */ Button downloadOrReadButton = (Button)res.findViewById(R.id.item_button_one); /** * sampleOrDeleteButton - this button can be "Delete button" or "Sample button" */ Button sampleOrDeleteButton = (Button)res.findViewById(R.id.item_button_two); if (currentMagazine.isDownloaded()) { // Read case downloadOrReadButton.setText(context.getResources().getString( R.string.read)); downloadOrReadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { LibrelioApplication.startPDFActivity(context, currentMagazine.getPdfPath()); /*Intent intent = new Intent(context, DownloadActivity.class); intent.putExtra(DownloadActivity.FILE_NAME_KEY,currentMagazine.getFileName()); intent.putExtra(DownloadActivity.FILE_URL_KEY,currentMagazine.getPdfUrl()); intent.putExtra(DownloadActivity.FILE_PATH_KEY,currentMagazine.getPdfPath()); intent.putExtra(DownloadActivity.PNG_PATH_KEY,currentMagazine.getPngPath()); context.startActivity(intent);*/ } }); } else { // download case downloadOrReadButton.setText(context.getResources().getString( R.string.download)); downloadOrReadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(currentMagazine.isPaid()){ //Intent intent = new Intent("123"); //context.sendBroadcast(intent); Intent intent = new Intent(context,BillingActivity.class); intent.putExtra(DownloadActivity.FILE_NAME_KEY,currentMagazine.getFileName()); intent.putExtra(DownloadActivity.TITLE_KEY,currentMagazine.getTitle()); intent.putExtra(DownloadActivity.SUBTITLE_KEY,currentMagazine.getSubtitle()); context.startActivity(intent); } else { Intent intent = new Intent(context, DownloadActivity.class); intent.putExtra(DownloadActivity.FILE_NAME_KEY,currentMagazine.getFileName()); intent.putExtra(DownloadActivity.TITLE_KEY,currentMagazine.getTitle()); intent.putExtra(DownloadActivity.SUBTITLE_KEY,currentMagazine.getSubtitle()); intent.putExtra(DownloadActivity.IS_SAMPLE_KEY,false); intent.putExtra(DownloadActivity.ORIENTATION_KEY, context.getResources().getConfiguration().orientation); context.startActivity(intent); } } }); } // if (!currentMagazine.isPaid() && !currentMagazine.isDownloaded()) { sampleOrDeleteButton.setVisibility(View.INVISIBLE); } else if (currentMagazine.isDownloaded()) { // delete case <MASK>sampleOrDeleteButton.setVisibility(View.VISIBLE);</MASK> sampleOrDeleteButton.setText(context.getResources().getString( R.string.delete)); sampleOrDeleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { currentMagazine.delete(); } }); } else { // Sample case sampleOrDeleteButton.setText(context.getResources().getString( R.string.sample)); sampleOrDeleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { File sample = new File(currentMagazine.getSamplePath()); Log.d(TAG, "test: " + sample.exists() + " " + currentMagazine.isSampleDownloaded()); if (currentMagazine.isSampleDownloaded()) { LibrelioApplication.startPDFActivity(context, currentMagazine.getSamplePath()); } else { Intent intent = new Intent(context, DownloadActivity.class); intent.putExtra(DownloadActivity.FILE_NAME_KEY,currentMagazine.getFileName()); intent.putExtra(DownloadActivity.TITLE_KEY,currentMagazine.getTitle()); intent.putExtra(DownloadActivity.SUBTITLE_KEY,currentMagazine.getSubtitle()); intent.putExtra(DownloadActivity.ORIENTATION_KEY, context.getResources().getConfiguration().orientation); intent.putExtra(DownloadActivity.IS_SAMPLE_KEY,true); context.startActivity(intent); } } }); } return res; }"
Inversion-Mutation
megadiff
"protected void onCreate ( Bundle savedInstanceState ) { MoaiLog.i ( "MoaiActivity onCreate: activity CREATED" ); super.onCreate ( savedInstanceState ); Moai.onCreate ( this ); Moai.createContext (); Moai.init (); requestWindowFeature ( Window.FEATURE_NO_TITLE ); getWindow ().addFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN ); getWindow ().addFlags ( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON ); try { ApplicationInfo myApp = getPackageManager ().getApplicationInfo ( getPackageName (), 0 ); Moai.mount ( "bundle", myApp.publicSourceDir ); Moai.setWorkingDirectory ( "bundle/assets/@WORKING_DIR@" ); } catch ( NameNotFoundException e ) { MoaiLog.e ( "MoaiActivity onCreate: Unable to locate the application bundle" ); } if ( getFilesDir () != null ) { Moai.setDocumentDirectory ( getFilesDir ().getAbsolutePath ()); } else { MoaiLog.e ( "MoaiActivity onCreate: Unable to set the document directory" ); } Display display = (( WindowManager ) getSystemService ( Context.WINDOW_SERVICE )).getDefaultDisplay (); ConfigurationInfo info = (( ActivityManager ) getSystemService ( Context.ACTIVITY_SERVICE )).getDeviceConfigurationInfo (); mMoaiView = new MoaiView ( this, display.getWidth (), display.getHeight (), info.reqGlEsVersion ); mSensorManager = ( SensorManager ) getSystemService ( Context.SENSOR_SERVICE ); startConnectivityReceiver (); enableAccelerometerEvents ( false ); setContentView ( mMoaiView ); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate"
"protected void onCreate ( Bundle savedInstanceState ) { MoaiLog.i ( "MoaiActivity onCreate: activity CREATED" ); super.onCreate ( savedInstanceState ); Moai.onCreate ( this ); <MASK>Moai.init ();</MASK> Moai.createContext (); requestWindowFeature ( Window.FEATURE_NO_TITLE ); getWindow ().addFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN ); getWindow ().addFlags ( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON ); try { ApplicationInfo myApp = getPackageManager ().getApplicationInfo ( getPackageName (), 0 ); Moai.mount ( "bundle", myApp.publicSourceDir ); Moai.setWorkingDirectory ( "bundle/assets/@WORKING_DIR@" ); } catch ( NameNotFoundException e ) { MoaiLog.e ( "MoaiActivity onCreate: Unable to locate the application bundle" ); } if ( getFilesDir () != null ) { Moai.setDocumentDirectory ( getFilesDir ().getAbsolutePath ()); } else { MoaiLog.e ( "MoaiActivity onCreate: Unable to set the document directory" ); } Display display = (( WindowManager ) getSystemService ( Context.WINDOW_SERVICE )).getDefaultDisplay (); ConfigurationInfo info = (( ActivityManager ) getSystemService ( Context.ACTIVITY_SERVICE )).getDeviceConfigurationInfo (); mMoaiView = new MoaiView ( this, display.getWidth (), display.getHeight (), info.reqGlEsVersion ); mSensorManager = ( SensorManager ) getSystemService ( Context.SENSOR_SERVICE ); startConnectivityReceiver (); enableAccelerometerEvents ( false ); setContentView ( mMoaiView ); }"
Inversion-Mutation
megadiff
"protected void repetitiveAssertPetclinicUrlIsAvailable() { RepetitiveConditionProvider condition = new RepetitiveConditionProvider() { @Override public boolean getCondition() { String spec = null; try { String hostAddress = tomcat.getInstances()[0].getGridServiceContainer().getMachine().getHostAddress(); spec = "http://" + hostAddress + ":8080/petclinic/"; LogUtils.log("Checking that url : " + spec + " is available"); boolean httpURLAvailable = ServiceUtils.isHttpURLAvailable(spec); LogUtils.log(spec + " available = " + httpURLAvailable); return httpURLAvailable; } catch (final Exception e) { throw new RuntimeException("Error polling to URL : " + spec + " . Reason --> " + e.getMessage()); } } }; AssertUtils.repetitiveAssertTrue("petclinic url is not available! waited for 10 seconds", condition, TEN_SECONDS); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "repetitiveAssertPetclinicUrlIsAvailable"
"protected void repetitiveAssertPetclinicUrlIsAvailable() { RepetitiveConditionProvider condition = new RepetitiveConditionProvider() { @Override public boolean getCondition() { String spec = null; try { String hostAddress = tomcat.getInstances()[0].getGridServiceContainer().getMachine().getHostAddress(); <MASK>LogUtils.log("Checking that url : " + spec + " is available");</MASK> spec = "http://" + hostAddress + ":8080/petclinic/"; boolean httpURLAvailable = ServiceUtils.isHttpURLAvailable(spec); LogUtils.log(spec + " available = " + httpURLAvailable); return httpURLAvailable; } catch (final Exception e) { throw new RuntimeException("Error polling to URL : " + spec + " . Reason --> " + e.getMessage()); } } }; AssertUtils.repetitiveAssertTrue("petclinic url is not available! waited for 10 seconds", condition, TEN_SECONDS); }"
Inversion-Mutation
megadiff
"@Override public boolean getCondition() { String spec = null; try { String hostAddress = tomcat.getInstances()[0].getGridServiceContainer().getMachine().getHostAddress(); spec = "http://" + hostAddress + ":8080/petclinic/"; LogUtils.log("Checking that url : " + spec + " is available"); boolean httpURLAvailable = ServiceUtils.isHttpURLAvailable(spec); LogUtils.log(spec + " available = " + httpURLAvailable); return httpURLAvailable; } catch (final Exception e) { throw new RuntimeException("Error polling to URL : " + spec + " . Reason --> " + e.getMessage()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getCondition"
"@Override public boolean getCondition() { String spec = null; try { String hostAddress = tomcat.getInstances()[0].getGridServiceContainer().getMachine().getHostAddress(); <MASK>LogUtils.log("Checking that url : " + spec + " is available");</MASK> spec = "http://" + hostAddress + ":8080/petclinic/"; boolean httpURLAvailable = ServiceUtils.isHttpURLAvailable(spec); LogUtils.log(spec + " available = " + httpURLAvailable); return httpURLAvailable; } catch (final Exception e) { throw new RuntimeException("Error polling to URL : " + spec + " . Reason --> " + e.getMessage()); } }"
Inversion-Mutation
megadiff
"@Override public Family createMappedForm(PersistentEntity entity) { ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(entity.getJavaClass()); final Closure value = cpf.getStaticPropertyValue(GormProperties.MAPPING, Closure.class); if(value != null) { final Region family = new Region(); AttributesFactory factory = new AttributesFactory() { public void setRegion(String name) { family.setRegion(name); } }; factory.setDataPolicy(defaultDataPolicy); MappingConfigurationBuilder builder = new MappingConfigurationBuilder(factory, KeyValue.class); builder.evaluate(value); entityToPropertyMap.put(entity, builder.getProperties()); final RegionAttributes regionAttributes = factory.create(); family.setRegionAttributes(regionAttributes); family.setCacheListeners(regionAttributes.getCacheListeners()); family.setDataPolicy(regionAttributes.getDataPolicy()); family.setCacheLoader(regionAttributes.getCacheLoader()); family.setCacheWriter(regionAttributes.getCacheWriter()); return family; } else { return new Region(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createMappedForm"
"@Override public Family createMappedForm(PersistentEntity entity) { ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(entity.getJavaClass()); final Closure value = cpf.getStaticPropertyValue(GormProperties.MAPPING, Closure.class); if(value != null) { final Region family = new Region(); AttributesFactory factory = new AttributesFactory() { public void setRegion(String name) { family.setRegion(name); } }; MappingConfigurationBuilder builder = new MappingConfigurationBuilder(factory, KeyValue.class); builder.evaluate(value); <MASK>factory.setDataPolicy(defaultDataPolicy);</MASK> entityToPropertyMap.put(entity, builder.getProperties()); final RegionAttributes regionAttributes = factory.create(); family.setRegionAttributes(regionAttributes); family.setCacheListeners(regionAttributes.getCacheListeners()); family.setDataPolicy(regionAttributes.getDataPolicy()); family.setCacheLoader(regionAttributes.getCacheLoader()); family.setCacheWriter(regionAttributes.getCacheWriter()); return family; } else { return new Region(); } }"
Inversion-Mutation
megadiff
"private void onBufferDraw() { if (mBuffer == null || mKeyboardChanged) { mKeyboard.setKeyboardWidth(mViewWidth); if (mBuffer == null || mKeyboardChanged && (mBuffer.getWidth() != getWidth() || mBuffer.getHeight() != getHeight())) { // Make sure our bitmap is at least 1x1 final int width = Math.max(1, getWidth()); final int height = Math.max(1, getHeight()); mBuffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBuffer); } invalidateAllKeys(); mKeyboardChanged = false; } final Canvas canvas = mCanvas; canvas.clipRect(mDirtyRect, Op.REPLACE); if (mKeyboard == null) return; final Paint paint = mPaint; final Paint paintHint = mPaintHint; final Drawable keyBackground = mKeyBackground; final Rect clipRegion = mClipRegion; final Rect padding = mPadding; final int kbdPaddingLeft = getPaddingLeft(); final int kbdPaddingTop = getPaddingTop(); final Key[] keys = mKeys; final Key invalidKey = mInvalidatedKey; boolean drawSingleKey = false; if (invalidKey != null && canvas.getClipBounds(clipRegion)) { // TODO we should use Rect.inset and Rect.contains here. // Is clipRegion completely contained within the invalidated key? if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left && invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top && invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right && invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) { drawSingleKey = true; } } canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR); final int keyCount = keys.length; for (int i = 0; i < keyCount; i++) { final Key key = keys[i]; if (drawSingleKey && invalidKey != key) { continue; } paint.setColor(key.isCursor ? mKeyCursorColor : mKeyTextColor); int[] drawableState = key.getCurrentDrawableState(); keyBackground.setState(drawableState); // Switch the character to uppercase if shift is pressed String label = key.label == null? null : adjustCase(key.label).toString(); float yscale = 1.0f; final Rect bounds = keyBackground.getBounds(); if (key.width != bounds.right || key.height != bounds.bottom) { int minHeight = keyBackground.getMinimumHeight(); if (minHeight > key.height) { yscale = (float) key.height / minHeight; keyBackground.setBounds(0, 0, key.width, minHeight); } else { keyBackground.setBounds(0, 0, key.width, key.height); } } canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop); if (yscale != 1.0f) { canvas.save(); canvas.scale(1.0f, yscale); } keyBackground.draw(canvas); if (yscale != 1.0f) canvas.restore(); boolean shouldDrawIcon = true; if (label != null) { // For characters, use large font. For labels like "Done", use small font. final int labelSize; if (label.length() > 1 && key.codes.length < 2) { //Log.i(TAG, "mLabelTextSize=" + mLabelTextSize + " mLabelScale=" + mLabelScale); labelSize = (int)(mLabelTextSize * mLabelScale); paint.setTypeface(Typeface.DEFAULT); } else { labelSize = (int)(mKeyTextSize * mLabelScale); paint.setTypeface(mKeyTextStyle); } paint.setFakeBoldText(key.isCursor); paint.setTextSize(labelSize); final int labelHeight = getLabelHeight(paint, labelSize); // Draw a drop shadow for the text paint.setShadowLayer(mShadowRadius, 0, 0, mShadowColor); // Draw hint label (if present) behind the main key char hint = getHintLabel(key); if (hint != 0) { int hintTextSize = (int)(mKeyTextSize * 0.6 * mLabelScale); paintHint.setTextSize(hintTextSize); final int hintLabelHeight = getLabelHeight(paintHint, hintTextSize); canvas.drawText(Character.toString(hint), key.width - padding.right, padding.top + hintLabelHeight * 11/10, paintHint); } // Draw main key label final int centerX = (key.width + padding.left - padding.right) / 2; final int centerY = (key.height + padding.top - padding.bottom) / 2; final float baseline = centerY + labelHeight * KEY_LABEL_VERTICAL_ADJUSTMENT_FACTOR; canvas.drawText(label, centerX, baseline, paint); if (key.isCursor) { // poor man's bold canvas.drawText(label, centerX+0.5f, baseline, paint); canvas.drawText(label, centerX-0.5f, baseline, paint); canvas.drawText(label, centerX, baseline+0.5f, paint); canvas.drawText(label, centerX, baseline-0.5f, paint); } // Turn off drop shadow paint.setShadowLayer(0, 0, 0, 0); // Usually don't draw icon if label is not null, but we draw icon for the number // hint and popup hint. shouldDrawIcon = shouldDrawLabelAndIcon(key); } if (key.icon != null && shouldDrawIcon) { // Special handing for the upper-right number hint icons final int drawableWidth; final int drawableHeight; final int drawableX; final int drawableY; if (shouldDrawIconFully(key)) { drawableWidth = key.width; drawableHeight = key.height; drawableX = 0; drawableY = NUMBER_HINT_VERTICAL_ADJUSTMENT_PIXEL; } else { drawableWidth = key.icon.getIntrinsicWidth(); drawableHeight = key.icon.getIntrinsicHeight(); drawableX = (key.width + padding.left - padding.right - drawableWidth) / 2; drawableY = (key.height + padding.top - padding.bottom - drawableHeight) / 2; } canvas.translate(drawableX, drawableY); key.icon.setBounds(0, 0, drawableWidth, drawableHeight); key.icon.draw(canvas); canvas.translate(-drawableX, -drawableY); } canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop); } mInvalidatedKey = null; // Overlay a dark rectangle to dim the keyboard if (mMiniKeyboard != null) { paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24); canvas.drawRect(0, 0, getWidth(), getHeight(), paint); } if (DEBUG) { if (mShowTouchPoints) { for (PointerTracker tracker : mPointerTrackers) { int startX = tracker.getStartX(); int startY = tracker.getStartY(); int lastX = tracker.getLastX(); int lastY = tracker.getLastY(); paint.setAlpha(128); paint.setColor(0xFFFF0000); canvas.drawCircle(startX, startY, 3, paint); canvas.drawLine(startX, startY, lastX, lastY, paint); paint.setColor(0xFF0000FF); canvas.drawCircle(lastX, lastY, 3, paint); paint.setColor(0xFF00FF00); canvas.drawCircle((startX + lastX) / 2, (startY + lastY) / 2, 2, paint); } } } mDrawPending = false; mDirtyRect.setEmpty(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onBufferDraw"
"private void onBufferDraw() { if (mBuffer == null || mKeyboardChanged) { mKeyboard.setKeyboardWidth(mViewWidth); if (mBuffer == null || mKeyboardChanged && (mBuffer.getWidth() != getWidth() || mBuffer.getHeight() != getHeight())) { // Make sure our bitmap is at least 1x1 final int width = Math.max(1, getWidth()); final int height = Math.max(1, getHeight()); mBuffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBuffer); } invalidateAllKeys(); mKeyboardChanged = false; } final Canvas canvas = mCanvas; canvas.clipRect(mDirtyRect, Op.REPLACE); if (mKeyboard == null) return; final Paint paint = mPaint; final Paint paintHint = mPaintHint; final Drawable keyBackground = mKeyBackground; final Rect clipRegion = mClipRegion; final Rect padding = mPadding; final int kbdPaddingLeft = getPaddingLeft(); final int kbdPaddingTop = getPaddingTop(); final Key[] keys = mKeys; final Key invalidKey = mInvalidatedKey; boolean drawSingleKey = false; if (invalidKey != null && canvas.getClipBounds(clipRegion)) { // TODO we should use Rect.inset and Rect.contains here. // Is clipRegion completely contained within the invalidated key? if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left && invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top && invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right && invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) { drawSingleKey = true; } } canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR); final int keyCount = keys.length; for (int i = 0; i < keyCount; i++) { final Key key = keys[i]; if (drawSingleKey && invalidKey != key) { continue; } paint.setColor(key.isCursor ? mKeyCursorColor : mKeyTextColor); int[] drawableState = key.getCurrentDrawableState(); keyBackground.setState(drawableState); // Switch the character to uppercase if shift is pressed String label = key.label == null? null : adjustCase(key.label).toString(); float yscale = 1.0f; final Rect bounds = keyBackground.getBounds(); if (key.width != bounds.right || key.height != bounds.bottom) { int minHeight = keyBackground.getMinimumHeight(); if (minHeight > key.height) { yscale = (float) key.height / minHeight; keyBackground.setBounds(0, 0, key.width, minHeight); } else { keyBackground.setBounds(0, 0, key.width, key.height); } } canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop); if (yscale != 1.0f) { canvas.save(); canvas.scale(1.0f, yscale); } keyBackground.draw(canvas); if (yscale != 1.0f) canvas.restore(); boolean shouldDrawIcon = true; if (label != null) { // For characters, use large font. For labels like "Done", use small font. final int labelSize; if (label.length() > 1 && key.codes.length < 2) { //Log.i(TAG, "mLabelTextSize=" + mLabelTextSize + " mLabelScale=" + mLabelScale); labelSize = (int)(mLabelTextSize * mLabelScale); paint.setTypeface(Typeface.DEFAULT); } else { labelSize = (int)(mKeyTextSize * mLabelScale); paint.setTypeface(mKeyTextStyle); <MASK>paint.setFakeBoldText(key.isCursor);</MASK> } paint.setTextSize(labelSize); final int labelHeight = getLabelHeight(paint, labelSize); // Draw a drop shadow for the text paint.setShadowLayer(mShadowRadius, 0, 0, mShadowColor); // Draw hint label (if present) behind the main key char hint = getHintLabel(key); if (hint != 0) { int hintTextSize = (int)(mKeyTextSize * 0.6 * mLabelScale); paintHint.setTextSize(hintTextSize); final int hintLabelHeight = getLabelHeight(paintHint, hintTextSize); canvas.drawText(Character.toString(hint), key.width - padding.right, padding.top + hintLabelHeight * 11/10, paintHint); } // Draw main key label final int centerX = (key.width + padding.left - padding.right) / 2; final int centerY = (key.height + padding.top - padding.bottom) / 2; final float baseline = centerY + labelHeight * KEY_LABEL_VERTICAL_ADJUSTMENT_FACTOR; canvas.drawText(label, centerX, baseline, paint); if (key.isCursor) { // poor man's bold canvas.drawText(label, centerX+0.5f, baseline, paint); canvas.drawText(label, centerX-0.5f, baseline, paint); canvas.drawText(label, centerX, baseline+0.5f, paint); canvas.drawText(label, centerX, baseline-0.5f, paint); } // Turn off drop shadow paint.setShadowLayer(0, 0, 0, 0); // Usually don't draw icon if label is not null, but we draw icon for the number // hint and popup hint. shouldDrawIcon = shouldDrawLabelAndIcon(key); } if (key.icon != null && shouldDrawIcon) { // Special handing for the upper-right number hint icons final int drawableWidth; final int drawableHeight; final int drawableX; final int drawableY; if (shouldDrawIconFully(key)) { drawableWidth = key.width; drawableHeight = key.height; drawableX = 0; drawableY = NUMBER_HINT_VERTICAL_ADJUSTMENT_PIXEL; } else { drawableWidth = key.icon.getIntrinsicWidth(); drawableHeight = key.icon.getIntrinsicHeight(); drawableX = (key.width + padding.left - padding.right - drawableWidth) / 2; drawableY = (key.height + padding.top - padding.bottom - drawableHeight) / 2; } canvas.translate(drawableX, drawableY); key.icon.setBounds(0, 0, drawableWidth, drawableHeight); key.icon.draw(canvas); canvas.translate(-drawableX, -drawableY); } canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop); } mInvalidatedKey = null; // Overlay a dark rectangle to dim the keyboard if (mMiniKeyboard != null) { paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24); canvas.drawRect(0, 0, getWidth(), getHeight(), paint); } if (DEBUG) { if (mShowTouchPoints) { for (PointerTracker tracker : mPointerTrackers) { int startX = tracker.getStartX(); int startY = tracker.getStartY(); int lastX = tracker.getLastX(); int lastY = tracker.getLastY(); paint.setAlpha(128); paint.setColor(0xFFFF0000); canvas.drawCircle(startX, startY, 3, paint); canvas.drawLine(startX, startY, lastX, lastY, paint); paint.setColor(0xFF0000FF); canvas.drawCircle(lastX, lastY, 3, paint); paint.setColor(0xFF00FF00); canvas.drawCircle((startX + lastX) / 2, (startY + lastY) / 2, 2, paint); } } } mDrawPending = false; mDirtyRect.setEmpty(); }"
Inversion-Mutation
megadiff
"@Override public SqlScript createCleanScript(JdbcTemplate jdbcTemplate) { final List<String> allDropStatements = new ArrayList<String>(); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "SEQUENCE", "")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "FUNCTION", "")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "MATERIALIZED VIEW", "")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "PACKAGE", "")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "PROCEDURE", "")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "SYNONYM", "")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "VIEW", "")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "TABLE", "CASCADE CONSTRAINTS PURGE")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "TYPE", "")); allDropStatements.addAll(generateDropStatementsForSpatialExtensions(jdbcTemplate)); List<SqlStatement> sqlStatements = new ArrayList<SqlStatement>(); int count = 0; for (String dropStatement : allDropStatements) { count++; sqlStatements.add(new SqlStatement(count, dropStatement)); } return new SqlScript(sqlStatements); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createCleanScript"
"@Override public SqlScript createCleanScript(JdbcTemplate jdbcTemplate) { final List<String> allDropStatements = new ArrayList<String>(); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "SEQUENCE", "")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "FUNCTION", "")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "MATERIALIZED VIEW", "")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "PACKAGE", "")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "PROCEDURE", "")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "SYNONYM", "")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "TABLE", "CASCADE CONSTRAINTS PURGE")); allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "TYPE", "")); <MASK>allDropStatements.addAll(generateDropStatementsForObjectType(jdbcTemplate, "VIEW", ""));</MASK> allDropStatements.addAll(generateDropStatementsForSpatialExtensions(jdbcTemplate)); List<SqlStatement> sqlStatements = new ArrayList<SqlStatement>(); int count = 0; for (String dropStatement : allDropStatements) { count++; sqlStatements.add(new SqlStatement(count, dropStatement)); } return new SqlScript(sqlStatements); }"
Inversion-Mutation
megadiff
"private void createProject() { // get the target and try to resolve it. int targetId = mSdkCommandLine.getParamTargetId(); IAndroidTarget[] targets = mSdkManager.getTargets(); if (targetId < 1 || targetId > targets.length) { errorAndExit("Target id is not valid. Use '%s list targets' to get the target ids.", SdkConstants.androidCmdName()); } IAndroidTarget target = targets[targetId - 1]; ProjectCreator creator = new ProjectCreator(mSdkFolder, mSdkCommandLine.isVerbose() ? OutputLevel.VERBOSE : mSdkCommandLine.isSilent() ? OutputLevel.SILENT : OutputLevel.NORMAL, mSdkLog); String projectDir = getProjectLocation(mSdkCommandLine.getParamLocationPath()); String projectName = mSdkCommandLine.getParamName(); String packageName = mSdkCommandLine.getParamProjectPackage(); String activityName = mSdkCommandLine.getParamProjectActivity(); if (projectName != null && !ProjectCreator.RE_PROJECT_NAME.matcher(projectName).matches()) { errorAndExit( "Project name '%1$s' contains invalid characters.\nAllowed characters are: %2$s", projectName, ProjectCreator.CHARS_PROJECT_NAME); return; } if (activityName != null && !ProjectCreator.RE_ACTIVITY_NAME.matcher(activityName).matches()) { errorAndExit( "Activity name '%1$s' contains invalid characters.\nAllowed characters are: %2$s", activityName, ProjectCreator.CHARS_ACTIVITY_NAME); return; } if (packageName != null && !ProjectCreator.RE_PACKAGE_NAME.matcher(packageName).matches()) { errorAndExit( "Package name '%1$s' contains invalid characters.\n" + "A package name must be constitued of two Java identifiers.\n" + "Each identifier allowed characters are: %2$s", packageName, ProjectCreator.CHARS_PACKAGE_NAME); return; } creator.createProject(projectDir, projectName, packageName, activityName, target, false /* isTestProject*/); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createProject"
"private void createProject() { // get the target and try to resolve it. int targetId = mSdkCommandLine.getParamTargetId(); IAndroidTarget[] targets = mSdkManager.getTargets(); if (targetId < 1 || targetId > targets.length) { errorAndExit("Target id is not valid. Use '%s list targets' to get the target ids.", SdkConstants.androidCmdName()); } IAndroidTarget target = targets[targetId - 1]; ProjectCreator creator = new ProjectCreator(mSdkFolder, mSdkCommandLine.isVerbose() ? OutputLevel.VERBOSE : mSdkCommandLine.isSilent() ? OutputLevel.SILENT : OutputLevel.NORMAL, mSdkLog); String projectDir = getProjectLocation(mSdkCommandLine.getParamLocationPath()); String projectName = mSdkCommandLine.getParamName(); String packageName = mSdkCommandLine.getParamProjectPackage(); String activityName = mSdkCommandLine.getParamProjectActivity(); if (projectName != null && !ProjectCreator.RE_PROJECT_NAME.matcher(projectName).matches()) { errorAndExit( "Project name '%1$s' contains invalid characters.\nAllowed characters are: %2$s", projectName, ProjectCreator.CHARS_PROJECT_NAME); return; } if (activityName != null && !ProjectCreator.RE_ACTIVITY_NAME.matcher(activityName).matches()) { errorAndExit( "Activity name '%1$s' contains invalid characters.\nAllowed characters are: %2$s", <MASK>activityName,</MASK> ProjectCreator.CHARS_ACTIVITY_NAME); return; } if (packageName != null && !ProjectCreator.RE_PACKAGE_NAME.matcher(packageName).matches()) { errorAndExit( "Package name '%1$s' contains invalid characters.\n" + "A package name must be constitued of two Java identifiers.\n" + "Each identifier allowed characters are: %2$s", packageName, ProjectCreator.CHARS_PACKAGE_NAME); return; } creator.createProject(projectDir, projectName, <MASK>activityName,</MASK> packageName, target, false /* isTestProject*/); }"
Inversion-Mutation
megadiff
"@Override public IMarkerResolution[] getResolutions(IMarker marker) { ArrayList<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>(); int position = marker.getAttribute(IMarker.CHAR_START, 0); try { if(marker.getResource() instanceof IFile){ IFile file = (IFile)marker.getResource(); if(file != null){ String preferenceKey = getPreferenceKey(marker); String preferencePageId = getPreferencePageId(marker); if(preferenceKey != null && preferencePageId != null){ boolean enabled = marker.getAttribute(ValidationErrorManager.SUPPRESS_WARNINGS_ENABLED_ATTRIBUTE, false); int severity = marker.getAttribute(IMarker.SEVERITY, 0); if(enabled && severity == IMarker.SEVERITY_WARNING){ IJavaElement element = findJavaElement(file, position); if(element != null){ if(element instanceof IMethod){ ILocalVariable parameter = findParameter((IMethod)element, position); if(parameter != null){ resolutions.add(new AddSuppressWarningsMarkerResolution(file, parameter, preferenceKey)); } } resolutions.add(new AddSuppressWarningsMarkerResolution(file, element, preferenceKey)); } } resolutions.add(new ConfigureProblemSeverityMarkerResolution(preferencePageId, preferenceKey)); } } } } catch (CoreException e) { CommonUIPlugin.getDefault().logError(e); } return resolutions.toArray(new IMarkerResolution[] {}); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getResolutions"
"@Override public IMarkerResolution[] getResolutions(IMarker marker) { ArrayList<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>(); int position = marker.getAttribute(IMarker.CHAR_START, 0); try { if(marker.getResource() instanceof IFile){ IFile file = (IFile)marker.getResource(); if(file != null){ String preferenceKey = getPreferenceKey(marker); String preferencePageId = getPreferencePageId(marker); if(preferenceKey != null && preferencePageId != null){ <MASK>resolutions.add(new ConfigureProblemSeverityMarkerResolution(preferencePageId, preferenceKey));</MASK> boolean enabled = marker.getAttribute(ValidationErrorManager.SUPPRESS_WARNINGS_ENABLED_ATTRIBUTE, false); int severity = marker.getAttribute(IMarker.SEVERITY, 0); if(enabled && severity == IMarker.SEVERITY_WARNING){ IJavaElement element = findJavaElement(file, position); if(element != null){ if(element instanceof IMethod){ ILocalVariable parameter = findParameter((IMethod)element, position); if(parameter != null){ resolutions.add(new AddSuppressWarningsMarkerResolution(file, parameter, preferenceKey)); } } resolutions.add(new AddSuppressWarningsMarkerResolution(file, element, preferenceKey)); } } } } } } catch (CoreException e) { CommonUIPlugin.getDefault().logError(e); } return resolutions.toArray(new IMarkerResolution[] {}); }"
Inversion-Mutation
megadiff
"private HaeinsaRowTransaction checkOrRecoverLock(HaeinsaTransaction tx, byte[] row, HaeinsaTableTransaction tableState, @Nullable HaeinsaRowTransaction rowState) throws IOException { if (rowState != null && rowState.getCurrent() != null) { // return rowState itself if rowState already exist and contains TRowLock return rowState; } int recoverCount = 0; while (true) { if (recoverCount > HaeinsaConstants.RECOVER_MAX_RETRY_COUNT) { throw new ConflictException("recover retry count is exceeded."); } TRowLock currentRowLock = getRowLock(row); if (checkAndIsShouldRecover(currentRowLock)) { recover(tx, row); recoverCount++; } else { rowState = tableState.createOrGetRowState(row); rowState.setCurrent(currentRowLock); break; } } return rowState; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "checkOrRecoverLock"
"private HaeinsaRowTransaction checkOrRecoverLock(HaeinsaTransaction tx, byte[] row, HaeinsaTableTransaction tableState, @Nullable HaeinsaRowTransaction rowState) throws IOException { if (rowState != null && rowState.getCurrent() != null) { // return rowState itself if rowState already exist and contains TRowLock return rowState; } int recoverCount = 0; while (true) { if (recoverCount > HaeinsaConstants.RECOVER_MAX_RETRY_COUNT) { throw new ConflictException("recover retry count is exceeded."); } TRowLock currentRowLock = getRowLock(row); if (checkAndIsShouldRecover(currentRowLock)) { recover(tx, row); } else { rowState = tableState.createOrGetRowState(row); rowState.setCurrent(currentRowLock); break; } <MASK>recoverCount++;</MASK> } return rowState; }"
Inversion-Mutation
megadiff
"private void push(double x, double y) { stack[stackptr++] = y; stack[stackptr++] = x; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "push"
"private void push(double x, double y) { <MASK>stack[stackptr++] = x;</MASK> stack[stackptr++] = y; }"
Inversion-Mutation
megadiff
"@SuppressWarnings("unchecked") protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) { // this is the bean peforming the registration of custom listeners BeanDefinitionBuilder listenerRegBean = BeanDefinitionBuilder.rootBeanDefinition(CustomListenersBean.class); Element emElement = DomUtils.getChildElementByTagName(element, "eventManager"); if (emElement != null) { // if the user overrides the default eventManager final String beanName = emElement.getAttribute("ref"); listenerRegBean.addDependsOn(beanName); listenerRegBean.addPropertyReference("eventManager", beanName); } List<Element> listenerElements = DomUtils.getChildElementsByTagName(element, "listener"); ManagedList listeners = new ManagedList(listenerElements.size()); for (Element listenerElement : listenerElements) { final BeanDefinitionParserDelegate beanParserDelegate = new BeanDefinitionParserDelegate(parserContext.getReaderContext()); // parse nested spring bean definitions Element bean = DomUtils.getChildElementByTagName(listenerElement, "bean"); // it could be a ref to an existing bean too if (bean == null) { Element ref = DomUtils.getChildElementByTagName(listenerElement, "ref"); String beanName = StringUtils.defaultString(ref.getAttribute("bean"), ref.getAttribute("local")); if (StringUtils.isBlank(beanName)) { throw new IllegalArgumentException("A listener ref element has neither 'bean' nor 'local' attributes"); } listeners.add(new RuntimeBeanReference(beanName)); } else { // need to init defaults beanParserDelegate.initDefaults(bean); BeanDefinitionHolder listener = beanParserDelegate.parseBeanDefinitionElement(bean); listeners.add(listener); } } listenerRegBean.addPropertyValue("customListeners", listeners); return listenerRegBean.getBeanDefinition(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parseInternal"
"@SuppressWarnings("unchecked") protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) { // this is the bean peforming the registration of custom listeners BeanDefinitionBuilder listenerRegBean = BeanDefinitionBuilder.rootBeanDefinition(CustomListenersBean.class); Element emElement = DomUtils.getChildElementByTagName(element, "eventManager"); if (emElement != null) { // if the user overrides the default eventManager final String beanName = emElement.getAttribute("ref"); listenerRegBean.addDependsOn(beanName); listenerRegBean.addPropertyReference("eventManager", beanName); } List<Element> listenerElements = DomUtils.getChildElementsByTagName(element, "listener"); ManagedList listeners = new ManagedList(listenerElements.size()); for (Element listenerElement : listenerElements) { final BeanDefinitionParserDelegate beanParserDelegate = new BeanDefinitionParserDelegate(parserContext.getReaderContext()); // parse nested spring bean definitions Element bean = DomUtils.getChildElementByTagName(listenerElement, "bean"); // it could be a ref to an existing bean too if (bean == null) { Element ref = DomUtils.getChildElementByTagName(listenerElement, "ref"); String beanName = StringUtils.defaultString(ref.getAttribute("bean"), ref.getAttribute("local")); if (StringUtils.isBlank(beanName)) { throw new IllegalArgumentException("A listener ref element has neither 'bean' nor 'local' attributes"); } listeners.add(new RuntimeBeanReference(beanName)); } else { <MASK>BeanDefinitionHolder listener = beanParserDelegate.parseBeanDefinitionElement(bean);</MASK> // need to init defaults beanParserDelegate.initDefaults(bean); listeners.add(listener); } } listenerRegBean.addPropertyValue("customListeners", listeners); return listenerRegBean.getBeanDefinition(); }"
Inversion-Mutation
megadiff
"public static byte[] encodeArtDmxPacket(final String univers, final String network, final int dmx[] ) throws IOException { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // Prepare next trame artDmxCounter++; // ID. byteArrayOutputStream.write(ByteUtils.toByta(Constants.ID)); byteArrayOutputStream.write(MagicNumbers.MAGIC_NUMBER_ZERO); // OpOutput byteArrayOutputStream.write(ByteUtilsArt.in16toByte(20480)); // Version byteArrayOutputStream.write(MagicNumbers.MAGIC_NUMBER_ZERO); byteArrayOutputStream.write(new Integer(Constants.ART_NET_VERSION).byteValue()); // Sequence byteArrayOutputStream.write(ByteUtilsArt.in8toByte(artDmxCounter)); // Physical byteArrayOutputStream.write(MagicNumbers.MAGIC_NUMBER_ZERO); // Net Switch byteArrayOutputStream.write(Integer.parseInt(univers, MagicNumbers.MAGIC_NUMBER_16)); byteArrayOutputStream.write(Integer.parseInt(network, MagicNumbers.MAGIC_NUMBER_16)); // DMX data Length byteArrayOutputStream.write(ByteUtilsArt.in16toBit(dmx.length)); byte bdmx; for(int i=0; i!=Constants.DMX_512_SIZE; i++) { if(dmx.length>i) { bdmx = (byte) dmx[i]; byteArrayOutputStream.write(ByteUtilsArt.in8toByte(bdmx)); } else { byteArrayOutputStream.write(ByteUtilsArt.in8toByte(MagicNumbers.MAGIC_NUMBER_ZERO)); } } return byteArrayOutputStream.toByteArray(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "encodeArtDmxPacket"
"public static byte[] encodeArtDmxPacket(final String univers, final String network, final int dmx[] ) throws IOException { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // Prepare next trame artDmxCounter++; // ID. byteArrayOutputStream.write(ByteUtils.toByta(Constants.ID)); byteArrayOutputStream.write(MagicNumbers.MAGIC_NUMBER_ZERO); // OpOutput byteArrayOutputStream.write(ByteUtilsArt.in16toByte(20480)); // Version <MASK>byteArrayOutputStream.write(new Integer(Constants.ART_NET_VERSION).byteValue());</MASK> byteArrayOutputStream.write(MagicNumbers.MAGIC_NUMBER_ZERO); // Sequence byteArrayOutputStream.write(ByteUtilsArt.in8toByte(artDmxCounter)); // Physical byteArrayOutputStream.write(MagicNumbers.MAGIC_NUMBER_ZERO); // Net Switch byteArrayOutputStream.write(Integer.parseInt(univers, MagicNumbers.MAGIC_NUMBER_16)); byteArrayOutputStream.write(Integer.parseInt(network, MagicNumbers.MAGIC_NUMBER_16)); // DMX data Length byteArrayOutputStream.write(ByteUtilsArt.in16toBit(dmx.length)); byte bdmx; for(int i=0; i!=Constants.DMX_512_SIZE; i++) { if(dmx.length>i) { bdmx = (byte) dmx[i]; byteArrayOutputStream.write(ByteUtilsArt.in8toByte(bdmx)); } else { byteArrayOutputStream.write(ByteUtilsArt.in8toByte(MagicNumbers.MAGIC_NUMBER_ZERO)); } } return byteArrayOutputStream.toByteArray(); }"
Inversion-Mutation
megadiff
"private void doConnect() { if (mConnectingThread != null) { // a connection is still goign on! return; } mLastConnectionError = getString(R.string.conn_connecting); updateServiceNotification(); if (mSmackable != null) { mSmackable.unRegisterCallback(); } mConnectingThread = new Thread() { public void run() { try { createAdapter(); if (!mSmackable.doConnect()) { postConnectionFailed("Inconsistency in Smackable.doConnect()"); } postConnectionEstablished(); } catch (YaximXMPPException e) { String message = e.getLocalizedMessage(); if (e.getCause() != null) message += "\n" + e.getCause().getLocalizedMessage(); postConnectionFailed(message); logError("YaximXMPPException in doConnect():"); e.printStackTrace(); } finally { if (mConnectingThread != null) synchronized(mConnectingThread) { mConnectingThread = null; } } } }; mConnectingThread.start(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doConnect"
"private void doConnect() { if (mConnectingThread != null) { // a connection is still goign on! return; } mLastConnectionError = getString(R.string.conn_connecting); updateServiceNotification(); if (mSmackable != null) { mSmackable.unRegisterCallback(); } <MASK>createAdapter();</MASK> mConnectingThread = new Thread() { public void run() { try { if (!mSmackable.doConnect()) { postConnectionFailed("Inconsistency in Smackable.doConnect()"); } postConnectionEstablished(); } catch (YaximXMPPException e) { String message = e.getLocalizedMessage(); if (e.getCause() != null) message += "\n" + e.getCause().getLocalizedMessage(); postConnectionFailed(message); logError("YaximXMPPException in doConnect():"); e.printStackTrace(); } finally { if (mConnectingThread != null) synchronized(mConnectingThread) { mConnectingThread = null; } } } }; mConnectingThread.start(); }"
Inversion-Mutation
megadiff
"public static void main(String[] args) throws FileNotFoundException, IOException, KettleXMLException { Properties properties = new Properties(); properties.load(new FileInputStream(new File(args[0]))); SharedObjects sharedObjects = new SharedObjects(args[1], new ArrayList(), new Hashtable()); DatabaseMeta mysql = new DatabaseMeta("MySQL EC2", "MySQL", "JDBC", null, "test", "3306", "matt", "abcd"); ClusterSchema clusterSchema = new ClusterSchema(); clusterSchema.setName(args[2]); clusterSchema.setBasePort("40000"); clusterSchema.setSocketsBufferSize("100000"); clusterSchema.setSocketsFlushInterval("0"); clusterSchema.setSocketsCompressed(true); int max = 1; while (properties.getProperty(PREFIX+max+IP)!=null) max++; max--; mysql.setPartitioned(true); PartitionDatabaseMeta[] partDbMeta = new PartitionDatabaseMeta[max]; for (int i=1;i<=max;i++) { String serverIp = properties.getProperty(PREFIX+i+IP); String serverPort = properties.getProperty(PREFIX+i+PORT); partDbMeta[i-1] = new PartitionDatabaseMeta("P"+i, serverIp, "3306", "test"); if (i==1) // use the first as the master { // add the master clusterSchema.getSlaveServers().add(new SlaveServer(serverIp, serverPort, "cluster", "cluster", null, null, null, true)); mysql.setHostname(serverIp); if (max==1) // if there is just one server here, so we add a slave too besides the master { clusterSchema.getSlaveServers().add(new SlaveServer(serverIp, serverPort, "cluster", "cluster")); } } else { // Add a slave server clusterSchema.getSlaveServers().add(new SlaveServer(serverIp, serverPort, "cluster", "cluster")); } } sharedObjects.storeObject(clusterSchema); mysql.setPartitioningInformation(partDbMeta); sharedObjects.storeObject(mysql); sharedObjects.saveToFile(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main"
"public static void main(String[] args) throws FileNotFoundException, IOException, KettleXMLException { Properties properties = new Properties(); properties.load(new FileInputStream(new File(args[0]))); SharedObjects sharedObjects = new SharedObjects(args[1], new ArrayList(), new Hashtable()); DatabaseMeta mysql = new DatabaseMeta("MySQL EC2", "MySQL", "JDBC", null, "test", "3306", "matt", "abcd"); ClusterSchema clusterSchema = new ClusterSchema(); clusterSchema.setName(args[2]); clusterSchema.setBasePort("40000"); clusterSchema.setSocketsBufferSize("100000"); clusterSchema.setSocketsFlushInterval("0"); clusterSchema.setSocketsCompressed(true); int max = 1; while (properties.getProperty(PREFIX+max+IP)!=null) max++; max--; mysql.setPartitioned(true); PartitionDatabaseMeta[] partDbMeta = new PartitionDatabaseMeta[max]; for (int i=1;i<=max;i++) { String serverIp = properties.getProperty(PREFIX+i+IP); String serverPort = properties.getProperty(PREFIX+i+PORT); if (i==1) // use the first as the master { // add the master clusterSchema.getSlaveServers().add(new SlaveServer(serverIp, serverPort, "cluster", "cluster", null, null, null, true)); mysql.setHostname(serverIp); <MASK>partDbMeta[i-1] = new PartitionDatabaseMeta("P"+i, serverIp, "3306", "test");</MASK> if (max==1) // if there is just one server here, so we add a slave too besides the master { clusterSchema.getSlaveServers().add(new SlaveServer(serverIp, serverPort, "cluster", "cluster")); } } else { // Add a slave server clusterSchema.getSlaveServers().add(new SlaveServer(serverIp, serverPort, "cluster", "cluster")); } } sharedObjects.storeObject(clusterSchema); mysql.setPartitioningInformation(partDbMeta); sharedObjects.storeObject(mysql); sharedObjects.saveToFile(); }"
Inversion-Mutation
megadiff
"public void propertyChange(PropertyChangeEvent evt) { if ("model".equals(evt.getPropertyName())) { hidePopup(); if (evt.getOldValue() instanceof ComboBoxModel) { ((ComboBoxModel) evt.getOldValue()).removeListDataListener(this); } if (evt.getNewValue() instanceof ComboBoxModel) { ((ComboBoxModel) evt.getNewValue()).addListDataListener(this); } fireSearchableEvent(new SearchableEvent(this, SearchableEvent.SEARCHABLE_MODEL_CHANGE)); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "propertyChange"
"public void propertyChange(PropertyChangeEvent evt) { if ("model".equals(evt.getPropertyName())) { hidePopup(); if (evt.getOldValue() instanceof ComboBoxModel) { ((ComboBoxModel) evt.getOldValue()).removeListDataListener(this); } if (evt.getNewValue() instanceof ComboBoxModel) { ((ComboBoxModel) evt.getNewValue()).addListDataListener(this); } } <MASK>fireSearchableEvent(new SearchableEvent(this, SearchableEvent.SEARCHABLE_MODEL_CHANGE));</MASK> }"
Inversion-Mutation
megadiff
"@SuppressWarnings( "unchecked" ) public Collection<File> buildClasspathList( final MavenProject project, final String scope, Set<Artifact> artifacts ) throws ClasspathBuilderException { getLogger().debug( "establishing classpath list (scope = " + scope + ")" ); Set<File> items = new LinkedHashSet<File>(); // Note : Don't call addSourceWithActiveProject as a GWT dependency MUST be a valid GWT library module : // * include java sources in the JAR as resources // * define a gwt.xml module file to declare the required inherits // addSourceWithActiveProject would make some java sources available to GWT compiler that should not be accessible in // a non-reactor build, making the build less deterministic and encouraging bad design. items.add( new File( project.getBuild().getOutputDirectory() ) ); addSources( items, project.getCompileSourceRoots() ); addResources( items, project.getResources() ); // Use our own ClasspathElements fitering, as for RUNTIME we need to include PROVIDED artifacts, // that is not the default Maven policy, as RUNTIME is used here to build the GWTShell execution classpath if ( scope.equals( SCOPE_TEST ) ) { addSources( items, project.getTestCompileSourceRoots() ); addResources( items, project.getTestResources() ); items.add( new File( project.getBuild().getTestOutputDirectory() ) ); // Add all project dependencies in classpath for ( Artifact artifact : artifacts ) { items.add( artifact.getFile() ); } } else if ( scope.equals( SCOPE_COMPILE ) ) { // Add all project dependencies in classpath getLogger().debug( "candidate artifacts : " + artifacts.size() ); for ( Artifact artifact : artifacts ) { String artifactScope = artifact.getScope(); if ( SCOPE_COMPILE.equals( artifactScope ) || SCOPE_PROVIDED.equals( artifactScope ) || SCOPE_SYSTEM.equals( artifactScope ) ) { items.add( artifact.getFile() ); } } } else if ( scope.equals( SCOPE_RUNTIME ) ) { // Add all dependencies BUT "TEST" as we need PROVIDED ones to setup the execution // GWTShell that is NOT a full JEE server for ( Artifact artifact : artifacts ) { getLogger().debug( "candidate artifact : " + artifact ); if ( !artifact.getScope().equals( SCOPE_TEST ) && artifact.getArtifactHandler().isAddedToClasspath() ) { items.add( artifact.getFile() ); } } } else { throw new ClasspathBuilderException( "unsupported scope " + scope ); } return items; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "buildClasspathList"
"@SuppressWarnings( "unchecked" ) public Collection<File> buildClasspathList( final MavenProject project, final String scope, Set<Artifact> artifacts ) throws ClasspathBuilderException { getLogger().debug( "establishing classpath list (scope = " + scope + ")" ); Set<File> items = new LinkedHashSet<File>(); // Note : Don't call addSourceWithActiveProject as a GWT dependency MUST be a valid GWT library module : // * include java sources in the JAR as resources // * define a gwt.xml module file to declare the required inherits // addSourceWithActiveProject would make some java sources available to GWT compiler that should not be accessible in // a non-reactor build, making the build less deterministic and encouraging bad design. addSources( items, project.getCompileSourceRoots() ); addResources( items, project.getResources() ); <MASK>items.add( new File( project.getBuild().getOutputDirectory() ) );</MASK> // Use our own ClasspathElements fitering, as for RUNTIME we need to include PROVIDED artifacts, // that is not the default Maven policy, as RUNTIME is used here to build the GWTShell execution classpath if ( scope.equals( SCOPE_TEST ) ) { addSources( items, project.getTestCompileSourceRoots() ); addResources( items, project.getTestResources() ); items.add( new File( project.getBuild().getTestOutputDirectory() ) ); // Add all project dependencies in classpath for ( Artifact artifact : artifacts ) { items.add( artifact.getFile() ); } } else if ( scope.equals( SCOPE_COMPILE ) ) { // Add all project dependencies in classpath getLogger().debug( "candidate artifacts : " + artifacts.size() ); for ( Artifact artifact : artifacts ) { String artifactScope = artifact.getScope(); if ( SCOPE_COMPILE.equals( artifactScope ) || SCOPE_PROVIDED.equals( artifactScope ) || SCOPE_SYSTEM.equals( artifactScope ) ) { items.add( artifact.getFile() ); } } } else if ( scope.equals( SCOPE_RUNTIME ) ) { // Add all dependencies BUT "TEST" as we need PROVIDED ones to setup the execution // GWTShell that is NOT a full JEE server for ( Artifact artifact : artifacts ) { getLogger().debug( "candidate artifact : " + artifact ); if ( !artifact.getScope().equals( SCOPE_TEST ) && artifact.getArtifactHandler().isAddedToClasspath() ) { items.add( artifact.getFile() ); } } } else { throw new ClasspathBuilderException( "unsupported scope " + scope ); } return items; }"
Inversion-Mutation
megadiff
"@Override public boolean onCommand(final CommandSender sender, Command cmd, String label, String[] args) { // If the player typed /tardis then do the following... // check there is the right number of arguments if (cmd.getName().equalsIgnoreCase("tardis")) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); return true; } // the command list - first argument MUST appear here! if (!firstArgs.contains(args[0].toLowerCase(Locale.ENGLISH))) { sender.sendMessage(plugin.pluginName + "That command wasn't recognised type " + ChatColor.GREEN + "/tardis help" + ChatColor.RESET + " to see the commands"); return false; } // delete the TARDIS if (args[0].equalsIgnoreCase("exterminate")) { if (player == null) { sender.sendMessage(plugin.pluginName + "You must be a player to run this command!"); return false; } if (!plugin.trackExterminate.containsKey(player.getName())) { sender.sendMessage(plugin.pluginName + "You must break the TARDIS Police Box sign first!"); return false; } TARDISExterminator del = new TARDISExterminator(plugin); return del.exterminate(player, plugin.trackExterminate.get(player.getName())); } // temporary command to convert old gravity well to new style if (args[0].equalsIgnoreCase("gravity")) { if (player == null) { sender.sendMessage(plugin.pluginName + "Must be a player"); return false; } // get the players TARDIS id HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); try { TARDISDatabase service = TARDISDatabase.getInstance(); Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String query = "SELECT * FROM gravity WHERE tardis_id = " + id; ResultSet rsg = statement.executeQuery(query); if (rsg.isBeforeFirst()) { String up = "Location{world=" + rsg.getString("world") + ",x=" + rsg.getFloat("upx") + ",y=10.0,z=" + rsg.getFloat("upz") + ",pitch=0.0,yaw=0.0}"; Double[] values = new Double[3]; values[0] = 1D; values[1] = 11D; values[2] = 0.5D; plugin.gravityUpList.put(up, values); String down = "Location{world=" + rsg.getString("world") + ",x=" + rsg.getFloat("downx") + ",y=10.0,z=" + rsg.getFloat("downz") + ",pitch=0.0,yaw=0.0}"; plugin.gravityDownList.add(down); HashMap<String, Object> setu = new HashMap<String, Object>(); setu.put("tardis_id", id); setu.put("location", up); setu.put("direction", 1); setu.put("distance", 11); setu.put("velocity", 0.5); HashMap<String, Object> setd = new HashMap<String, Object>(); setd.put("tardis_id", id); setd.put("location", down); setd.put("direction", 0); setd.put("distance", 0); setd.put("velocity", 0); QueryFactory qf = new QueryFactory(plugin); qf.doInsert("gravity_well", setu); qf.doInsert("gravity_well", setd); player.sendMessage(plugin.pluginName + "Gravity well converted successfully."); return true; } } catch (SQLException e) { plugin.debug("Gravity conversion error: " + e.getMessage()); } } if (args[0].equalsIgnoreCase("version")) { FileConfiguration pluginYml = YamlConfiguration.loadConfiguration(plugin.pm.getPlugin("TARDIS").getResource("plugin.yml")); String version = pluginYml.getString("version"); String cb = Bukkit.getVersion(); sender.sendMessage(plugin.pluginName + "You are running TARDIS version: " + ChatColor.AQUA + version + ChatColor.RESET + " with CraftBukkit " + cb); // also check if there is an update if (plugin.getConfig().getBoolean("check_for_updates")) { TARDISUpdateChecker update = new TARDISUpdateChecker(plugin); update.checkVersion(player); } return true; } if (player == null) { sender.sendMessage(plugin.pluginName + ChatColor.RED + " This command can only be run by a player"); return false; } else { if (args[0].equalsIgnoreCase("lamps")) { TARDISLampScanner tls = new TARDISLampScanner(plugin); return tls.addLampBlocks(player); } if (args[0].equalsIgnoreCase("chameleon")) { if (!plugin.getConfig().getBoolean("chameleon")) { sender.sendMessage(plugin.pluginName + "This server does not allow the use of the chameleon circuit!"); return false; } if (player.hasPermission("tardis.timetravel")) { if (args.length < 2 || (!args[1].equalsIgnoreCase("on") && !args[1].equalsIgnoreCase("off") && !args[1].equalsIgnoreCase("short") && !args[1].equalsIgnoreCase("reset"))) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } // get the players TARDIS id HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); String chamStr = rs.getChameleon(); if (chamStr.isEmpty()) { sender.sendMessage(plugin.pluginName + "Could not find the Chameleon Circuit!"); return false; } else { QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); if (args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("off")) { int x, y, z; String[] chamData = chamStr.split(":"); World w = plugin.getServer().getWorld(chamData[0]); TARDISConstants.COMPASS d = rs.getDirection(); x = plugin.utils.parseNum(chamData[1]); y = plugin.utils.parseNum(chamData[2]); z = plugin.utils.parseNum(chamData[3]); Block chamBlock = w.getBlockAt(x, y, z); Material chamType = chamBlock.getType(); if (chamType == Material.WALL_SIGN || chamType == Material.SIGN_POST) { Sign cs = (Sign) chamBlock.getState(); if (args[1].equalsIgnoreCase("on")) { set.put("chamele_on", 1); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was turned ON!"); cs.setLine(3, ChatColor.GREEN + "ON"); } if (args[1].equalsIgnoreCase("off")) { set.put("chamele_on", 0); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was turned OFF."); cs.setLine(3, ChatColor.RED + "OFF"); } cs.update(); } } int dwid = plugin.getConfig().getInt("wall_id"); int dwd = plugin.getConfig().getInt("wall_data"); if (args[1].equalsIgnoreCase("short")) { // get the block the player is targeting Block target_block = player.getTargetBlock(transparent, 50).getLocation().getBlock(); TARDISChameleonCircuit tcc = new TARDISChameleonCircuit(plugin); int[] b_data = tcc.getChameleonBlock(target_block, player, true); int c_id = b_data[0], c_data = b_data[1]; set.put("chameleon_id", c_id); set.put("chameleon_data", c_data); qf.doUpdate("tardis", set, tid); boolean bluewool = (c_id == dwid && c_data == (byte) dwd); if (!bluewool) { sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was shorted out to: " + target_block.getType().toString() + "."); } } if (args[1].equalsIgnoreCase("reset")) { // set.put("chameleon_id", 35); // set.put("chameleon_data", 11); set.put("chameleon_id", dwid); set.put("chameleon_data", dwd); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was repaired."); } } return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("rescue")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "Too few command arguments!"); return true; } if (player.hasPermission("tardis.timetravel.player")) { final String saved = args[1]; Player destPlayer = plugin.getServer().getPlayer(saved); if (destPlayer == null) { player.sendMessage(plugin.pluginName + "That player is not online!"); return true; } String playerNameStr = player.getName(); destPlayer.sendMessage(plugin.pluginName + playerNameStr + "wants to rescue you! Type: " + ChatColor.AQUA + "tardis rescue accept" + ChatColor.RESET + " in chat within 60 seconds to accept the rescue."); plugin.trackChat.put(saved, playerNameStr); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { if (plugin.trackChat.containsKey(saved)) { plugin.trackChat.remove(saved); sender.sendMessage(plugin.pluginName + saved + " didn't respond with 60 seconds, aborting rescue!"); } } }, 1200L); } else { player.sendMessage(plugin.pluginName + "You do not have permission to time travel to a player!"); return true; } } if (args[0].equalsIgnoreCase("room")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String room = args[1].toUpperCase(Locale.ENGLISH); StringBuilder buf = new StringBuilder(); for (String rl : roomArgs) { buf.append(rl).append(", "); } String roomlist = buf.toString().substring(0, buf.length() - 2); if (room.equals("HELP")) { player.sendMessage(plugin.pluginName + "There are currently " + roomArgs.size() + " room types! They are: " + roomlist + "."); player.sendMessage("View a TARDIS room gallery at http://eccentricdevotion.github.com/TARDIS/room-gallery.html"); return true; } if (!roomArgs.contains(room)) { player.sendMessage(plugin.pluginName + "That is not a valid room type! Try one of: " + roomlist + "."); return true; } String perm = "tardis.room." + args[1].toLowerCase(Locale.ENGLISH); if (!player.hasPermission(perm) && !player.hasPermission("tardis.room")) { String grammar = (TARDISConstants.vowels.contains(room.substring(0, 1))) ? "an" : "a"; sender.sendMessage(plugin.pluginName + "You do not have permission to grow " + grammar + " " + room); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { player.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return true; } String chunk = rs.getChunk(); String[] data = chunk.split(":"); World room_world = plugin.getServer().getWorld(data[0]); ChunkGenerator gen = room_world.getGenerator(); WorldType wt = room_world.getWorldType(); boolean special = (data[0].contains("TARDIS_TimeVortex") && (wt.equals(WorldType.FLAT) || gen instanceof TARDISChunkGenerator)); if (!data[0].contains("TARDIS_WORLD_") && !special) { player.sendMessage(plugin.pluginName + "You cannot grow rooms unless your TARDIS was created in its own world!"); return true; } int id = rs.getTardis_id(); int level = rs.getArtron_level(); // check they are in the tardis HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); wheret.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { player.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return true; } // check they have enough artron energy if (level < plugin.getRoomsConfig().getInt("rooms." + room + ".cost")) { player.sendMessage(plugin.pluginName + "The TARDIS does not have enough Artron Energy to grow this room!"); return true; } if (plugin.getConfig().getBoolean("rooms_require_blocks")) { HashMap<String, Integer> blockIDCount = new HashMap<String, Integer>(); boolean hasRequired = true; HashMap<String, Integer> roomBlocks = plugin.roomBlockCounts.get(room); String wall = "ORANGE_WOOL"; String floor = "LIGHT_GREY_WOOL"; HashMap<String, Object> wherepp = new HashMap<String, Object>(); boolean hasPrefs = false; wherepp.put("player", player.getName()); ResultSetPlayerPrefs rsp = new ResultSetPlayerPrefs(plugin, wherepp); if (rsp.resultSet()) { hasPrefs = true; wall = rsp.getWall(); floor = rsp.getFloor(); } for (Map.Entry<String, Integer> entry : roomBlocks.entrySet()) { String[] block_data = entry.getKey().split(":"); int bid = plugin.utils.parseNum(block_data[0]); String mat; String bdata; if (hasPrefs && block_data.length == 2 && (block_data[1].equals("1") || block_data[1].equals("8"))) { mat = (block_data[1].equals("1")) ? wall : floor; TARDISWalls tw = new TARDISWalls(); Integer[] iddata = tw.blocks.get(mat); bdata = String.format("%d", iddata[0]); } else { mat = Material.getMaterial(bid).toString(); bdata = String.format("%d", bid); } int tmp = Math.round((entry.getValue() / 100.0F) * plugin.getConfig().getInt("rooms_condenser_percent")); int required = (tmp > 0) ? tmp : 1; blockIDCount.put(bdata, required); HashMap<String, Object> wherec = new HashMap<String, Object>(); wherec.put("tardis_id", id); wherec.put("block_data", bdata); ResultSetCondenser rsc = new ResultSetCondenser(plugin, wherec, false); if (rsc.resultSet()) { if (rsc.getBlock_count() < required) { hasRequired = false; int diff = required - rsc.getBlock_count(); player.sendMessage(plugin.pluginName + "You need to condense " + diff + " more " + mat + "!"); } } else { hasRequired = false; player.sendMessage(plugin.pluginName + "You need to condense a minimum of " + required + " " + mat); } } if (hasRequired == false) { player.sendMessage("-----------------------------"); return true; } TARDISCondenserData c_data = new TARDISCondenserData(); c_data.setBlockIDCount(blockIDCount); c_data.setTardis_id(id); plugin.roomCondenserData.put(player.getName(), c_data); } String message; // if it is a gravity well if (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) { message = "Place the GRAVITY WELL seed block (" + plugin.getRoomsConfig().getString("rooms." + room + ".seed") + ") into the centre of the floor in an empty room, then hit it with the TARDIS key to start growing your room!"; } else { message = "Place the " + room + " seed block (" + plugin.getRoomsConfig().getString("rooms." + room + ".seed") + ") where the door should be, then hit it with the TARDIS key to start growing your room!"; } plugin.trackRoomSeed.put(player.getName(), room); player.sendMessage(plugin.pluginName + message); return true; } if (args[0].equalsIgnoreCase("jettison")) { if (player.hasPermission("tardis.room")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String room = args[1].toUpperCase(Locale.ENGLISH); if (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) { player.sendMessage(plugin.pluginName + "You cannot jettison gravity wells! To remove the gravity blocks use the " + ChatColor.AQUA + "/tardisgravity remove" + ChatColor.RESET + " command."); return true; } if (!roomArgs.contains(room)) { StringBuilder buf = new StringBuilder(args[1]); for (String rl : roomArgs) { buf.append(rl).append(", "); } String roomlist = buf.toString().substring(0, buf.length() - 2); player.sendMessage(plugin.pluginName + "That is not a valid room type! Try one of: " + roomlist); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { player.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return true; } int id = rs.getTardis_id(); // check they are in the tardis HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); wheret.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { player.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return true; } plugin.trackJettison.put(player.getName(), room); String seed = plugin.getArtronConfig().getString("jettison_seed"); player.sendMessage(plugin.pluginName + "Stand in the doorway of the room you want to jettison and place a " + seed + " block directly in front of the door. Hit the " + seed + " with the TARDIS key to jettison the room!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("abort")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "You must specify the task ID number!"); return false; } try { int task = Integer.parseInt(args[1]); plugin.getServer().getScheduler().cancelTask(task); player.sendMessage(plugin.pluginName + "Task aborted!"); return true; } catch (NumberFormatException nfe) { player.sendMessage(plugin.pluginName + "Task ID is not a number!"); return false; } } if (args[0].equalsIgnoreCase("occupy")) { if (player.hasPermission("tardis.timetravel")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + " You must be the Timelord of the TARDIS to use this command!"); return false; } int id = rs.getTardis_id(); HashMap<String, Object> wheret = new HashMap<String, Object>(); //wheret.put("tardis_id", id); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); String occupied; QueryFactory qf = new QueryFactory(plugin); if (rst.resultSet()) { HashMap<String, Object> whered = new HashMap<String, Object>(); //whered.put("tardis_id", id); whered.put("player", player.getName()); qf.doDelete("travellers", whered); occupied = ChatColor.RED + "UNOCCUPIED"; } else { HashMap<String, Object> wherei = new HashMap<String, Object>(); wherei.put("tardis_id", id); wherei.put("player", player.getName()); qf.doInsert("travellers", wherei); occupied = ChatColor.GREEN + "OCCUPIED"; } sender.sendMessage(plugin.pluginName + " TARDIS occupation was set to: " + occupied); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("comehere")) { if (plugin.getConfig().getString("difficulty").equalsIgnoreCase("easy")) { if (player.hasPermission("tardis.timetravel")) { final Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && eyeLocation.getWorld().getName().equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to bring the TARDIS to this world!"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, eyeLocation, true)) { return true; } if (player.hasPermission("tardis.exile") && plugin.getConfig().getBoolean("exile")) { String areaPerm = plugin.ta.getExileArea(player); if (plugin.ta.areaCheckInExile(areaPerm, eyeLocation)) { sender.sendMessage(plugin.pluginName + "You exile status does not allow you to bring the TARDIS to this location!"); return true; } } if (!plugin.ta.areaCheckInExisting(eyeLocation)) { sender.sendMessage(plugin.pluginName + "You cannot use /tardis comehere to bring the Police Box to a TARDIS area! Please use " + ChatColor.AQUA + "/tardistravel area [area name]"); return true; } Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check the world is not excluded String world = eyeLocation.getWorld().getName(); if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot bring the TARDIS Police Box to this world"); return true; } // check they are a timelord HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); final ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of the TARDIS to use this command!"); return true; } final int id = rs.getTardis_id(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot bring the Police Box here because you are inside a TARDIS!"); return true; } if (plugin.tardisMaterialising.contains(id) || plugin.tardisDematerialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } final TARDISConstants.COMPASS d = rs.getDirection(); TARDISTimeTravel tt = new TARDISTimeTravel(plugin); int count; String sub = "false"; Block b = eyeLocation.getBlock(); if (b.getRelative(BlockFace.UP).getTypeId() == 8 || b.getRelative(BlockFace.UP).getTypeId() == 9) { count = (tt.isSafeSubmarine(eyeLocation, d)) ? 0 : 1; if (count == 0) { plugin.trackSubmarine.add(id); sub = "true"; } } else { if (plugin.trackSubmarine.contains(Integer.valueOf(id))) { plugin.trackSubmarine.remove(Integer.valueOf(id)); } int[] start_loc = tt.getStartLocation(eyeLocation, d); // safeLocation(int startx, int starty, int startz, int resetx, int resetz, World w, TARDISConstants.COMPASS d) count = tt.safeLocation(start_loc[0], eyeLocation.getBlockY(), start_loc[2], start_loc[1], start_loc[3], eyeLocation.getWorld(), d); } if (count > 0) { sender.sendMessage(plugin.pluginName + "That location would grief existing blocks! Try somewhere else!"); return true; } int level = rs.getArtron_level(); int ch = plugin.getArtronConfig().getInt("comehere"); if (level < ch) { player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to make this trip!"); return true; } final Player p = player; String current_str = rs.getCurrent(); boolean chamtmp = false; if (plugin.getConfig().getBoolean("chameleon")) { chamtmp = rs.isChamele_on(); } final boolean cham = chamtmp; String[] saveData = current_str.split(":"); World w = plugin.getServer().getWorld(saveData[0]); if (w != null) { int x, y, z; x = plugin.utils.parseNum(saveData[1]); y = plugin.utils.parseNum(saveData[2]); z = plugin.utils.parseNum(saveData[3]); final Location oldSave = w.getBlockAt(x, y, z).getLocation(); String comehere = eyeLocation.getWorld().getName() + ":" + eyeLocation.getBlockX() + ":" + eyeLocation.getBlockY() + ":" + eyeLocation.getBlockZ() + ":" + d.toString() + ":" + sub; final boolean hidden = rs.isHidden(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("save", comehere); set.put("current", comehere); if (hidden) { set.put("hidden", 0); } qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The TARDIS is coming..."); final boolean mat = plugin.getConfig().getBoolean("materialise"); long delay = (mat) ? 1L : 180L; Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { if (!hidden) { plugin.tardisDematerialising.add(id); plugin.destroyPB.destroyPoliceBox(oldSave, d, id, false, mat, cham, p); } } }, delay); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.buildPB.buildPoliceBox(id, eyeLocation, d, cham, p, false, false); } }, delay * 2); // remove energy from TARDIS HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); qf.alterEnergyLevel("tardis", -ch, wheret, player); plugin.tardisHasDestination.remove(id); if (plugin.trackRescue.containsKey(Integer.valueOf(id))) { plugin.trackRescue.remove(Integer.valueOf(id)); } return true; } else { sender.sendMessage(plugin.pluginName + "Could not get the previous location of the TARDIS!"); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } else { sender.sendMessage(plugin.pluginName + "You need to craft a Stattenheim Remote Control! Type " + ChatColor.AQUA + "/tardisrecipe remote" + ChatColor.RESET + " to see how to make it."); return true; } } if (args[0].equalsIgnoreCase("check_loc")) { final Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check they are a timelord HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of a TARDIS to use this command!"); return true; } final TARDISConstants.COMPASS d = rs.getDirection(); TARDISTimeTravel tt = new TARDISTimeTravel(plugin); tt.testSafeLocation(eyeLocation, d); return true; } if (args[0].equalsIgnoreCase("inside")) { // check they are a timelord HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of a TARDIS to use this command!"); return true; } int id = rs.getTardis_id(); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, true); if (rst.resultSet()) { List<String> data = rst.getData(); sender.sendMessage(plugin.pluginName + "The players inside your TARDIS are:"); for (String s : data) { sender.sendMessage(s); } } else { sender.sendMessage(plugin.pluginName + "Nobody is inside your TARDIS."); } return true; } if (args[0].equalsIgnoreCase("home")) { if (player.hasPermission("tardis.timetravel")) { Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && eyeLocation.getWorld().getName().equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to set the TARDIS home in this world!"); return true; } if (!plugin.ta.areaCheckInExisting(eyeLocation)) { sender.sendMessage(plugin.pluginName + "You cannot use /tardis home in a TARDIS area! Please use " + ChatColor.AQUA + "/tardistravel area [area name]"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, eyeLocation, true)) { return true; } Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check the world is not excluded String world = eyeLocation.getWorld().getName(); if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot set the TARDIS home location to this world"); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of the TARDIS to use this command!"); return false; } int id = rs.getTardis_id(); String direction = rs.getDirection().toString(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot set the home location here because you are inside a TARDIS!"); return true; } String sethome = eyeLocation.getWorld().getName() + ":" + eyeLocation.getBlockX() + ":" + eyeLocation.getBlockY() + ":" + eyeLocation.getBlockZ() + ":" + direction; QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("home", sethome); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The new TARDIS home was set!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("update")) { if (player.hasPermission("tardis.update")) { String[] validBlockNames = {"door", "button", "world-repeater", "x-repeater", "z-repeater", "y-repeater", "chameleon", "save-sign", "artron", "handbrake", "condenser", "scanner", "backdoor", "keyboard", "creeper", "eps", "back", "terminal", "ars", "temporal", "light", "farm", "stable", "rail", "info"}; if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String tardis_block = args[1].toLowerCase(Locale.ENGLISH); if (!Arrays.asList(validBlockNames).contains(tardis_block)) { player.sendMessage(plugin.pluginName + "That is not a valid TARDIS block name! Try one of : door|button|world-repeater|x-repeater|z-repeater|y-repeater|chameleon|save-sign|artron|handbrake|condenser|scanner|backdoor|keyboard|creeper|eps|back|terminal|ars|temporal|light|farm|stable|rail|info"); return false; } if (tardis_block.equals("backdoor") && !player.hasPermission("tardis.backdoor")) { sender.sendMessage(plugin.pluginName + "You do not have permission to create a back door!"); return true; } if (tardis_block.equals("temporal") && !player.hasPermission("tardis.temporal")) { sender.sendMessage(plugin.pluginName + "You do not have permission to create a Temporal Locator!"); return true; } if ((tardis_block.equals("farm") || tardis_block.equals("stable")) && !player.hasPermission("tardis.farm")) { sender.sendMessage(plugin.pluginName + "You do not have permission to update the " + tardis_block + "!"); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return false; } String rail = rs.getRail(); if (!tardis_block.equals("backdoor")) { HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return false; } } if (tardis_block.equals("rail") && rail.isEmpty()) { player.sendMessage(plugin.pluginName + "You need to grow a rail room before you can update its position."); return true; } plugin.trackPlayers.put(player.getName(), tardis_block); player.sendMessage(plugin.pluginName + "Click the TARDIS " + tardis_block + " to update its position."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("secondary")) { if (player.hasPermission("tardis.update")) { String[] validBlockNames = {"button", "world-repeater", "x-repeater", "z-repeater", "y-repeater", "artron", "handbrake", "door", "back"}; if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String tardis_block = args[1].toLowerCase(Locale.ENGLISH); if (!Arrays.asList(validBlockNames).contains(tardis_block)) { player.sendMessage(plugin.pluginName + "That is not a valid TARDIS block name! Try one of : button|world-repeater|x-repeater|z-repeater|y-repeater|artron|handbrake|door|back"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return false; } HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return false; } plugin.trackSecondary.put(player.getName(), tardis_block); player.sendMessage(plugin.pluginName + "Click the TARDIS " + tardis_block + " to update its position."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("rebuild") || args[0].equalsIgnoreCase("hide")) { if (player.hasPermission("tardis.rebuild")) { String save; World w; int x, y, z, id; TARDISConstants.COMPASS d; boolean cham = false; HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } id = rs.getTardis_id(); HashMap<String, Object> wherein = new HashMap<String, Object>(); wherein.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherein, false); if (rst.resultSet() && args[0].equalsIgnoreCase("rebuild") && plugin.tardisHasDestination.containsKey(id)) { sender.sendMessage(plugin.pluginName + "You cannot rebuild the TARDIS right now! Try travelling first."); return true; } int level = rs.getArtron_level(); save = rs.getCurrent(); if (plugin.tardisMaterialising.contains(id) || plugin.tardisDematerialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } if (plugin.getConfig().getBoolean("chameleon")) { cham = rs.isChamele_on(); } d = rs.getDirection(); String[] save_data = save.split(":"); w = plugin.getServer().getWorld(save_data[0]); x = plugin.utils.parseNum(save_data[1]); y = plugin.utils.parseNum(save_data[2]); z = plugin.utils.parseNum(save_data[3]); Location l = new Location(w, x, y, z); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); QueryFactory qf = new QueryFactory(plugin); if (args[0].equalsIgnoreCase("rebuild")) { int rebuild = plugin.getArtronConfig().getInt("random"); if (level < rebuild) { player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to rebuild!"); return false; } plugin.buildPB.buildPoliceBox(id, l, d, cham, player, true, false); sender.sendMessage(plugin.pluginName + "The TARDIS Police Box was rebuilt!"); qf.alterEnergyLevel("tardis", -rebuild, wheret, player); // set hidden to false if (rs.isHidden()) { HashMap<String, Object> whereh = new HashMap<String, Object>(); whereh.put("tardis_id", id); HashMap<String, Object> seth = new HashMap<String, Object>(); seth.put("hidden", 0); qf.doUpdate("tardis", seth, whereh); } return true; } if (args[0].equalsIgnoreCase("hide")) { int hide = plugin.getArtronConfig().getInt("hide"); if (level < hide) { player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to hide!"); return false; } plugin.destroyPB.destroyPoliceBox(l, d, id, true, false, false, null); sender.sendMessage(plugin.pluginName + "The TARDIS Police Box was hidden! Use " + ChatColor.GREEN + "/tardis rebuild" + ChatColor.RESET + " to show it again."); qf.alterEnergyLevel("tardis", -hide, wheret, player); // set hidden to true HashMap<String, Object> whereh = new HashMap<String, Object>(); whereh.put("tardis_id", id); HashMap<String, Object> seth = new HashMap<String, Object>(); seth.put("hidden", 1); qf.doUpdate("tardis", seth, whereh); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("list")) { if (player.hasPermission("tardis.list")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2 || (!args[1].equalsIgnoreCase("saves") && !args[1].equalsIgnoreCase("companions") && !args[1].equalsIgnoreCase("areas") && !args[1].equalsIgnoreCase("rechargers"))) { sender.sendMessage(plugin.pluginName + "You need to specify which TARDIS list you want to view! [saves|companions|areas|rechargers]"); return false; } TARDISLister.list(player, args[1]); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("find")) { if (plugin.getConfig().getString("difficulty").equalsIgnoreCase("easy")) { if (player.hasPermission("tardis.find")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } String loc = rs.getCurrent(); String[] findData = loc.split(":"); sender.sendMessage(plugin.pluginName + "TARDIS was left at " + findData[0] + " at x: " + findData[1] + " y: " + findData[2] + " z: " + findData[3]); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } else { sender.sendMessage(plugin.pluginName + "You need to craft a TARDIS Locator! Type " + ChatColor.AQUA + "/tardisrecipe locator" + ChatColor.RESET + " to see how to make it."); return true; } } if (args[0].equalsIgnoreCase("add")) { if (player.hasPermission("tardis.add")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); String comps; int id; if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } else { id = rs.getTardis_id(); comps = rs.getCompanions(); } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid username"); return false; } else { QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); if (comps != null && !comps.isEmpty()) { // add to the list String newList = comps + ":" + args[1].toLowerCase(Locale.ENGLISH); set.put("companions", newList); } else { // make a list set.put("companions", args[1].toLowerCase(Locale.ENGLISH)); } qf.doUpdate("tardis", set, tid); player.sendMessage(plugin.pluginName + "You added " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); // are we doing an achievement? if (plugin.getAchivementConfig().getBoolean("friends.enabled")) { TARDISAchievementFactory taf = new TARDISAchievementFactory(plugin, player, "friends", 1); taf.doAchievement(1); } return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("remove")) { if (player.hasPermission("tardis.add")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); String comps; int id; if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } else { id = rs.getTardis_id(); comps = rs.getCompanions(); if (comps == null || comps.isEmpty()) { sender.sendMessage(plugin.pluginName + "You have not added any TARDIS companions yet!"); return true; } } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid username"); return false; } else { String[] split = comps.split(":"); StringBuilder buf = new StringBuilder(); String newList = ""; if (split.length > 1) { // recompile string without the specified player for (String c : split) { if (!c.equals(args[1].toLowerCase(Locale.ENGLISH))) { // add to new string buf.append(c).append(":"); } } // remove trailing colon if (buf.length() > 0) { newList = buf.toString().substring(0, buf.length() - 1); } } QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("companions", newList); qf.doUpdate("tardis", set, tid); player.sendMessage(plugin.pluginName + "You removed " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("save")) { if (player.hasPermission("tardis.save")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid save name (it may be too long or contains spaces)."); return false; } else { int id = rs.getTardis_id(); // get current destination String cur = rs.getCurrent(); String[] curDest = cur.split(":"); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> set = new HashMap<String, Object>(); set.put("tardis_id", id); set.put("dest_name", args[1]); set.put("world", curDest[0]); set.put("x", plugin.utils.parseNum(curDest[1])); set.put("y", plugin.utils.parseNum(curDest[2])); set.put("z", plugin.utils.parseNum(curDest[3])); set.put("direction", rs.getDirection().toString()); if (qf.doInsert("destinations", set) < 0) { return false; } else { sender.sendMessage(plugin.pluginName + "The location '" + args[1] + "' was saved successfully."); return true; } } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("removesave")) { if (player.hasPermission("tardis.save")) { if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("dest_name", args[1]); whered.put("tardis_id", id); ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false); if (!rsd.resultSet()) { sender.sendMessage(plugin.pluginName + "Could not find a saved destination with that name!"); return false; } int destID = rsd.getDest_id(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> did = new HashMap<String, Object>(); did.put("dest_id", destID); qf.doDelete("destinations", did); sender.sendMessage(plugin.pluginName + "The destination " + args[1] + " was deleted!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("setdest")) { if (player.hasPermission("tardis.save")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "The destination name must be between 2 and 16 characters and have no spaces!"); return false; } else if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { sender.sendMessage(plugin.pluginName + "That is a reserved destination name!"); return false; } else { int id = rs.getTardis_id(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot bring the Police Box here because you are inside a TARDIS!"); return true; } // get location player is looking at Block b = player.getTargetBlock(transparent, 50); Location l = b.getLocation(); if (!plugin.ta.areaCheckInExisting(l)) { sender.sendMessage(plugin.pluginName + "You cannot use /tardis setdest in a TARDIS area! Please use " + ChatColor.AQUA + "/tardistravel area [area name]"); return true; } String world = l.getWorld().getName(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && world.equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to set the TARDIS destination to this world!"); return true; } // check the world is not excluded if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot bring the TARDIS Police Box to this world"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, l, true)) { return true; } if (player.hasPermission("tardis.exile") && plugin.getConfig().getBoolean("exile")) { String areaPerm = plugin.ta.getExileArea(player); if (plugin.ta.areaCheckInExile(areaPerm, l)) { sender.sendMessage(plugin.pluginName + "You exile status does not allow you to save the TARDIS to this location!"); return false; } } String dw = l.getWorld().getName(); int dx = l.getBlockX(); int dy = l.getBlockY() + 1; int dz = l.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> set = new HashMap<String, Object>(); set.put("tardis_id", id); set.put("dest_name", args[1]); set.put("world", dw); set.put("x", dx); set.put("y", dy); set.put("z", dz); if (qf.doInsert("destinations", set) < 0) { return false; } else { sender.sendMessage(plugin.pluginName + "The destination '" + args[1] + "' was saved successfully."); return true; } } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("direction")) { if (player.hasPermission("tardis.timetravel")) { if (args.length < 2 || (!args[1].equalsIgnoreCase("north") && !args[1].equalsIgnoreCase("west") && !args[1].equalsIgnoreCase("south") && !args[1].equalsIgnoreCase("east"))) { sender.sendMessage(plugin.pluginName + "You need to specify the compass direction e.g. north, west, south or east!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); int level = rs.getArtron_level(); int amount = plugin.getArtronConfig().getInt("random"); if (level < amount) { sender.sendMessage(plugin.pluginName + "The TARDIS does not have enough Artron Energy to change the Police Box direction!"); return true; } String save = rs.getCurrent(); String[] save_data = save.split(":"); if (plugin.tardisMaterialising.contains(id) || plugin.tardisDematerialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } boolean cham = false; if (plugin.getConfig().getBoolean("chameleon")) { cham = rs.isChamele_on(); } String dir = args[1].toUpperCase(Locale.ENGLISH); TARDISConstants.COMPASS old_d = rs.getDirection(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("direction", dir); qf.doUpdate("tardis", set, tid); HashMap<String, Object> did = new HashMap<String, Object>(); HashMap<String, Object> setd = new HashMap<String, Object>(); did.put("door_type", 0); did.put("tardis_id", id); setd.put("door_direction", dir); qf.doUpdate("doors", setd, did); World w = plugin.getServer().getWorld(save_data[0]); int x = plugin.utils.parseNum(save_data[1]); int y = plugin.utils.parseNum(save_data[2]); int z = plugin.utils.parseNum(save_data[3]); Location l = new Location(w, x, y, z); TARDISConstants.COMPASS d = TARDISConstants.COMPASS.valueOf(dir); // destroy platform if (!rs.isHidden()) { plugin.destroyPB.destroyPlatform(rs.getPlatform(), id); plugin.destroyPB.destroySign(l, old_d); } plugin.buildPB.buildPoliceBox(id, l, d, cham, player, true, false); HashMap<String, Object> wherea = new HashMap<String, Object>(); wherea.put("tardis_id", id); qf.alterEnergyLevel("tardis", -amount, wherea, player); sender.sendMessage(plugin.pluginName + "You used " + amount + " Artron Energy changing the Police Box direction."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("namekey")) { if (plugin.bukkitversion.compareTo(plugin.preIMversion) < 0 || (plugin.bukkitversion.compareTo(plugin.preIMversion) == 0 && plugin.SUBversion.compareTo(plugin.preSUBversion) < 0)) { sender.sendMessage(plugin.pluginName + "You cannot rename the TARDIS key with this version of Bukkit!"); return true; } // determine key item String key; HashMap<String, Object> where = new HashMap<String, Object>(); where.put("player", player.getName()); ResultSetPlayerPrefs rsp = new ResultSetPlayerPrefs(plugin, where); if (rsp.resultSet()) { key = (!rsp.getKey().isEmpty()) ? rsp.getKey() : plugin.getConfig().getString("key"); } else { key = plugin.getConfig().getString("key"); } Material m = Material.getMaterial(key); if (m.equals(Material.AIR)) { sender.sendMessage(plugin.pluginName + "You cannot rename AIR!"); return true; } ItemStack is = player.getItemInHand(); if (!is.getType().equals(m)) { sender.sendMessage(plugin.pluginName + "You can only rename the TARDIS key!"); return true; } int count = args.length; if (count < 2) { return false; } StringBuilder buf = new StringBuilder(args[1]); for (int i = 2; i < count; i++) { buf.append(" ").append(args[i]); } String tmp = buf.toString(); if (!tmp.isEmpty()) { TARDISItemRenamer ir = new TARDISItemRenamer(is); ir.setName(tmp, false); sender.sendMessage(plugin.pluginName + "TARDIS key renamed to '" + tmp + "'"); return true; } else { return false; } } if (args[0].equalsIgnoreCase("help")) { if (args.length == 1) { sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); return true; } if (args.length == 2) { List<String> cmds = new ArrayList<String>(); for (TARDISConstants.CMDS c : TARDISConstants.CMDS.values()) { cmds.add(c.toString()); } // check that the second arument is valid if (!cmds.contains(args[1].toUpperCase(Locale.ENGLISH))) { sender.sendMessage(plugin.pluginName + "That is not a valid help topic!"); return true; } switch (TARDISConstants.fromString(args[1])) { case CREATE: sender.sendMessage(TARDISConstants.COMMAND_CREATE.split("\n")); break; case DELETE: sender.sendMessage(TARDISConstants.COMMAND_DELETE.split("\n")); break; case TIMETRAVEL: sender.sendMessage(TARDISConstants.COMMAND_TIMETRAVEL.split("\n")); break; case LIST: sender.sendMessage(TARDISConstants.COMMAND_LIST.split("\n")); break; case FIND: sender.sendMessage(TARDISConstants.COMMAND_FIND.split("\n")); break; case SAVE: sender.sendMessage(TARDISConstants.COMMAND_SAVE.split("\n")); break; case REMOVESAVE: sender.sendMessage(TARDISConstants.COMMAND_REMOVESAVE.split("\n")); break; case ADD: sender.sendMessage(TARDISConstants.COMMAND_ADD.split("\n")); break; case TRAVEL: sender.sendMessage(TARDISConstants.COMMAND_TRAVEL.split("\n")); break; case UPDATE: sender.sendMessage(TARDISConstants.COMMAND_UPDATE.split("\n")); break; case REBUILD: sender.sendMessage(TARDISConstants.COMMAND_REBUILD.split("\n")); break; case CHAMELEON: sender.sendMessage(TARDISConstants.COMMAND_CHAMELEON.split("\n")); break; case SFX: sender.sendMessage(TARDISConstants.COMMAND_SFX.split("\n")); break; case PLATFORM: sender.sendMessage(TARDISConstants.COMMAND_PLATFORM.split("\n")); break; case SETDEST: sender.sendMessage(TARDISConstants.COMMAND_SETDEST.split("\n")); break; case HOME: sender.sendMessage(TARDISConstants.COMMAND_HOME.split("\n")); break; case HIDE: sender.sendMessage(TARDISConstants.COMMAND_HIDE.split("\n")); break; case VERSION: sender.sendMessage(TARDISConstants.COMMAND_HIDE.split("\n")); break; case ADMIN: sender.sendMessage(TARDISConstants.COMMAND_ADMIN.split("\n")); break; case AREA: sender.sendMessage(TARDISConstants.COMMAND_AREA.split("\n")); break; case ROOM: sender.sendMessage(TARDISConstants.COMMAND_ROOM.split("\n")); break; case ARTRON: sender.sendMessage(TARDISConstants.COMMAND_ARTRON.split("\n")); break; case BIND: sender.sendMessage(TARDISConstants.COMMAND_BIND.split("\n")); break; default: sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); } } return true; } } } // If the above has happened the function will break and return true. if this hasn't happened then value of false will be returned. return false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCommand"
"@Override public boolean onCommand(final CommandSender sender, Command cmd, String label, String[] args) { // If the player typed /tardis then do the following... // check there is the right number of arguments if (cmd.getName().equalsIgnoreCase("tardis")) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); return true; } // the command list - first argument MUST appear here! if (!firstArgs.contains(args[0].toLowerCase(Locale.ENGLISH))) { sender.sendMessage(plugin.pluginName + "That command wasn't recognised type " + ChatColor.GREEN + "/tardis help" + ChatColor.RESET + " to see the commands"); return false; } // delete the TARDIS if (args[0].equalsIgnoreCase("exterminate")) { if (player == null) { sender.sendMessage(plugin.pluginName + "You must be a player to run this command!"); return false; } if (!plugin.trackExterminate.containsKey(player.getName())) { sender.sendMessage(plugin.pluginName + "You must break the TARDIS Police Box sign first!"); return false; } TARDISExterminator del = new TARDISExterminator(plugin); return del.exterminate(player, plugin.trackExterminate.get(player.getName())); } // temporary command to convert old gravity well to new style if (args[0].equalsIgnoreCase("gravity")) { if (player == null) { sender.sendMessage(plugin.pluginName + "Must be a player"); return false; } // get the players TARDIS id HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); try { TARDISDatabase service = TARDISDatabase.getInstance(); Connection connection = service.getConnection(); Statement statement = connection.createStatement(); String query = "SELECT * FROM gravity WHERE tardis_id = " + id; ResultSet rsg = statement.executeQuery(query); if (rsg.isBeforeFirst()) { String up = "Location{world=" + rsg.getString("world") + ",x=" + rsg.getFloat("upx") + ",y=10.0,z=" + rsg.getFloat("upz") + ",pitch=0.0,yaw=0.0}"; Double[] values = new Double[3]; values[0] = 1D; values[1] = 11D; values[2] = 0.5D; plugin.gravityUpList.put(up, values); String down = "Location{world=" + rsg.getString("world") + ",x=" + rsg.getFloat("downx") + ",y=10.0,z=" + rsg.getFloat("downz") + ",pitch=0.0,yaw=0.0}"; plugin.gravityDownList.add(down); HashMap<String, Object> setu = new HashMap<String, Object>(); setu.put("tardis_id", id); setu.put("location", up); setu.put("direction", 1); setu.put("distance", 11); setu.put("velocity", 0.5); HashMap<String, Object> setd = new HashMap<String, Object>(); setd.put("tardis_id", id); setd.put("location", down); setd.put("direction", 0); setd.put("distance", 0); setd.put("velocity", 0); QueryFactory qf = new QueryFactory(plugin); qf.doInsert("gravity_well", setu); qf.doInsert("gravity_well", setd); player.sendMessage(plugin.pluginName + "Gravity well converted successfully."); return true; } } catch (SQLException e) { plugin.debug("Gravity conversion error: " + e.getMessage()); } } if (args[0].equalsIgnoreCase("version")) { FileConfiguration pluginYml = YamlConfiguration.loadConfiguration(plugin.pm.getPlugin("TARDIS").getResource("plugin.yml")); String version = pluginYml.getString("version"); String cb = Bukkit.getVersion(); sender.sendMessage(plugin.pluginName + "You are running TARDIS version: " + ChatColor.AQUA + version + ChatColor.RESET + " with CraftBukkit " + cb); // also check if there is an update if (plugin.getConfig().getBoolean("check_for_updates")) { TARDISUpdateChecker update = new TARDISUpdateChecker(plugin); update.checkVersion(player); } return true; } if (player == null) { sender.sendMessage(plugin.pluginName + ChatColor.RED + " This command can only be run by a player"); return false; } else { if (args[0].equalsIgnoreCase("lamps")) { TARDISLampScanner tls = new TARDISLampScanner(plugin); return tls.addLampBlocks(player); } if (args[0].equalsIgnoreCase("chameleon")) { if (!plugin.getConfig().getBoolean("chameleon")) { sender.sendMessage(plugin.pluginName + "This server does not allow the use of the chameleon circuit!"); return false; } if (player.hasPermission("tardis.timetravel")) { if (args.length < 2 || (!args[1].equalsIgnoreCase("on") && !args[1].equalsIgnoreCase("off") && !args[1].equalsIgnoreCase("short") && !args[1].equalsIgnoreCase("reset"))) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } // get the players TARDIS id HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); String chamStr = rs.getChameleon(); if (chamStr.isEmpty()) { sender.sendMessage(plugin.pluginName + "Could not find the Chameleon Circuit!"); return false; } else { QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); if (args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("off")) { int x, y, z; String[] chamData = chamStr.split(":"); World w = plugin.getServer().getWorld(chamData[0]); TARDISConstants.COMPASS d = rs.getDirection(); x = plugin.utils.parseNum(chamData[1]); y = plugin.utils.parseNum(chamData[2]); z = plugin.utils.parseNum(chamData[3]); Block chamBlock = w.getBlockAt(x, y, z); Material chamType = chamBlock.getType(); if (chamType == Material.WALL_SIGN || chamType == Material.SIGN_POST) { Sign cs = (Sign) chamBlock.getState(); if (args[1].equalsIgnoreCase("on")) { set.put("chamele_on", 1); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was turned ON!"); cs.setLine(3, ChatColor.GREEN + "ON"); } if (args[1].equalsIgnoreCase("off")) { set.put("chamele_on", 0); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was turned OFF."); cs.setLine(3, ChatColor.RED + "OFF"); } cs.update(); } } int dwid = plugin.getConfig().getInt("wall_id"); int dwd = plugin.getConfig().getInt("wall_data"); if (args[1].equalsIgnoreCase("short")) { // get the block the player is targeting Block target_block = player.getTargetBlock(transparent, 50).getLocation().getBlock(); TARDISChameleonCircuit tcc = new TARDISChameleonCircuit(plugin); int[] b_data = tcc.getChameleonBlock(target_block, player, true); int c_id = b_data[0], c_data = b_data[1]; set.put("chameleon_id", c_id); set.put("chameleon_data", c_data); qf.doUpdate("tardis", set, tid); boolean bluewool = (c_id == dwid && c_data == (byte) dwd); if (!bluewool) { sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was shorted out to: " + target_block.getType().toString() + "."); } } if (args[1].equalsIgnoreCase("reset")) { // set.put("chameleon_id", 35); // set.put("chameleon_data", 11); set.put("chameleon_id", dwid); set.put("chameleon_data", dwd); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The Chameleon Circuit was repaired."); } } return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("rescue")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "Too few command arguments!"); return true; } if (player.hasPermission("tardis.timetravel.player")) { final String saved = args[1]; Player destPlayer = plugin.getServer().getPlayer(saved); if (destPlayer == null) { player.sendMessage(plugin.pluginName + "That player is not online!"); return true; } String playerNameStr = player.getName(); destPlayer.sendMessage(plugin.pluginName + playerNameStr + "wants to rescue you! Type: " + ChatColor.AQUA + "tardis rescue accept" + ChatColor.RESET + " in chat within 60 seconds to accept the rescue."); plugin.trackChat.put(saved, playerNameStr); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { if (plugin.trackChat.containsKey(saved)) { plugin.trackChat.remove(saved); sender.sendMessage(plugin.pluginName + saved + " didn't respond with 60 seconds, aborting rescue!"); } } }, 1200L); } else { player.sendMessage(plugin.pluginName + "You do not have permission to time travel to a player!"); return true; } } if (args[0].equalsIgnoreCase("room")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String room = args[1].toUpperCase(Locale.ENGLISH); StringBuilder buf = new StringBuilder(); for (String rl : roomArgs) { buf.append(rl).append(", "); } String roomlist = buf.toString().substring(0, buf.length() - 2); if (room.equals("HELP")) { player.sendMessage(plugin.pluginName + "There are currently " + roomArgs.size() + " room types! They are: " + roomlist + "."); player.sendMessage("View a TARDIS room gallery at http://eccentricdevotion.github.com/TARDIS/room-gallery.html"); return true; } if (!roomArgs.contains(room)) { player.sendMessage(plugin.pluginName + "That is not a valid room type! Try one of: " + roomlist + "."); return true; } String perm = "tardis.room." + args[1].toLowerCase(Locale.ENGLISH); if (!player.hasPermission(perm) && !player.hasPermission("tardis.room")) { String grammar = (TARDISConstants.vowels.contains(room.substring(0, 1))) ? "an" : "a"; sender.sendMessage(plugin.pluginName + "You do not have permission to grow " + grammar + " " + room); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { player.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return true; } String chunk = rs.getChunk(); String[] data = chunk.split(":"); World room_world = plugin.getServer().getWorld(data[0]); ChunkGenerator gen = room_world.getGenerator(); WorldType wt = room_world.getWorldType(); boolean special = (data[0].contains("TARDIS_TimeVortex") && (wt.equals(WorldType.FLAT) || gen instanceof TARDISChunkGenerator)); if (!data[0].contains("TARDIS_WORLD_") && !special) { player.sendMessage(plugin.pluginName + "You cannot grow rooms unless your TARDIS was created in its own world!"); return true; } int id = rs.getTardis_id(); int level = rs.getArtron_level(); // check they are in the tardis HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); wheret.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { player.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return true; } // check they have enough artron energy if (level < plugin.getRoomsConfig().getInt("rooms." + room + ".cost")) { player.sendMessage(plugin.pluginName + "The TARDIS does not have enough Artron Energy to grow this room!"); return true; } if (plugin.getConfig().getBoolean("rooms_require_blocks")) { HashMap<String, Integer> blockIDCount = new HashMap<String, Integer>(); boolean hasRequired = true; HashMap<String, Integer> roomBlocks = plugin.roomBlockCounts.get(room); String wall = "ORANGE_WOOL"; String floor = "LIGHT_GREY_WOOL"; HashMap<String, Object> wherepp = new HashMap<String, Object>(); boolean hasPrefs = false; wherepp.put("player", player.getName()); ResultSetPlayerPrefs rsp = new ResultSetPlayerPrefs(plugin, wherepp); if (rsp.resultSet()) { hasPrefs = true; wall = rsp.getWall(); floor = rsp.getFloor(); } for (Map.Entry<String, Integer> entry : roomBlocks.entrySet()) { String[] block_data = entry.getKey().split(":"); int bid = plugin.utils.parseNum(block_data[0]); String mat; String bdata; if (hasPrefs && block_data.length == 2 && (block_data[1].equals("1") || block_data[1].equals("8"))) { mat = (block_data[1].equals("1")) ? wall : floor; TARDISWalls tw = new TARDISWalls(); Integer[] iddata = tw.blocks.get(mat); bdata = String.format("%d", iddata[0]); } else { mat = Material.getMaterial(bid).toString(); bdata = String.format("%d", bid); } int tmp = Math.round((entry.getValue() / 100.0F) * plugin.getConfig().getInt("rooms_condenser_percent")); int required = (tmp > 0) ? tmp : 1; blockIDCount.put(bdata, required); HashMap<String, Object> wherec = new HashMap<String, Object>(); wherec.put("tardis_id", id); wherec.put("block_data", bdata); ResultSetCondenser rsc = new ResultSetCondenser(plugin, wherec, false); if (rsc.resultSet()) { if (rsc.getBlock_count() < required) { hasRequired = false; int diff = required - rsc.getBlock_count(); player.sendMessage(plugin.pluginName + "You need to condense " + diff + " more " + mat + "!"); } } else { hasRequired = false; player.sendMessage(plugin.pluginName + "You need to condense a minimum of " + required + " " + mat); } } if (hasRequired == false) { player.sendMessage("-----------------------------"); return true; } TARDISCondenserData c_data = new TARDISCondenserData(); c_data.setBlockIDCount(blockIDCount); c_data.setTardis_id(id); plugin.roomCondenserData.put(player.getName(), c_data); } String message; // if it is a gravity well if (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) { message = "Place the GRAVITY WELL seed block (" + plugin.getRoomsConfig().getString("rooms." + room + ".seed") + ") into the centre of the floor in an empty room, then hit it with the TARDIS key to start growing your room!"; } else { message = "Place the " + room + " seed block (" + plugin.getRoomsConfig().getString("rooms." + room + ".seed") + ") where the door should be, then hit it with the TARDIS key to start growing your room!"; } plugin.trackRoomSeed.put(player.getName(), room); player.sendMessage(plugin.pluginName + message); return true; } if (args[0].equalsIgnoreCase("jettison")) { if (player.hasPermission("tardis.room")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String room = args[1].toUpperCase(Locale.ENGLISH); if (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) { player.sendMessage(plugin.pluginName + "You cannot jettison gravity wells! To remove the gravity blocks use the " + ChatColor.AQUA + "/tardisgravity remove" + ChatColor.RESET + " command."); return true; } if (!roomArgs.contains(room)) { StringBuilder buf = new StringBuilder(args[1]); for (String rl : roomArgs) { buf.append(rl).append(", "); } String roomlist = buf.toString().substring(0, buf.length() - 2); player.sendMessage(plugin.pluginName + "That is not a valid room type! Try one of: " + roomlist); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { player.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return true; } int id = rs.getTardis_id(); // check they are in the tardis HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); wheret.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { player.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return true; } plugin.trackJettison.put(player.getName(), room); String seed = plugin.getArtronConfig().getString("jettison_seed"); player.sendMessage(plugin.pluginName + "Stand in the doorway of the room you want to jettison and place a " + seed + " block directly in front of the door. Hit the " + seed + " with the TARDIS key to jettison the room!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("abort")) { if (args.length < 2) { player.sendMessage(plugin.pluginName + "You must specify the task ID number!"); return false; } try { int task = Integer.parseInt(args[1]); plugin.getServer().getScheduler().cancelTask(task); player.sendMessage(plugin.pluginName + "Task aborted!"); return true; } catch (NumberFormatException nfe) { player.sendMessage(plugin.pluginName + "Task ID is not a number!"); return false; } } if (args[0].equalsIgnoreCase("occupy")) { if (player.hasPermission("tardis.timetravel")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + " You must be the Timelord of the TARDIS to use this command!"); return false; } int id = rs.getTardis_id(); HashMap<String, Object> wheret = new HashMap<String, Object>(); //wheret.put("tardis_id", id); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); String occupied; QueryFactory qf = new QueryFactory(plugin); if (rst.resultSet()) { HashMap<String, Object> whered = new HashMap<String, Object>(); //whered.put("tardis_id", id); whered.put("player", player.getName()); qf.doDelete("travellers", whered); occupied = ChatColor.RED + "UNOCCUPIED"; } else { HashMap<String, Object> wherei = new HashMap<String, Object>(); wherei.put("tardis_id", id); wherei.put("player", player.getName()); qf.doInsert("travellers", wherei); occupied = ChatColor.GREEN + "OCCUPIED"; } sender.sendMessage(plugin.pluginName + " TARDIS occupation was set to: " + occupied); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("comehere")) { if (plugin.getConfig().getString("difficulty").equalsIgnoreCase("easy")) { if (player.hasPermission("tardis.timetravel")) { final Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && eyeLocation.getWorld().getName().equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to bring the TARDIS to this world!"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, eyeLocation, true)) { return true; } if (player.hasPermission("tardis.exile") && plugin.getConfig().getBoolean("exile")) { String areaPerm = plugin.ta.getExileArea(player); if (plugin.ta.areaCheckInExile(areaPerm, eyeLocation)) { sender.sendMessage(plugin.pluginName + "You exile status does not allow you to bring the TARDIS to this location!"); return true; } } if (!plugin.ta.areaCheckInExisting(eyeLocation)) { sender.sendMessage(plugin.pluginName + "You cannot use /tardis comehere to bring the Police Box to a TARDIS area! Please use " + ChatColor.AQUA + "/tardistravel area [area name]"); return true; } Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check the world is not excluded String world = eyeLocation.getWorld().getName(); if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot bring the TARDIS Police Box to this world"); return true; } // check they are a timelord HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); final ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of the TARDIS to use this command!"); return true; } final int id = rs.getTardis_id(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot bring the Police Box here because you are inside a TARDIS!"); return true; } if (plugin.tardisMaterialising.contains(id) || plugin.tardisDematerialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } final TARDISConstants.COMPASS d = rs.getDirection(); TARDISTimeTravel tt = new TARDISTimeTravel(plugin); int count; String sub = "false"; Block b = eyeLocation.getBlock(); if (b.getRelative(BlockFace.UP).getTypeId() == 8 || b.getRelative(BlockFace.UP).getTypeId() == 9) { count = (tt.isSafeSubmarine(eyeLocation, d)) ? 0 : 1; if (count == 0) { plugin.trackSubmarine.add(id); sub = "true"; } } else { if (plugin.trackSubmarine.contains(Integer.valueOf(id))) { plugin.trackSubmarine.remove(Integer.valueOf(id)); } int[] start_loc = tt.getStartLocation(eyeLocation, d); // safeLocation(int startx, int starty, int startz, int resetx, int resetz, World w, TARDISConstants.COMPASS d) count = tt.safeLocation(start_loc[0], eyeLocation.getBlockY(), start_loc[2], start_loc[1], start_loc[3], eyeLocation.getWorld(), d); } if (count > 0) { sender.sendMessage(plugin.pluginName + "That location would grief existing blocks! Try somewhere else!"); return true; } int level = rs.getArtron_level(); int ch = plugin.getArtronConfig().getInt("comehere"); if (level < ch) { player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to make this trip!"); return true; } final Player p = player; String current_str = rs.getCurrent(); boolean chamtmp = false; if (plugin.getConfig().getBoolean("chameleon")) { chamtmp = rs.isChamele_on(); } final boolean cham = chamtmp; String[] saveData = current_str.split(":"); World w = plugin.getServer().getWorld(saveData[0]); if (w != null) { int x, y, z; x = plugin.utils.parseNum(saveData[1]); y = plugin.utils.parseNum(saveData[2]); z = plugin.utils.parseNum(saveData[3]); final Location oldSave = w.getBlockAt(x, y, z).getLocation(); String comehere = eyeLocation.getWorld().getName() + ":" + eyeLocation.getBlockX() + ":" + eyeLocation.getBlockY() + ":" + eyeLocation.getBlockZ() + ":" + d.toString() + ":" + sub; final boolean hidden = rs.isHidden(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("save", comehere); set.put("current", comehere); if (hidden) { set.put("hidden", 0); } qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The TARDIS is coming..."); final boolean mat = plugin.getConfig().getBoolean("materialise"); long delay = (mat) ? 1L : 180L; Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { if (!hidden) { plugin.tardisDematerialising.add(id); plugin.destroyPB.destroyPoliceBox(oldSave, d, id, false, mat, cham, p); } } }, delay); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.buildPB.buildPoliceBox(id, eyeLocation, d, cham, p, false, false); } }, delay * 2); // remove energy from TARDIS HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); qf.alterEnergyLevel("tardis", -ch, wheret, player); plugin.tardisHasDestination.remove(id); if (plugin.trackRescue.containsKey(Integer.valueOf(id))) { plugin.trackRescue.remove(Integer.valueOf(id)); } return true; } else { sender.sendMessage(plugin.pluginName + "Could not get the previous location of the TARDIS!"); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } else { sender.sendMessage(plugin.pluginName + "You need to craft a Stattenheim Remote Control! Type " + ChatColor.AQUA + "/tardisrecipe remote" + ChatColor.RESET + " to see how to make it."); return true; } } if (args[0].equalsIgnoreCase("check_loc")) { final Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check they are a timelord HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of a TARDIS to use this command!"); return true; } final TARDISConstants.COMPASS d = rs.getDirection(); TARDISTimeTravel tt = new TARDISTimeTravel(plugin); tt.testSafeLocation(eyeLocation, d); return true; } if (args[0].equalsIgnoreCase("inside")) { // check they are a timelord HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of a TARDIS to use this command!"); return true; } int id = rs.getTardis_id(); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, true); if (rst.resultSet()) { List<String> data = rst.getData(); sender.sendMessage(plugin.pluginName + "The players inside your TARDIS are:"); for (String s : data) { sender.sendMessage(s); } } else { sender.sendMessage(plugin.pluginName + "Nobody is inside your TARDIS."); } return true; } if (args[0].equalsIgnoreCase("home")) { if (player.hasPermission("tardis.timetravel")) { Location eyeLocation = player.getTargetBlock(transparent, 50).getLocation(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && eyeLocation.getWorld().getName().equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to set the TARDIS home in this world!"); return true; } if (!plugin.ta.areaCheckInExisting(eyeLocation)) { sender.sendMessage(plugin.pluginName + "You cannot use /tardis home in a TARDIS area! Please use " + ChatColor.AQUA + "/tardistravel area [area name]"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, eyeLocation, true)) { return true; } Material m = player.getTargetBlock(transparent, 50).getType(); if (m != Material.SNOW) { int yplusone = eyeLocation.getBlockY(); eyeLocation.setY(yplusone + 1); } // check the world is not excluded String world = eyeLocation.getWorld().getName(); if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot set the TARDIS home location to this world"); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You must be the Timelord of the TARDIS to use this command!"); return false; } int id = rs.getTardis_id(); String direction = rs.getDirection().toString(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot set the home location here because you are inside a TARDIS!"); return true; } String sethome = eyeLocation.getWorld().getName() + ":" + eyeLocation.getBlockX() + ":" + eyeLocation.getBlockY() + ":" + eyeLocation.getBlockZ() + ":" + direction; QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("home", sethome); qf.doUpdate("tardis", set, tid); sender.sendMessage(plugin.pluginName + "The new TARDIS home was set!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("update")) { if (player.hasPermission("tardis.update")) { String[] validBlockNames = {"door", "button", "world-repeater", "x-repeater", "z-repeater", "y-repeater", "chameleon", "save-sign", "artron", "handbrake", "condenser", "scanner", "backdoor", "keyboard", "creeper", "eps", "back", "terminal", "ars", "temporal", "light", "farm", "stable", "rail", "info"}; if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String tardis_block = args[1].toLowerCase(Locale.ENGLISH); if (!Arrays.asList(validBlockNames).contains(tardis_block)) { player.sendMessage(plugin.pluginName + "That is not a valid TARDIS block name! Try one of : door|button|world-repeater|x-repeater|z-repeater|y-repeater|chameleon|save-sign|artron|handbrake|condenser|scanner|backdoor|keyboard|creeper|eps|back|terminal|ars|temporal|light|farm|stable|rail|info"); return false; } if (tardis_block.equals("backdoor") && !player.hasPermission("tardis.backdoor")) { sender.sendMessage(plugin.pluginName + "You do not have permission to create a back door!"); return true; } if (tardis_block.equals("temporal") && !player.hasPermission("tardis.temporal")) { sender.sendMessage(plugin.pluginName + "You do not have permission to create a Temporal Locator!"); return true; } if ((tardis_block.equals("farm") || tardis_block.equals("stable")) && !player.hasPermission("tardis.farm")) { sender.sendMessage(plugin.pluginName + "You do not have permission to update the " + tardis_block + "!"); return true; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); <MASK>String rail = rs.getRail();</MASK> if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return false; } if (!tardis_block.equals("backdoor")) { HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return false; } } if (tardis_block.equals("rail") && rail.isEmpty()) { player.sendMessage(plugin.pluginName + "You need to grow a rail room before you can update its position."); return true; } plugin.trackPlayers.put(player.getName(), tardis_block); player.sendMessage(plugin.pluginName + "Click the TARDIS " + tardis_block + " to update its position."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("secondary")) { if (player.hasPermission("tardis.update")) { String[] validBlockNames = {"button", "world-repeater", "x-repeater", "z-repeater", "y-repeater", "artron", "handbrake", "door", "back"}; if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } String tardis_block = args[1].toLowerCase(Locale.ENGLISH); if (!Arrays.asList(validBlockNames).contains(tardis_block)) { player.sendMessage(plugin.pluginName + "That is not a valid TARDIS block name! Try one of : button|world-repeater|x-repeater|z-repeater|y-repeater|artron|handbrake|door|back"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not a Timelord. You need to create a TARDIS first before using this command!"); return false; } HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheret, false); if (!rst.resultSet()) { sender.sendMessage(plugin.pluginName + "You are not inside your TARDIS. You need to be to run this command!"); return false; } plugin.trackSecondary.put(player.getName(), tardis_block); player.sendMessage(plugin.pluginName + "Click the TARDIS " + tardis_block + " to update its position."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("rebuild") || args[0].equalsIgnoreCase("hide")) { if (player.hasPermission("tardis.rebuild")) { String save; World w; int x, y, z, id; TARDISConstants.COMPASS d; boolean cham = false; HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } id = rs.getTardis_id(); HashMap<String, Object> wherein = new HashMap<String, Object>(); wherein.put("player", player.getName()); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherein, false); if (rst.resultSet() && args[0].equalsIgnoreCase("rebuild") && plugin.tardisHasDestination.containsKey(id)) { sender.sendMessage(plugin.pluginName + "You cannot rebuild the TARDIS right now! Try travelling first."); return true; } int level = rs.getArtron_level(); save = rs.getCurrent(); if (plugin.tardisMaterialising.contains(id) || plugin.tardisDematerialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } if (plugin.getConfig().getBoolean("chameleon")) { cham = rs.isChamele_on(); } d = rs.getDirection(); String[] save_data = save.split(":"); w = plugin.getServer().getWorld(save_data[0]); x = plugin.utils.parseNum(save_data[1]); y = plugin.utils.parseNum(save_data[2]); z = plugin.utils.parseNum(save_data[3]); Location l = new Location(w, x, y, z); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); QueryFactory qf = new QueryFactory(plugin); if (args[0].equalsIgnoreCase("rebuild")) { int rebuild = plugin.getArtronConfig().getInt("random"); if (level < rebuild) { player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to rebuild!"); return false; } plugin.buildPB.buildPoliceBox(id, l, d, cham, player, true, false); sender.sendMessage(plugin.pluginName + "The TARDIS Police Box was rebuilt!"); qf.alterEnergyLevel("tardis", -rebuild, wheret, player); // set hidden to false if (rs.isHidden()) { HashMap<String, Object> whereh = new HashMap<String, Object>(); whereh.put("tardis_id", id); HashMap<String, Object> seth = new HashMap<String, Object>(); seth.put("hidden", 0); qf.doUpdate("tardis", seth, whereh); } return true; } if (args[0].equalsIgnoreCase("hide")) { int hide = plugin.getArtronConfig().getInt("hide"); if (level < hide) { player.sendMessage(plugin.pluginName + ChatColor.RED + "The TARDIS does not have enough Artron Energy to hide!"); return false; } plugin.destroyPB.destroyPoliceBox(l, d, id, true, false, false, null); sender.sendMessage(plugin.pluginName + "The TARDIS Police Box was hidden! Use " + ChatColor.GREEN + "/tardis rebuild" + ChatColor.RESET + " to show it again."); qf.alterEnergyLevel("tardis", -hide, wheret, player); // set hidden to true HashMap<String, Object> whereh = new HashMap<String, Object>(); whereh.put("tardis_id", id); HashMap<String, Object> seth = new HashMap<String, Object>(); seth.put("hidden", 1); qf.doUpdate("tardis", seth, whereh); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("list")) { if (player.hasPermission("tardis.list")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2 || (!args[1].equalsIgnoreCase("saves") && !args[1].equalsIgnoreCase("companions") && !args[1].equalsIgnoreCase("areas") && !args[1].equalsIgnoreCase("rechargers"))) { sender.sendMessage(plugin.pluginName + "You need to specify which TARDIS list you want to view! [saves|companions|areas|rechargers]"); return false; } TARDISLister.list(player, args[1]); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("find")) { if (plugin.getConfig().getString("difficulty").equalsIgnoreCase("easy")) { if (player.hasPermission("tardis.find")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } String loc = rs.getCurrent(); String[] findData = loc.split(":"); sender.sendMessage(plugin.pluginName + "TARDIS was left at " + findData[0] + " at x: " + findData[1] + " y: " + findData[2] + " z: " + findData[3]); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } else { sender.sendMessage(plugin.pluginName + "You need to craft a TARDIS Locator! Type " + ChatColor.AQUA + "/tardisrecipe locator" + ChatColor.RESET + " to see how to make it."); return true; } } if (args[0].equalsIgnoreCase("add")) { if (player.hasPermission("tardis.add")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); String comps; int id; if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } else { id = rs.getTardis_id(); comps = rs.getCompanions(); } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid username"); return false; } else { QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); if (comps != null && !comps.isEmpty()) { // add to the list String newList = comps + ":" + args[1].toLowerCase(Locale.ENGLISH); set.put("companions", newList); } else { // make a list set.put("companions", args[1].toLowerCase(Locale.ENGLISH)); } qf.doUpdate("tardis", set, tid); player.sendMessage(plugin.pluginName + "You added " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); // are we doing an achievement? if (plugin.getAchivementConfig().getBoolean("friends.enabled")) { TARDISAchievementFactory taf = new TARDISAchievementFactory(plugin, player, "friends", 1); taf.doAchievement(1); } return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("remove")) { if (player.hasPermission("tardis.add")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); String comps; int id; if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } else { id = rs.getTardis_id(); comps = rs.getCompanions(); if (comps == null || comps.isEmpty()) { sender.sendMessage(plugin.pluginName + "You have not added any TARDIS companions yet!"); return true; } } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid username"); return false; } else { String[] split = comps.split(":"); StringBuilder buf = new StringBuilder(); String newList = ""; if (split.length > 1) { // recompile string without the specified player for (String c : split) { if (!c.equals(args[1].toLowerCase(Locale.ENGLISH))) { // add to new string buf.append(c).append(":"); } } // remove trailing colon if (buf.length() > 0) { newList = buf.toString().substring(0, buf.length() - 1); } } QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("companions", newList); qf.doUpdate("tardis", set, tid); player.sendMessage(plugin.pluginName + "You removed " + ChatColor.GREEN + args[1] + ChatColor.RESET + " as a TARDIS companion."); return true; } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("save")) { if (player.hasPermission("tardis.save")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "That doesn't appear to be a valid save name (it may be too long or contains spaces)."); return false; } else { int id = rs.getTardis_id(); // get current destination String cur = rs.getCurrent(); String[] curDest = cur.split(":"); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> set = new HashMap<String, Object>(); set.put("tardis_id", id); set.put("dest_name", args[1]); set.put("world", curDest[0]); set.put("x", plugin.utils.parseNum(curDest[1])); set.put("y", plugin.utils.parseNum(curDest[2])); set.put("z", plugin.utils.parseNum(curDest[3])); set.put("direction", rs.getDirection().toString()); if (qf.doInsert("destinations", set) < 0) { return false; } else { sender.sendMessage(plugin.pluginName + "The location '" + args[1] + "' was saved successfully."); return true; } } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("removesave")) { if (player.hasPermission("tardis.save")) { if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); HashMap<String, Object> whered = new HashMap<String, Object>(); whered.put("dest_name", args[1]); whered.put("tardis_id", id); ResultSetDestinations rsd = new ResultSetDestinations(plugin, whered, false); if (!rsd.resultSet()) { sender.sendMessage(plugin.pluginName + "Could not find a saved destination with that name!"); return false; } int destID = rsd.getDest_id(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> did = new HashMap<String, Object>(); did.put("dest_id", destID); qf.doDelete("destinations", did); sender.sendMessage(plugin.pluginName + "The destination " + args[1] + " was deleted!"); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("setdest")) { if (player.hasPermission("tardis.save")) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } if (args.length < 2) { sender.sendMessage(plugin.pluginName + "Too few command arguments!"); return false; } if (!args[1].matches("[A-Za-z0-9_]{2,16}")) { sender.sendMessage(plugin.pluginName + "The destination name must be between 2 and 16 characters and have no spaces!"); return false; } else if (args[1].equalsIgnoreCase("hide") || args[1].equalsIgnoreCase("rebuild") || args[1].equalsIgnoreCase("home")) { sender.sendMessage(plugin.pluginName + "That is a reserved destination name!"); return false; } else { int id = rs.getTardis_id(); // check they are not in the tardis HashMap<String, Object> wherettrav = new HashMap<String, Object>(); wherettrav.put("player", player.getName()); wherettrav.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, wherettrav, false); if (rst.resultSet()) { player.sendMessage(plugin.pluginName + "You cannot bring the Police Box here because you are inside a TARDIS!"); return true; } // get location player is looking at Block b = player.getTargetBlock(transparent, 50); Location l = b.getLocation(); if (!plugin.ta.areaCheckInExisting(l)) { sender.sendMessage(plugin.pluginName + "You cannot use /tardis setdest in a TARDIS area! Please use " + ChatColor.AQUA + "/tardistravel area [area name]"); return true; } String world = l.getWorld().getName(); if (!plugin.getConfig().getBoolean("include_default_world") && plugin.getConfig().getBoolean("default_world") && world.equals(plugin.getConfig().getString("default_world_name"))) { sender.sendMessage(plugin.pluginName + "The server admin will not allow you to set the TARDIS destination to this world!"); return true; } // check the world is not excluded if (!plugin.getConfig().getBoolean("worlds." + world)) { sender.sendMessage(plugin.pluginName + "You cannot bring the TARDIS Police Box to this world"); return true; } respect = new TARDISPluginRespect(plugin); if (!respect.getRespect(player, l, true)) { return true; } if (player.hasPermission("tardis.exile") && plugin.getConfig().getBoolean("exile")) { String areaPerm = plugin.ta.getExileArea(player); if (plugin.ta.areaCheckInExile(areaPerm, l)) { sender.sendMessage(plugin.pluginName + "You exile status does not allow you to save the TARDIS to this location!"); return false; } } String dw = l.getWorld().getName(); int dx = l.getBlockX(); int dy = l.getBlockY() + 1; int dz = l.getBlockZ(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> set = new HashMap<String, Object>(); set.put("tardis_id", id); set.put("dest_name", args[1]); set.put("world", dw); set.put("x", dx); set.put("y", dy); set.put("z", dz); if (qf.doInsert("destinations", set) < 0) { return false; } else { sender.sendMessage(plugin.pluginName + "The destination '" + args[1] + "' was saved successfully."); return true; } } } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("direction")) { if (player.hasPermission("tardis.timetravel")) { if (args.length < 2 || (!args[1].equalsIgnoreCase("north") && !args[1].equalsIgnoreCase("west") && !args[1].equalsIgnoreCase("south") && !args[1].equalsIgnoreCase("east"))) { sender.sendMessage(plugin.pluginName + "You need to specify the compass direction e.g. north, west, south or east!"); return false; } HashMap<String, Object> where = new HashMap<String, Object>(); where.put("owner", player.getName()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_TARDIS); return false; } int id = rs.getTardis_id(); int level = rs.getArtron_level(); int amount = plugin.getArtronConfig().getInt("random"); if (level < amount) { sender.sendMessage(plugin.pluginName + "The TARDIS does not have enough Artron Energy to change the Police Box direction!"); return true; } String save = rs.getCurrent(); String[] save_data = save.split(":"); if (plugin.tardisMaterialising.contains(id) || plugin.tardisDematerialising.contains(id)) { sender.sendMessage(plugin.pluginName + "You cannot do that while the TARDIS is materialising!"); return true; } boolean cham = false; if (plugin.getConfig().getBoolean("chameleon")) { cham = rs.isChamele_on(); } String dir = args[1].toUpperCase(Locale.ENGLISH); TARDISConstants.COMPASS old_d = rs.getDirection(); QueryFactory qf = new QueryFactory(plugin); HashMap<String, Object> tid = new HashMap<String, Object>(); HashMap<String, Object> set = new HashMap<String, Object>(); tid.put("tardis_id", id); set.put("direction", dir); qf.doUpdate("tardis", set, tid); HashMap<String, Object> did = new HashMap<String, Object>(); HashMap<String, Object> setd = new HashMap<String, Object>(); did.put("door_type", 0); did.put("tardis_id", id); setd.put("door_direction", dir); qf.doUpdate("doors", setd, did); World w = plugin.getServer().getWorld(save_data[0]); int x = plugin.utils.parseNum(save_data[1]); int y = plugin.utils.parseNum(save_data[2]); int z = plugin.utils.parseNum(save_data[3]); Location l = new Location(w, x, y, z); TARDISConstants.COMPASS d = TARDISConstants.COMPASS.valueOf(dir); // destroy platform if (!rs.isHidden()) { plugin.destroyPB.destroyPlatform(rs.getPlatform(), id); plugin.destroyPB.destroySign(l, old_d); } plugin.buildPB.buildPoliceBox(id, l, d, cham, player, true, false); HashMap<String, Object> wherea = new HashMap<String, Object>(); wherea.put("tardis_id", id); qf.alterEnergyLevel("tardis", -amount, wherea, player); sender.sendMessage(plugin.pluginName + "You used " + amount + " Artron Energy changing the Police Box direction."); return true; } else { sender.sendMessage(plugin.pluginName + TARDISConstants.NO_PERMS_MESSAGE); return false; } } if (args[0].equalsIgnoreCase("namekey")) { if (plugin.bukkitversion.compareTo(plugin.preIMversion) < 0 || (plugin.bukkitversion.compareTo(plugin.preIMversion) == 0 && plugin.SUBversion.compareTo(plugin.preSUBversion) < 0)) { sender.sendMessage(plugin.pluginName + "You cannot rename the TARDIS key with this version of Bukkit!"); return true; } // determine key item String key; HashMap<String, Object> where = new HashMap<String, Object>(); where.put("player", player.getName()); ResultSetPlayerPrefs rsp = new ResultSetPlayerPrefs(plugin, where); if (rsp.resultSet()) { key = (!rsp.getKey().isEmpty()) ? rsp.getKey() : plugin.getConfig().getString("key"); } else { key = plugin.getConfig().getString("key"); } Material m = Material.getMaterial(key); if (m.equals(Material.AIR)) { sender.sendMessage(plugin.pluginName + "You cannot rename AIR!"); return true; } ItemStack is = player.getItemInHand(); if (!is.getType().equals(m)) { sender.sendMessage(plugin.pluginName + "You can only rename the TARDIS key!"); return true; } int count = args.length; if (count < 2) { return false; } StringBuilder buf = new StringBuilder(args[1]); for (int i = 2; i < count; i++) { buf.append(" ").append(args[i]); } String tmp = buf.toString(); if (!tmp.isEmpty()) { TARDISItemRenamer ir = new TARDISItemRenamer(is); ir.setName(tmp, false); sender.sendMessage(plugin.pluginName + "TARDIS key renamed to '" + tmp + "'"); return true; } else { return false; } } if (args[0].equalsIgnoreCase("help")) { if (args.length == 1) { sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); return true; } if (args.length == 2) { List<String> cmds = new ArrayList<String>(); for (TARDISConstants.CMDS c : TARDISConstants.CMDS.values()) { cmds.add(c.toString()); } // check that the second arument is valid if (!cmds.contains(args[1].toUpperCase(Locale.ENGLISH))) { sender.sendMessage(plugin.pluginName + "That is not a valid help topic!"); return true; } switch (TARDISConstants.fromString(args[1])) { case CREATE: sender.sendMessage(TARDISConstants.COMMAND_CREATE.split("\n")); break; case DELETE: sender.sendMessage(TARDISConstants.COMMAND_DELETE.split("\n")); break; case TIMETRAVEL: sender.sendMessage(TARDISConstants.COMMAND_TIMETRAVEL.split("\n")); break; case LIST: sender.sendMessage(TARDISConstants.COMMAND_LIST.split("\n")); break; case FIND: sender.sendMessage(TARDISConstants.COMMAND_FIND.split("\n")); break; case SAVE: sender.sendMessage(TARDISConstants.COMMAND_SAVE.split("\n")); break; case REMOVESAVE: sender.sendMessage(TARDISConstants.COMMAND_REMOVESAVE.split("\n")); break; case ADD: sender.sendMessage(TARDISConstants.COMMAND_ADD.split("\n")); break; case TRAVEL: sender.sendMessage(TARDISConstants.COMMAND_TRAVEL.split("\n")); break; case UPDATE: sender.sendMessage(TARDISConstants.COMMAND_UPDATE.split("\n")); break; case REBUILD: sender.sendMessage(TARDISConstants.COMMAND_REBUILD.split("\n")); break; case CHAMELEON: sender.sendMessage(TARDISConstants.COMMAND_CHAMELEON.split("\n")); break; case SFX: sender.sendMessage(TARDISConstants.COMMAND_SFX.split("\n")); break; case PLATFORM: sender.sendMessage(TARDISConstants.COMMAND_PLATFORM.split("\n")); break; case SETDEST: sender.sendMessage(TARDISConstants.COMMAND_SETDEST.split("\n")); break; case HOME: sender.sendMessage(TARDISConstants.COMMAND_HOME.split("\n")); break; case HIDE: sender.sendMessage(TARDISConstants.COMMAND_HIDE.split("\n")); break; case VERSION: sender.sendMessage(TARDISConstants.COMMAND_HIDE.split("\n")); break; case ADMIN: sender.sendMessage(TARDISConstants.COMMAND_ADMIN.split("\n")); break; case AREA: sender.sendMessage(TARDISConstants.COMMAND_AREA.split("\n")); break; case ROOM: sender.sendMessage(TARDISConstants.COMMAND_ROOM.split("\n")); break; case ARTRON: sender.sendMessage(TARDISConstants.COMMAND_ARTRON.split("\n")); break; case BIND: sender.sendMessage(TARDISConstants.COMMAND_BIND.split("\n")); break; default: sender.sendMessage(TARDISConstants.COMMANDS.split("\n")); } } return true; } } } // If the above has happened the function will break and return true. if this hasn't happened then value of false will be returned. return false; }"
Inversion-Mutation
megadiff
"public void deselectUser(String postId){ bodyHtml = ""; if(mThreadView != null){ this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { aq.find(R.id.thread_userpost_notice).gone(); mThreadView.loadUrl("javascript:loadpagehtml()"); } }); } if(TextUtils.isEmpty(postId) || postId.length() < 3){ mUserId = 0; mPostByUsername = null; setPage(savedPage); mLastPage = 0; mPostJump = ""; syncThread(); }else{ openThread(AwfulURL.parse(generatePostUrl(postId))); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "deselectUser"
"public void deselectUser(String postId){ bodyHtml = ""; <MASK>aq.find(R.id.thread_userpost_notice).gone();</MASK> if(mThreadView != null){ this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { mThreadView.loadUrl("javascript:loadpagehtml()"); } }); } if(TextUtils.isEmpty(postId) || postId.length() < 3){ mUserId = 0; mPostByUsername = null; setPage(savedPage); mLastPage = 0; mPostJump = ""; syncThread(); }else{ openThread(AwfulURL.parse(generatePostUrl(postId))); } }"
Inversion-Mutation
megadiff
"public void onPlayerJoin(PlayerJoinEvent event){ if (!plugin.isEnabled()) return; if (plugin.poller.isPanicing() && ! event.getPlayer().isOp()){ event.getPlayer().kickPlayer("Sorry mate, the server is in Memory Panic. Try again later."); event.setJoinMessage(ChatColor.RED+event.getPlayer().getName()+" joined, but is rejected due to the current Memory Panic."); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPlayerJoin"
"public void onPlayerJoin(PlayerJoinEvent event){ if (!plugin.isEnabled()) return; if (plugin.poller.isPanicing() && ! event.getPlayer().isOp()){ event.getPlayer().kickPlayer("Sorry mate, the server is in Memory Panic. Try again later."); } <MASK>event.setJoinMessage(ChatColor.RED+event.getPlayer().getName()+" joined, but is rejected due to the current Memory Panic.");</MASK> }"
Inversion-Mutation
megadiff
"@Override public void draw(){ glMatrixMode(GL_MODELVIEW); glPushMatrix(); { glTranslated(x, y, z); fb.put(rotMatrix); fb.flip(); glMultMatrix(fb); drawGeometry(); } glPopMatrix(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "draw"
"@Override public void draw(){ glPushMatrix(); { <MASK>glMatrixMode(GL_MODELVIEW);</MASK> glTranslated(x, y, z); fb.put(rotMatrix); fb.flip(); glMultMatrix(fb); drawGeometry(); } glPopMatrix(); }"
Inversion-Mutation
megadiff
"public int compare( Object o1, Object o2 ) { Object[] sortKeys1 = ( (GroupBoundaryInfo) o1 ).getSortKeys( ); Object[] sortKeys2 = ( (GroupBoundaryInfo) o2 ).getSortKeys( ); boolean[] sortDirection = ( (GroupBoundaryInfo) o1 ).getSortDirection( ); Comparator[] comparator = ( (GroupBoundaryInfo) o1 ).getCollarComparator( ); int result = 0; for ( int i = 0; i < sortKeys1.length; i++ ) { try { result = ScriptEvalUtil.compare( sortKeys1[i], sortKeys2[i], comparator[i] ); } catch ( DataException e ) { result = 0; } if ( result != 0 ) { if ( sortDirection[i] == false ) { result = result * -1; } break; } } return result; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "compare"
"public int compare( Object o1, Object o2 ) { Object[] sortKeys1 = ( (GroupBoundaryInfo) o1 ).getSortKeys( ); Object[] sortKeys2 = ( (GroupBoundaryInfo) o2 ).getSortKeys( ); boolean[] sortDirection = ( (GroupBoundaryInfo) o1 ).getSortDirection( ); Comparator[] comparator = ( (GroupBoundaryInfo) o1 ).getCollarComparator( ); int result = 0; for ( int i = 0; i < sortKeys1.length; i++ ) { try { result = ScriptEvalUtil.compare( sortKeys1[i], sortKeys2[i], comparator[i] ); } catch ( DataException e ) { result = 0; } if ( result != 0 ) { if ( sortDirection[i] == false ) { result = result * -1; <MASK>break;</MASK> } } } return result; }"
Inversion-Mutation
megadiff
"public GenericJDBCDataModel(Properties props) throws TasteException { super(AbstractJDBCComponent.lookupDataSource(props.getProperty(DATA_SOURCE_KEY)), props.getProperty(GET_PREFERENCE_SQL_KEY), props.getProperty(GET_PREFERENCE_TIME_SQL_KEY), props.getProperty(GET_USER_SQL_KEY), props.getProperty(GET_ALL_USERS_SQL_KEY), props.getProperty(GET_NUM_ITEMS_SQL_KEY), props.getProperty(GET_NUM_USERS_SQL_KEY), props.getProperty(SET_PREFERENCE_SQL_KEY), props.getProperty(REMOVE_PREFERENCE_SQL_KEY), props.getProperty(GET_USERS_SQL_KEY), props.getProperty(GET_ITEMS_SQL_KEY), props.getProperty(GET_PREFS_FOR_ITEM_SQL_KEY), props.getProperty(GET_NUM_PREFERENCE_FOR_ITEM_KEY), props.getProperty(GET_NUM_PREFERENCE_FOR_ITEMS_KEY), props.getProperty(GET_MAX_PREFERENCE_KEY), props.getProperty(GET_MIN_PREFERENCE_KEY)); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "GenericJDBCDataModel"
"public GenericJDBCDataModel(Properties props) throws TasteException { super(AbstractJDBCComponent.lookupDataSource(props.getProperty(DATA_SOURCE_KEY)), props.getProperty(GET_PREFERENCE_SQL_KEY), props.getProperty(GET_PREFERENCE_TIME_SQL_KEY), props.getProperty(GET_USER_SQL_KEY), props.getProperty(GET_ALL_USERS_SQL_KEY), <MASK>props.getProperty(GET_NUM_USERS_SQL_KEY),</MASK> props.getProperty(GET_NUM_ITEMS_SQL_KEY), props.getProperty(SET_PREFERENCE_SQL_KEY), props.getProperty(REMOVE_PREFERENCE_SQL_KEY), props.getProperty(GET_USERS_SQL_KEY), props.getProperty(GET_ITEMS_SQL_KEY), props.getProperty(GET_PREFS_FOR_ITEM_SQL_KEY), props.getProperty(GET_NUM_PREFERENCE_FOR_ITEM_KEY), props.getProperty(GET_NUM_PREFERENCE_FOR_ITEMS_KEY), props.getProperty(GET_MAX_PREFERENCE_KEY), props.getProperty(GET_MIN_PREFERENCE_KEY)); }"
Inversion-Mutation
megadiff
"public void start() throws Exception { if(running == true) { throw new Exception("Deacon is already running!"); } // Check to see if a timeout is set and it is expired if((this.catchUpTimeOut != 0) && (this.lastStop != 0)) { // Deacon is "resuming" from a previous stop long timedelta = System.currentTimeMillis() - lastStop; if (timedelta > (((long)this.catchUpTimeOut) * 1000)) { // We're past the timeout; zero the catchup parameters of all subscriptions for(Subscription sub : subscriptions) { sub.catchup = 0; } } } // Start the client this.running = true; deaconThread = new Thread(new DeaconRunnable()); deaconThread.start(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "start"
"public void start() throws Exception { if(running == true) { throw new Exception("Deacon is already running!"); } // Check to see if a timeout is set and it is expired if((this.catchUpTimeOut != 0) && (this.lastStop != 0)) { // Deacon is "resuming" from a previous stop long timedelta = System.currentTimeMillis() - lastStop; if (timedelta > (((long)this.catchUpTimeOut) * 1000)) { // We're past the timeout; zero the catchup parameters of all subscriptions for(Subscription sub : subscriptions) { sub.catchup = 0; } } } // Start the client deaconThread = new Thread(new DeaconRunnable()); deaconThread.start(); <MASK>this.running = true;</MASK> }"
Inversion-Mutation
megadiff
"public void run() { InputStream is = null; RandomAccessFile randomAccessFile = null; try { int startPos = downinfo.getCompletesize()*1024; int endPos = downinfo.getFilesize()*1024; is = mService.getPushDownLoadInputStream(downinfo.getUrl(), startPos, endPos); boolean isBreakPoint = mService.getIsBreakPoint(downinfo.getUrl()); randomAccessFile = new RandomAccessFile(file, "rwd"); if(!isBreakPoint) { downinfo.setCompletesize(0); startPos = 0; } // 从断点处 继续下载(初始为0) randomAccessFile.seek(startPos); if (is == null) { return; } final int length = 1024; byte[] b = new byte[length]; int len = -1; int pool = 0; boolean isover = false; long startime = System.currentTimeMillis(); Log.e(TAG, "-----downinfo starttime--->1 " + startime); int tempLen = startPos; callback.downloadUpdate(); while ((len = is.read(b))!=-1) { if (isPause) { return; } randomAccessFile.write(b, 0, len); pool += len; if (pool >= 100 * 1024) { // 100kb写一次数据库 Log.e(TAG, "-----下载 未完成----" + len); PushDownLoadDBHelper.getInstances().update(downinfo); //暂不支持断点下载 pool = 0; callback.downloadUpdate();// 刷新一次 } tempLen += len; downinfo.setCompletesize(tempLen/1024); if (pool != 0) { //PushDownLoadDBHelper.getInstances().update(downinfo);/// 暂不支持断点下载 } } long endtime = System.currentTimeMillis(); Log.e(TAG, "-----downinfo time--->1 " + (endtime - startime)); } catch (Exception e) { //Log.i(TAG, "-------->e " + e); e.printStackTrace(); } finally { // end.countDown(); Log.e(TAG, "---over----"); PushDownLoadDBHelper.getInstances().update(downinfo); if (downinfo.getCompletesize() >= downinfo.getFilesize()) { Log.i(TAG, "----finsh----"); if(callback != null){ callback.downloadSucceed(); } }else{ callback.downloadFailed(); } callback.downloadUpdate(); map.remove(String.valueOf(downinfo.getId())); if (is != null) { try { is.close(); } catch (IOException e) { } } if (randomAccessFile != null) { try { randomAccessFile.close(); } catch (IOException e) { } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { InputStream is = null; RandomAccessFile randomAccessFile = null; try { int startPos = downinfo.getCompletesize()*1024; int endPos = downinfo.getFilesize()*1024; is = mService.getPushDownLoadInputStream(downinfo.getUrl(), startPos, endPos); boolean isBreakPoint = mService.getIsBreakPoint(downinfo.getUrl()); randomAccessFile = new RandomAccessFile(file, "rwd"); if(!isBreakPoint) { downinfo.setCompletesize(0); startPos = 0; } // 从断点处 继续下载(初始为0) randomAccessFile.seek(startPos); if (is == null) { return; } final int length = 1024; byte[] b = new byte[length]; int len = -1; int pool = 0; boolean isover = false; long startime = System.currentTimeMillis(); Log.e(TAG, "-----downinfo starttime--->1 " + startime); int tempLen = startPos; callback.downloadUpdate(); while ((len = is.read(b))!=-1) { if (isPause) { return; } randomAccessFile.write(b, 0, len); pool += len; if (pool >= 100 * 1024) { // 100kb写一次数据库 Log.e(TAG, "-----下载 未完成----" + len); <MASK>PushDownLoadDBHelper.getInstances().update(downinfo);</MASK> //暂不支持断点下载 pool = 0; callback.downloadUpdate();// 刷新一次 } tempLen += len; downinfo.setCompletesize(tempLen/1024); if (pool != 0) { //<MASK>PushDownLoadDBHelper.getInstances().update(downinfo);</MASK>/// 暂不支持断点下载 } } long endtime = System.currentTimeMillis(); Log.e(TAG, "-----downinfo time--->1 " + (endtime - startime)); } catch (Exception e) { //Log.i(TAG, "-------->e " + e); e.printStackTrace(); } finally { // end.countDown(); Log.e(TAG, "---over----"); if (downinfo.getCompletesize() >= downinfo.getFilesize()) { Log.i(TAG, "----finsh----"); <MASK>PushDownLoadDBHelper.getInstances().update(downinfo);</MASK> if(callback != null){ callback.downloadSucceed(); } }else{ callback.downloadFailed(); } callback.downloadUpdate(); map.remove(String.valueOf(downinfo.getId())); if (is != null) { try { is.close(); } catch (IOException e) { } } if (randomAccessFile != null) { try { randomAccessFile.close(); } catch (IOException e) { } } } }"
Inversion-Mutation
megadiff
"private SimpleFieldSet handleGetIdentitiesByScore(final SimpleFieldSet params) throws InvalidParameterException, UnknownIdentityException { final String treeOwnerID = params.get("TreeOwner"); final String selection = getMandatoryParameter(params, "Selection"); final String context = getMandatoryParameter(params, "Context"); final String selectString = selection.trim(); int select = 0; // TODO: decide about the default value if (selectString.equals("+")) select = 1; else if (selectString.equals("-")) select = -1; else if (selectString.equals("0")) select = 0; else throw new InvalidParameterException("Unhandled selection value (" + select + ")"); final SimpleFieldSet sfs = new SimpleFieldSet(true); sfs.putOverwrite("Message", "Identities"); synchronized(mWoT) { final OwnIdentity treeOwner = treeOwnerID != null ? mWoT.getOwnIdentityByID(treeOwnerID) : null; final ObjectSet<Score> result = mWoT.getIdentitiesByScore(treeOwner, select); final boolean getAll = context.equals(""); for(int i = 0; result.hasNext(); ) { final Score score = result.next(); if(getAll || score.getTarget().hasContext(context)) { final Identity identity = score.getTarget(); sfs.putOverwrite("Identity" + i, identity.getID()); sfs.putOverwrite("RequestURI" + i, identity.getRequestURI().toString()); sfs.putOverwrite("Nickname" + i, identity.getNickname() != null ? identity.getNickname() : ""); int contextCounter = 0; for (String identityContext: identity.getContexts()) { sfs.putOverwrite("Contexts" + i + ".Context" + contextCounter++, identityContext); } int propertiesCounter = 0; for (Entry<String, String> property : identity.getProperties().entrySet()) { sfs.putOverwrite("Properties" + i + ".Property" + propertiesCounter + ".Name", property.getKey()); sfs.putOverwrite("Properties" + i + ".Property" + propertiesCounter++ + ".Value", property.getValue()); } // TODO: Allow the client to select what data he wants ++i; } } } return sfs; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleGetIdentitiesByScore"
"private SimpleFieldSet handleGetIdentitiesByScore(final SimpleFieldSet params) throws InvalidParameterException, UnknownIdentityException { final String treeOwnerID = params.get("TreeOwner"); final String selection = getMandatoryParameter(params, "Selection"); final String context = getMandatoryParameter(params, "Context"); final String selectString = selection.trim(); int select = 0; // TODO: decide about the default value if (selectString.equals("+")) select = 1; else if (selectString.equals("-")) select = -1; else if (selectString.equals("0")) select = 0; else throw new InvalidParameterException("Unhandled selection value (" + select + ")"); final SimpleFieldSet sfs = new SimpleFieldSet(true); sfs.putOverwrite("Message", "Identities"); synchronized(mWoT) { final OwnIdentity treeOwner = treeOwnerID != null ? mWoT.getOwnIdentityByID(treeOwnerID) : null; final ObjectSet<Score> result = mWoT.getIdentitiesByScore(treeOwner, select); final boolean getAll = context.equals(""); for(int i = 0; result.hasNext(); ) { final Score score = result.next(); if(getAll || score.getTarget().hasContext(context)) { final Identity identity = score.getTarget(); sfs.putOverwrite("Identity" + i, identity.getID()); sfs.putOverwrite("RequestURI" + i, identity.getRequestURI().toString()); sfs.putOverwrite("Nickname" + i, identity.getNickname() != null ? identity.getNickname() : ""); <MASK>++i;</MASK> int contextCounter = 0; for (String identityContext: identity.getContexts()) { sfs.putOverwrite("Contexts" + i + ".Context" + contextCounter++, identityContext); } int propertiesCounter = 0; for (Entry<String, String> property : identity.getProperties().entrySet()) { sfs.putOverwrite("Properties" + i + ".Property" + propertiesCounter + ".Name", property.getKey()); sfs.putOverwrite("Properties" + i + ".Property" + propertiesCounter++ + ".Value", property.getValue()); } // TODO: Allow the client to select what data he wants } } } return sfs; }"
Inversion-Mutation
megadiff
"public Card(JsonObject obj){ this.name = obj.has(PROP_CARD_NAME) ? obj.getAsJsonPrimitive(PROP_CARD_NAME).getAsString() : ""; this.color = obj.has(PROP_CARD_COLOR) ? obj.getAsJsonPrimitive(PROP_CARD_COLOR).getAsString() : ""; this.cost = convertJSONToAssetMap(obj, PROP_CARD_COST); this.minPlayers = obj.has(PROP_CARD_MIN_PLAYERS) ? obj.getAsJsonPrimitive(PROP_CARD_MIN_PLAYERS).getAsInt() : 0; this.age = obj.has(PROP_CARD_AGE) ? obj.getAsJsonPrimitive(PROP_CARD_AGE).getAsInt() : 0; this.id = this.getName().replace(" ","")+"_"+this.age+"_"+this.minPlayers; this.image = new ImageIcon(SevenWonders.PATH_IMG+getId()+".png").getImage(); //figure out what this card actually does this.baseAssets = convertJSONToAssetMap(obj,PROP_CARD_BASE_ASSETS); this.multiplierAssets = convertJSArrayToSet(obj,PROP_CARD_MULTIPLIER_ASSETS); this.multiplierTargets = convertJSArrayToSet(obj,PROP_CARD_MULTIPLIER_TARGETS); this.discountsAssets = convertJSArrayToSet(obj,PROP_CARD_DISCOUNTS_ASSETS); this.discountsTargets = convertJSArrayToSet(obj,PROP_CARD_DISCOUNTS_TARGETS); this.isChoice = obj.has(PROP_CARD_CHOICE) && obj.getAsJsonPrimitive(PROP_CARD_CHOICE).getAsBoolean(); this.freeFor = obj.has(PROP_CARD_FREE_FOR) ? obj.getAsJsonPrimitive(PROP_CARD_FREE_FOR).getAsString() : ""; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Card"
"public Card(JsonObject obj){ this.name = obj.has(PROP_CARD_NAME) ? obj.getAsJsonPrimitive(PROP_CARD_NAME).getAsString() : ""; this.color = obj.has(PROP_CARD_COLOR) ? obj.getAsJsonPrimitive(PROP_CARD_COLOR).getAsString() : ""; this.cost = convertJSONToAssetMap(obj, PROP_CARD_COST); this.minPlayers = obj.has(PROP_CARD_MIN_PLAYERS) ? obj.getAsJsonPrimitive(PROP_CARD_MIN_PLAYERS).getAsInt() : 0; this.age = obj.has(PROP_CARD_AGE) ? obj.getAsJsonPrimitive(PROP_CARD_AGE).getAsInt() : 0; this.image = new ImageIcon(SevenWonders.PATH_IMG+getId()+".png").getImage(); //figure out what this card actually does this.baseAssets = convertJSONToAssetMap(obj,PROP_CARD_BASE_ASSETS); this.multiplierAssets = convertJSArrayToSet(obj,PROP_CARD_MULTIPLIER_ASSETS); this.multiplierTargets = convertJSArrayToSet(obj,PROP_CARD_MULTIPLIER_TARGETS); this.discountsAssets = convertJSArrayToSet(obj,PROP_CARD_DISCOUNTS_ASSETS); this.discountsTargets = convertJSArrayToSet(obj,PROP_CARD_DISCOUNTS_TARGETS); this.isChoice = obj.has(PROP_CARD_CHOICE) && obj.getAsJsonPrimitive(PROP_CARD_CHOICE).getAsBoolean(); this.freeFor = obj.has(PROP_CARD_FREE_FOR) ? obj.getAsJsonPrimitive(PROP_CARD_FREE_FOR).getAsString() : ""; <MASK>this.id = this.getName().replace(" ","")+"_"+this.age+"_"+this.minPlayers;</MASK> }"
Inversion-Mutation
megadiff
"@Override protected void hideFakeTitleBar() { if (isFakeTitleBarShowing()) { mFakeTitleBar.setEditMode(false); mTabBar.onHideTitleBar(); mContentView.removeView(mFakeTitleBar); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "hideFakeTitleBar"
"@Override protected void hideFakeTitleBar() { if (isFakeTitleBarShowing()) { mFakeTitleBar.setEditMode(false); <MASK>mContentView.removeView(mFakeTitleBar);</MASK> mTabBar.onHideTitleBar(); } }"
Inversion-Mutation
megadiff
"public UserVO updateUser(long userId, AccessLevel accessLevel, int invites) { final UserVO user = findUserBy(userId); user.setAccessLevel(accessLevel); userDao.store(user); UserProfile userProfile = getUserProfile(user.getUserName()); //errors can occur where user is saved without profile if (null == userProfile) { userProfile = UserProfile.newProfile(user); } userProfile.setInvites(invites); userDao.store(userProfile); return user; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateUser"
"public UserVO updateUser(long userId, AccessLevel accessLevel, int invites) { final UserVO user = findUserBy(userId); user.setAccessLevel(accessLevel); userDao.store(user); UserProfile userProfile = getUserProfile(user.getUserName()); //errors can occur where user is saved without profile if (null == userProfile) { userProfile = UserProfile.newProfile(user); <MASK>userProfile.setInvites(invites);</MASK> } userDao.store(userProfile); return user; }"
Inversion-Mutation
megadiff
"public void start() { m_Listener = new Thread(this); m_Listening.set(true); m_Listener.start(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "start"
"public void start() { m_Listener = new Thread(this); <MASK>m_Listener.start();</MASK> m_Listening.set(true); }"
Inversion-Mutation
megadiff
"private void vmExecute(int nexeccalls) { // This labelled while loop is used to simulate the effect of C's // goto. The end of the while loop is never reached. The beginning // of the while loop is branched to using a "continue reentry;" // statement (when a Lua function is called or returns). reentry: while (true) { // assert stack.elementAt[ci.function()] instanceof LuaFunction; LuaFunction function = (LuaFunction)stack.elementAt(ci.function()); Proto proto = function.proto(); int[] code = proto.code(); Object[] k = proto.constant(); int pc = savedpc; while (true) // main loop of interpreter { // Where the PUC-Rio code used the Protect macro, this has been // replaced with "savedpc = pc" and a "// Protect" comment. // Where the PUC-Rio code used the dojump macro, this has been // replaced with the equivalent increment of the pc and a // "//dojump" comment. int i = code[pc++]; // VM instruction. // :todo: count and line hook int a = ARGA(i); // its A field. Object rb; Object rc; switch (OPCODE(i)) { case OP_MOVE: stack.setElementAt(stack.elementAt(base+ARGB(i)), base+a); continue; case OP_LOADK: stack.setElementAt(k[ARGBx(i)], base+a); continue; case OP_LOADBOOL: stack.setElementAt(valueOfBoolean(ARGB(i) != 0), base+a); if (ARGC(i) != 0) { ++pc; } continue; case OP_LOADNIL: { int b = base + ARGB(i); do { stack.setElementAt(NIL, b--); } while (b >= base + a); continue; } case OP_GETUPVAL: { int b = ARGB(i); stack.setElementAt(function.upVal(b).getValue(), base+a); continue; } case OP_GETGLOBAL: rb = k[ARGBx(i)]; // assert rb instance of String; savedpc = pc; // Protect stack.setElementAt(vmGettable(function.getEnv(), rb), base+a); continue; case OP_GETTABLE: { savedpc = pc; // Protect Object t = stack.elementAt(base+ARGB(i)); stack.setElementAt(vmGettable(t, RK(k, ARGC(i))), base+a); continue; } case OP_SETUPVAL: { UpVal uv = function.upVal(ARGB(i)); uv.setValue(stack.elementAt(base+a)); continue; } case OP_SETGLOBAL: savedpc = pc; // Protect vmSettable(function.getEnv(), k[ARGBx(i)], stack.elementAt(base+a)); continue; case OP_SETTABLE: { savedpc = pc; // Protect Object t = stack.elementAt(base+a); vmSettable(t, RK(k, ARGB(i)), RK(k, ARGC(i))); continue; } case OP_NEWTABLE: { // :todo: use the b and c hints, currently ignored. int b = ARGB(i); int c = ARGC(i); stack.setElementAt(new LuaTable(), base+a); continue; } case OP_SELF: { int b = ARGB(i); rb = stack.elementAt(base+b); stack.setElementAt(rb, base+a+1); savedpc = pc; // Protect stack.setElementAt(vmGettable(rb, RK(k, ARGC(i))), base+a); continue; } case OP_ADD: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double sum = ((Double)rb).doubleValue() + ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(sum), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double sum = NUMOP[0] + NUMOP[1]; stack.setElementAt(valueOfNumber(sum), base+a); } else { // :todo: use metamethod throw new IllegalArgumentException(); } continue; case OP_SUB: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double difference = ((Double)rb).doubleValue() - ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(difference), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double difference = NUMOP[0] - NUMOP[1]; stack.setElementAt(valueOfNumber(difference), base+a); } else { // :todo: use metamethod throw new IllegalArgumentException(); } continue; case OP_MUL: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double product = ((Double)rb).doubleValue() * ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(product), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double product = NUMOP[0] * NUMOP[1]; stack.setElementAt(valueOfNumber(product), base+a); } else { // :todo: use metamethod throw new IllegalArgumentException(); } continue; case OP_DIV: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double quotient = ((Double)rb).doubleValue() / ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(quotient), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double quotient = NUMOP[0] / NUMOP[1]; stack.setElementAt(valueOfNumber(quotient), base+a); } else { // :todo: use metamethod throw new IllegalArgumentException(); } continue; case OP_MOD: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double db = ((Double)rb).doubleValue(); double dc = ((Double)rc).doubleValue(); double modulus = modulus(db, dc); stack.setElementAt(valueOfNumber(modulus), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double modulus = modulus(NUMOP[0], NUMOP[1]); stack.setElementAt(valueOfNumber(modulus), base+a); } else { // :todo: use metamethod throw new IllegalArgumentException(); } continue; case OP_POW: // There's no Math.pow. :todo: consider implementing. rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double result = iNumpow (((Double)rb).doubleValue(), ((Double)rc).doubleValue()); stack.setElementAt(valueOfNumber(result), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double result = iNumpow (NUMOP[0], NUMOP[1]); stack.setElementAt(valueOfNumber(result), base+a); } else { // :todo: use metamethod throw new IllegalArgumentException(); } continue; case OP_UNM: { rb = stack.elementAt(base+ARGB(i)); if (rb instanceof Double) { double db = ((Double)rb).doubleValue(); stack.setElementAt(valueOfNumber(-db), base+a); } else if (tonumber(rb, NUMOP)) { stack.setElementAt(valueOfNumber(-NUMOP[0]), base+a); } else { // :todo: metamethod throw new IllegalArgumentException(); } continue; } case OP_NOT: { Object ra = stack.elementAt(base+ARGB(i)); stack.setElementAt(valueOfBoolean(isFalse(ra)), base+a); continue; } case OP_LEN: rb = stack.elementAt(base+ARGB(i)); if (rb instanceof LuaTable) { LuaTable t = (LuaTable)rb; stack.setElementAt(new Double(t.getn()), base+a); continue; } else if (rb instanceof String) { String s = (String)rb; stack.setElementAt(new Double(s.length()), base+a); continue; } // :todo: metamethod throw new IllegalArgumentException(); case OP_CONCAT: { int b = ARGB(i); int c = ARGC(i); savedpc = pc; // Protect // :todo: It's possible that the compiler assumes that all // stack locations _above_ b end up with junk in them. In // which case we can improve the speed of vmConcat (by not // converting each stack slot, but simply using // StringBuffer.append on whatever is there). vmConcat(c - b + 1, c); stack.setElementAt(stack.elementAt(base+b), base+a); continue; } case OP_JMP: // dojump pc += ARGsBx(i); continue; case OP_EQ: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (vmEqual(rb, rc) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_LT: savedpc = pc; // Protect if (vmLessthan(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_LE: savedpc = pc; // Protect if (vmLessequal(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_TEST: if (isFalse(stack.elementAt(base+a)) != (ARGC(i) != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_TESTSET: rb = stack.elementAt(base+ARGB(i)); if (isFalse(rb) != (ARGC(i) != 0)) { stack.setElementAt(rb, base+a); // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_CALL: { int b = ARGB(i); int nresults = ARGC(i) - 1; if (b != 0) { stack.setSize(base+a+b); } savedpc = pc; switch (vmPrecall(base+a, nresults)) { case PCRLUA: nexeccalls++; continue reentry; case PCRJ: // Was Java function called by precall, adjust result if (nresults >= 0) { stack.setSize(ci.top()); } continue; default: return; // yield } } case OP_TAILCALL: { int b = ARGB(i); if (b != 0) { stack.setSize(base+a+b); } savedpc = pc; // assert ARGC(i) - 1 == MULTRET switch (vmPrecall(base+a, MULTRET)) { case PCRLUA: { // tail call: put new frame in place of previous one. CallInfo ci = (CallInfo)civ.elementAt(civ.size()-2); int func = ci.function(); int pfunc = this.ci.function(); fClose(base); base = func + (this.ci.base() - pfunc); int aux; // loop index is used after loop ends for (aux=0; pfunc+aux < stack.size(); ++aux) { // move frame down stack.setElementAt(stack.elementAt(pfunc+aux), func+aux); } stack.setSize(func+aux); // correct top // assert stack.size() == base + ((LuaFunction)stack.elementAt(func)).proto().maxstacksize(); ci.tailcall(base, stack.size()); dec_ci(); // remove new frame. continue reentry; } case PCRJ: // It was a Java function { continue; } default: { return; // yield } } } case OP_RETURN: { fClose(base); int b = ARGB(i); if (b != 0) { int top = a + b - 1; stack.setSize(base + top); } savedpc = pc; // 'adjust' replaces aliased 'b' in PUC-Rio code. boolean adjust = vmPoscall(base+a); if (--nexeccalls == 0) { return; } if (adjust) { stack.setSize(ci.top()); } continue reentry; } case OP_FORLOOP: { double step = ((Double)stack.elementAt(base+a+2)).doubleValue(); double idx = ((Double)stack.elementAt(base+a)).doubleValue() + step; double limit = ((Double)stack.elementAt(base+a+1)).doubleValue(); if ((0 < step && idx <= limit) || (step <= 0 && limit <= idx)) { // dojump pc += ARGsBx(i); Object d = valueOfNumber(idx); stack.setElementAt(d, base+a); // internal index stack.setElementAt(d, base+a+3); // external index } continue; } case OP_FORPREP: { int init = base+a; int plimit = base+a+1; int pstep = base+a+2; savedpc = pc; // next steps may throw errors if (!tonumber(init)) { gRunerror("'for' initial value must be a number"); } else if (!tonumber(plimit)) { gRunerror("'for' limit must be a number"); } else if (!tonumber(pstep)) { gRunerror("'for' step must be a number"); } double step = ((Double)stack.elementAt(pstep)).doubleValue(); double idx = ((Double)stack.elementAt(init)).doubleValue() - step; stack.setElementAt(new Double(idx), init); // dojump pc += ARGsBx(i); continue; } case OP_TFORLOOP: { int cb = base+a+3; // call base stack.setElementAt(stack.elementAt(base+a+2), cb+2); stack.setElementAt(stack.elementAt(base+a+1), cb+1); stack.setElementAt(stack.elementAt(base+a), cb); stack.setSize(cb+3); savedpc = pc; // Protect vmCall(cb, ARGC(i)); stack.setSize(ci.top()); if (NIL != stack.elementAt(cb)) // continue loop { stack.setElementAt(stack.elementAt(cb), cb-1); // dojump pc += ARGsBx(code[pc]); } ++pc; continue; } case OP_SETLIST: { int n = ARGB(i); int c = ARGC(i); int last; LuaTable t; if (0 == n) { n = (stack.size() - a) - 1; // :todo: check this against PUC-Rio // stack.setSize ?? } if (0 == c) { c = code[pc++]; } t = (LuaTable)stack.elementAt(base+a); last = ((c-1)*LFIELDS_PER_FLUSH) + n; // :todo: consider expanding space in table for (; n > 0; n--) { Object val = stack.elementAt(base+a+n); t.putnum(last--, val); } continue; } case OP_CLOSE: fClose(base+a); continue; case OP_CLOSURE: { Proto p = function.proto().proto()[ARGBx(i)]; int nup = p.nups(); UpVal[] up = new UpVal[nup]; for (int j=0; j<nup; j++, pc++) { int in = code[pc]; if (OPCODE(in) == OP_GETUPVAL) { up[j] = function.upVal(ARGB(in)); } else { // assert OPCODE(in) == OP_MOVE; up[j] = fFindupval(base + ARGB(in)); } } LuaFunction nf = new LuaFunction(p, up, function.getEnv()); stack.setElementAt(nf, base+a); continue; } case OP_VARARG: { int b = ARGB(i)-1; int n = (base - ci.function()) - function.proto().numparams() - 1; if (b == MULTRET) { // :todo: Protect // :todo: check stack b = n; stack.setSize(base+a+n); } for (int j=0; j<b; ++j) { if (j < n) { Object src = stack.elementAt(base - n + j); stack.setElementAt(src, base+a+j); } else { stack.setElementAt(NIL, base+a+j); } } continue; } } /* switch */ } /* while */ } /* reentry: while */ }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "vmExecute"
"private void vmExecute(int nexeccalls) { // This labelled while loop is used to simulate the effect of C's // goto. The end of the while loop is never reached. The beginning // of the while loop is branched to using a "continue reentry;" // statement (when a Lua function is called or returns). reentry: while (true) { // assert stack.elementAt[ci.function()] instanceof LuaFunction; LuaFunction function = (LuaFunction)stack.elementAt(ci.function()); Proto proto = function.proto(); int[] code = proto.code(); Object[] k = proto.constant(); int pc = savedpc; while (true) // main loop of interpreter { // Where the PUC-Rio code used the Protect macro, this has been // replaced with "savedpc = pc" and a "// Protect" comment. // Where the PUC-Rio code used the dojump macro, this has been // replaced with the equivalent increment of the pc and a // "//dojump" comment. int i = code[pc++]; // VM instruction. // :todo: count and line hook int a = ARGA(i); // its A field. Object rb; Object rc; switch (OPCODE(i)) { case OP_MOVE: stack.setElementAt(stack.elementAt(base+ARGB(i)), base+a); continue; case OP_LOADK: stack.setElementAt(k[ARGBx(i)], base+a); continue; case OP_LOADBOOL: stack.setElementAt(valueOfBoolean(ARGB(i) != 0), base+a); if (ARGC(i) != 0) { ++pc; } continue; case OP_LOADNIL: { int b = base + ARGB(i); do { stack.setElementAt(NIL, b--); } while (b >= base + a); continue; } case OP_GETUPVAL: { int b = ARGB(i); stack.setElementAt(function.upVal(b).getValue(), base+a); continue; } case OP_GETGLOBAL: rb = k[ARGBx(i)]; // assert rb instance of String; savedpc = pc; // Protect stack.setElementAt(vmGettable(function.getEnv(), rb), base+a); continue; case OP_GETTABLE: { savedpc = pc; // Protect Object t = stack.elementAt(base+ARGB(i)); stack.setElementAt(vmGettable(t, RK(k, ARGC(i))), base+a); continue; } case OP_SETUPVAL: { UpVal uv = function.upVal(ARGB(i)); uv.setValue(stack.elementAt(base+a)); continue; } case OP_SETGLOBAL: savedpc = pc; // Protect vmSettable(function.getEnv(), k[ARGBx(i)], stack.elementAt(base+a)); continue; case OP_SETTABLE: { savedpc = pc; // Protect Object t = stack.elementAt(base+a); vmSettable(t, RK(k, ARGB(i)), RK(k, ARGC(i))); continue; } case OP_NEWTABLE: { // :todo: use the b and c hints, currently ignored. int b = ARGB(i); int c = ARGC(i); stack.setElementAt(new LuaTable(), base+a); continue; } case OP_SELF: { int b = ARGB(i); rb = stack.elementAt(base+b); stack.setElementAt(rb, base+a+1); savedpc = pc; // Protect stack.setElementAt(vmGettable(rb, RK(k, ARGC(i))), base+a); continue; } case OP_ADD: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double sum = ((Double)rb).doubleValue() + ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(sum), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double sum = NUMOP[0] + NUMOP[1]; stack.setElementAt(valueOfNumber(sum), base+a); } else { // :todo: use metamethod throw new IllegalArgumentException(); } continue; case OP_SUB: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double difference = ((Double)rb).doubleValue() - ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(difference), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double difference = NUMOP[0] - NUMOP[1]; stack.setElementAt(valueOfNumber(difference), base+a); } else { // :todo: use metamethod throw new IllegalArgumentException(); } continue; case OP_MUL: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double product = ((Double)rb).doubleValue() * ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(product), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double product = NUMOP[0] * NUMOP[1]; stack.setElementAt(valueOfNumber(product), base+a); } else { // :todo: use metamethod throw new IllegalArgumentException(); } continue; case OP_DIV: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double quotient = ((Double)rb).doubleValue() / ((Double)rc).doubleValue(); stack.setElementAt(valueOfNumber(quotient), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double quotient = NUMOP[0] / NUMOP[1]; stack.setElementAt(valueOfNumber(quotient), base+a); } else { // :todo: use metamethod throw new IllegalArgumentException(); } continue; case OP_MOD: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double db = ((Double)rb).doubleValue(); double dc = ((Double)rc).doubleValue(); double modulus = modulus(db, dc); stack.setElementAt(valueOfNumber(modulus), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double modulus = modulus(NUMOP[0], NUMOP[1]); stack.setElementAt(valueOfNumber(modulus), base+a); } else { // :todo: use metamethod throw new IllegalArgumentException(); } continue; case OP_POW: // There's no Math.pow. :todo: consider implementing. rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (rb instanceof Double && rc instanceof Double) { double result = iNumpow (((Double)rb).doubleValue(), ((Double)rc).doubleValue()); stack.setElementAt(valueOfNumber(result), base+a); } else if (toNumberPair(rb, rc, NUMOP)) { double result = iNumpow (NUMOP[0], NUMOP[1]); stack.setElementAt(valueOfNumber(result), base+a); } else { // :todo: use metamethod throw new IllegalArgumentException(); } continue; case OP_UNM: { rb = stack.elementAt(base+ARGB(i)); if (rb instanceof Double) { double db = ((Double)rb).doubleValue(); stack.setElementAt(valueOfNumber(-db), base+a); } else if (tonumber(rb, NUMOP)) { stack.setElementAt(valueOfNumber(-NUMOP[0]), base+a); } else { // :todo: metamethod throw new IllegalArgumentException(); } continue; } case OP_NOT: { Object ra = stack.elementAt(base+ARGB(i)); stack.setElementAt(valueOfBoolean(isFalse(ra)), base+a); continue; } case OP_LEN: rb = stack.elementAt(base+ARGB(i)); if (rb instanceof LuaTable) { LuaTable t = (LuaTable)rb; stack.setElementAt(new Double(t.getn()), base+a); continue; } else if (rb instanceof String) { String s = (String)rb; stack.setElementAt(new Double(s.length()), base+a); continue; } // :todo: metamethod throw new IllegalArgumentException(); case OP_CONCAT: { int b = ARGB(i); int c = ARGC(i); savedpc = pc; // Protect // :todo: It's possible that the compiler assumes that all // stack locations _above_ b end up with junk in them. In // which case we can improve the speed of vmConcat (by not // converting each stack slot, but simply using // StringBuffer.append on whatever is there). vmConcat(c - b + 1, c); stack.setElementAt(stack.elementAt(base+b), base+a); continue; } case OP_JMP: // dojump pc += ARGsBx(i); continue; case OP_EQ: rb = RK(k, ARGB(i)); rc = RK(k, ARGC(i)); if (vmEqual(rb, rc) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_LT: savedpc = pc; // Protect if (vmLessthan(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_LE: savedpc = pc; // Protect if (vmLessequal(RK(k, ARGB(i)), RK(k, ARGC(i))) == (a != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_TEST: if (isFalse(stack.elementAt(base+a)) != (ARGC(i) != 0)) { // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_TESTSET: rb = stack.elementAt(base+ARGB(i)); if (isFalse(rb) != (ARGC(i) != 0)) { stack.setElementAt(rb, base+a); // dojump pc += ARGsBx(code[pc]); } ++pc; continue; case OP_CALL: { int b = ARGB(i); int nresults = ARGC(i) - 1; if (b != 0) { stack.setSize(base+a+b); } savedpc = pc; switch (vmPrecall(base+a, nresults)) { case PCRLUA: nexeccalls++; continue reentry; case PCRJ: // Was Java function called by precall, adjust result if (nresults >= 0) { stack.setSize(ci.top()); } continue; default: return; // yield } } case OP_TAILCALL: { int b = ARGB(i); if (b != 0) { stack.setSize(base+a+b); } savedpc = pc; // assert ARGC(i) - 1 == MULTRET switch (vmPrecall(base+a, MULTRET)) { case PCRLUA: { // tail call: put new frame in place of previous one. CallInfo ci = (CallInfo)civ.elementAt(civ.size()-2); int func = ci.function(); int pfunc = this.ci.function(); <MASK>fClose(base);</MASK> base = func + (this.ci.base() - pfunc); int aux; // loop index is used after loop ends for (aux=0; pfunc+aux < stack.size(); ++aux) { // move frame down stack.setElementAt(stack.elementAt(pfunc+aux), func+aux); } stack.setSize(func+aux); // correct top // assert stack.size() == base + ((LuaFunction)stack.elementAt(func)).proto().maxstacksize(); ci.tailcall(base, stack.size()); dec_ci(); // remove new frame. continue reentry; } case PCRJ: // It was a Java function { continue; } default: { return; // yield } } } case OP_RETURN: { int b = ARGB(i); if (b != 0) { int top = a + b - 1; stack.setSize(base + top); } <MASK>fClose(base);</MASK> savedpc = pc; // 'adjust' replaces aliased 'b' in PUC-Rio code. boolean adjust = vmPoscall(base+a); if (--nexeccalls == 0) { return; } if (adjust) { stack.setSize(ci.top()); } continue reentry; } case OP_FORLOOP: { double step = ((Double)stack.elementAt(base+a+2)).doubleValue(); double idx = ((Double)stack.elementAt(base+a)).doubleValue() + step; double limit = ((Double)stack.elementAt(base+a+1)).doubleValue(); if ((0 < step && idx <= limit) || (step <= 0 && limit <= idx)) { // dojump pc += ARGsBx(i); Object d = valueOfNumber(idx); stack.setElementAt(d, base+a); // internal index stack.setElementAt(d, base+a+3); // external index } continue; } case OP_FORPREP: { int init = base+a; int plimit = base+a+1; int pstep = base+a+2; savedpc = pc; // next steps may throw errors if (!tonumber(init)) { gRunerror("'for' initial value must be a number"); } else if (!tonumber(plimit)) { gRunerror("'for' limit must be a number"); } else if (!tonumber(pstep)) { gRunerror("'for' step must be a number"); } double step = ((Double)stack.elementAt(pstep)).doubleValue(); double idx = ((Double)stack.elementAt(init)).doubleValue() - step; stack.setElementAt(new Double(idx), init); // dojump pc += ARGsBx(i); continue; } case OP_TFORLOOP: { int cb = base+a+3; // call base stack.setElementAt(stack.elementAt(base+a+2), cb+2); stack.setElementAt(stack.elementAt(base+a+1), cb+1); stack.setElementAt(stack.elementAt(base+a), cb); stack.setSize(cb+3); savedpc = pc; // Protect vmCall(cb, ARGC(i)); stack.setSize(ci.top()); if (NIL != stack.elementAt(cb)) // continue loop { stack.setElementAt(stack.elementAt(cb), cb-1); // dojump pc += ARGsBx(code[pc]); } ++pc; continue; } case OP_SETLIST: { int n = ARGB(i); int c = ARGC(i); int last; LuaTable t; if (0 == n) { n = (stack.size() - a) - 1; // :todo: check this against PUC-Rio // stack.setSize ?? } if (0 == c) { c = code[pc++]; } t = (LuaTable)stack.elementAt(base+a); last = ((c-1)*LFIELDS_PER_FLUSH) + n; // :todo: consider expanding space in table for (; n > 0; n--) { Object val = stack.elementAt(base+a+n); t.putnum(last--, val); } continue; } case OP_CLOSE: fClose(base+a); continue; case OP_CLOSURE: { Proto p = function.proto().proto()[ARGBx(i)]; int nup = p.nups(); UpVal[] up = new UpVal[nup]; for (int j=0; j<nup; j++, pc++) { int in = code[pc]; if (OPCODE(in) == OP_GETUPVAL) { up[j] = function.upVal(ARGB(in)); } else { // assert OPCODE(in) == OP_MOVE; up[j] = fFindupval(base + ARGB(in)); } } LuaFunction nf = new LuaFunction(p, up, function.getEnv()); stack.setElementAt(nf, base+a); continue; } case OP_VARARG: { int b = ARGB(i)-1; int n = (base - ci.function()) - function.proto().numparams() - 1; if (b == MULTRET) { // :todo: Protect // :todo: check stack b = n; stack.setSize(base+a+n); } for (int j=0; j<b; ++j) { if (j < n) { Object src = stack.elementAt(base - n + j); stack.setElementAt(src, base+a+j); } else { stack.setElementAt(NIL, base+a+j); } } continue; } } /* switch */ } /* while */ } /* reentry: while */ }"
Inversion-Mutation
megadiff
"public synchronized Future<?> addIndexedColumn(ColumnDefinition cdef) { if (indexesByColumn.containsKey(cdef.name)) return null; assert cdef.getIndexType() != null; SecondaryIndex index; try { index = SecondaryIndex.createInstance(baseCfs, cdef); } catch (ConfigurationException e) { throw new RuntimeException(e); } // Keep a single instance of the index per-cf for row level indexes // since we want all columns to be under the index if (index instanceof PerRowSecondaryIndex) { SecondaryIndex currentIndex = rowLevelIndexMap.get(index.getClass()); if (currentIndex == null) { rowLevelIndexMap.put(index.getClass(), index); index.init(); } else { index = currentIndex; index.addColumnDef(cdef); logger.info("Creating new index : {}",cdef); } } else { index.init(); } // link in indexedColumns. this means that writes will add new data to // the index immediately, // so we don't have to lock everything while we do the build. it's up to // the operator to wait // until the index is actually built before using in queries. indexesByColumn.put(cdef.name, index); // if we're just linking in the index to indexedColumns on an // already-built index post-restart, we're done if (index.isIndexBuilt(cdef.name)) return null; return index.buildIndexAsync(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addIndexedColumn"
"public synchronized Future<?> addIndexedColumn(ColumnDefinition cdef) { if (indexesByColumn.containsKey(cdef.name)) return null; assert cdef.getIndexType() != null; <MASK>logger.info("Creating new index : {}",cdef);</MASK> SecondaryIndex index; try { index = SecondaryIndex.createInstance(baseCfs, cdef); } catch (ConfigurationException e) { throw new RuntimeException(e); } // Keep a single instance of the index per-cf for row level indexes // since we want all columns to be under the index if (index instanceof PerRowSecondaryIndex) { SecondaryIndex currentIndex = rowLevelIndexMap.get(index.getClass()); if (currentIndex == null) { rowLevelIndexMap.put(index.getClass(), index); index.init(); } else { index = currentIndex; index.addColumnDef(cdef); } } else { index.init(); } // link in indexedColumns. this means that writes will add new data to // the index immediately, // so we don't have to lock everything while we do the build. it's up to // the operator to wait // until the index is actually built before using in queries. indexesByColumn.put(cdef.name, index); // if we're just linking in the index to indexedColumns on an // already-built index post-restart, we're done if (index.isIndexBuilt(cdef.name)) return null; return index.buildIndexAsync(); }"
Inversion-Mutation
megadiff
"public void run() { try { log.info("Starting Thread " + threadId); synchronized (startSemaphore) { if (!started) { startSemaphore.wait(); } } //log.info("Thread " + threadId + "Opening valve"); if (!valve.open()) { //log.info("Valve couldn't be opened at thread " + threadId); synchronized (VeryBasicValveTest.class) { counterWait ++; } } else { //log.info("Thread " + threadId + " could open the valve"); //Thread.sleep(1000); synchronized (VeryBasicValveTest.class) { counter ++; } valve.close(); } //log.info("Thread " + threadId + " is now closing the valve"); } catch (Exception e) { e.printStackTrace(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { try { log.info("Starting Thread " + threadId); synchronized (startSemaphore) { if (!started) { startSemaphore.wait(); } } //log.info("Thread " + threadId + "Opening valve"); if (!valve.open()) { //log.info("Valve couldn't be opened at thread " + threadId); synchronized (VeryBasicValveTest.class) { counterWait ++; } } else { //log.info("Thread " + threadId + " could open the valve"); //Thread.sleep(1000); synchronized (VeryBasicValveTest.class) { counter ++; } } //log.info("Thread " + threadId + " is now closing the valve"); <MASK>valve.close();</MASK> } catch (Exception e) { e.printStackTrace(); } }"
Inversion-Mutation
megadiff
"public void setAllPersons(List<Person> persons) { this.persons = persons; for (Person person : persons) { if (person.getUsername().equals(username)) { user = person; } selected.add(false); } persons.remove(user); persons.add(user); selected.set(selected.size()-1, true); pcs.firePropertyChange(PERSONS_ADDED_Property, null, persons); requestEverything(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setAllPersons"
"public void setAllPersons(List<Person> persons) { this.persons = persons; for (Person person : persons) { if (person.getUsername().equals(username)) { user = person; <MASK>selected.add(false);</MASK> } } persons.remove(user); persons.add(user); selected.set(selected.size()-1, true); pcs.firePropertyChange(PERSONS_ADDED_Property, null, persons); requestEverything(); }"
Inversion-Mutation
megadiff
"protected void createTrimWidgets(Shell shell) { if (menuBarManager != null) { shell.setMenuBar(menuBarManager.createMenuBar((Decorations) shell)); menuBarManager.updateAll(true); } if (showTopSeperator()) { seperator1 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL); } // will create either a cool bar or a tool bar createToolBarControl(shell); createCoolBarControl(shell); createStatusLine(shell); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createTrimWidgets"
"protected void createTrimWidgets(Shell shell) { if (menuBarManager != null) { menuBarManager.updateAll(true); <MASK>shell.setMenuBar(menuBarManager.createMenuBar((Decorations) shell));</MASK> } if (showTopSeperator()) { seperator1 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL); } // will create either a cool bar or a tool bar createToolBarControl(shell); createCoolBarControl(shell); createStatusLine(shell); }"
Inversion-Mutation
megadiff
"protected void endJob(InternalJob job, IStatus result, boolean notify) { InternalJob blocked = null; int blockedJobCount = 0; long rescheduleDelay = InternalJob.T_NONE; synchronized (lock) { //if the job is finishing asynchronously, there is nothing more to do for now if (result == Job.ASYNC_FINISH) return; //if job is not known then it cannot be done if (job.getState() == Job.NONE) return; if (JobManager.DEBUG && notify) JobManager.debug("Ending job: " + job); //$NON-NLS-1$ job.setResult(result); job.setProgressMonitor(null); job.setThread(null); rescheduleDelay = job.getStartTime(); blocked = job.previous(); job.remove(); changeState(job, Job.NONE); //add any blocked jobs back to the wait queue while (blocked != null) { InternalJob previous = blocked.previous(); changeState(blocked, Job.WAITING); blockedJobCount++; blocked = previous; } } //notify queue outside sync block for (int i = 0; i < blockedJobCount; i++) pool.jobQueued(blocked); //notify listeners outside sync block final boolean reschedule = active && rescheduleDelay > InternalJob.T_NONE && job.shouldSchedule(); if (notify) jobListeners.done((Job) job, result, reschedule); //reschedule the job if requested and we are still active if (reschedule) schedule(job, rescheduleDelay, reschedule); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "endJob"
"protected void endJob(InternalJob job, IStatus result, boolean notify) { InternalJob blocked = null; int blockedJobCount = 0; long rescheduleDelay = InternalJob.T_NONE; synchronized (lock) { //if the job is finishing asynchronously, there is nothing more to do for now if (result == Job.ASYNC_FINISH) return; //if job is not known then it cannot be done if (job.getState() == Job.NONE) return; if (JobManager.DEBUG && notify) JobManager.debug("Ending job: " + job); //$NON-NLS-1$ job.setResult(result); job.setProgressMonitor(null); job.setThread(null); rescheduleDelay = job.getStartTime(); <MASK>changeState(job, Job.NONE);</MASK> blocked = job.previous(); job.remove(); //add any blocked jobs back to the wait queue while (blocked != null) { InternalJob previous = blocked.previous(); changeState(blocked, Job.WAITING); blockedJobCount++; blocked = previous; } } //notify queue outside sync block for (int i = 0; i < blockedJobCount; i++) pool.jobQueued(blocked); //notify listeners outside sync block final boolean reschedule = active && rescheduleDelay > InternalJob.T_NONE && job.shouldSchedule(); if (notify) jobListeners.done((Job) job, result, reschedule); //reschedule the job if requested and we are still active if (reschedule) schedule(job, rescheduleDelay, reschedule); }"
Inversion-Mutation
megadiff
"public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { final ITextEditor textEditor = (ITextEditor)getAdapter(ITextEditor.class); // shortcut : do not show links for non relevant chars (dot, arrows, ...) boolean shortcut = false; if (region == null || !(textEditor instanceof AcceleoEditor)) { shortcut = true; } int offset = region.getOffset(); final AcceleoEditor editor = (AcceleoEditor)textEditor; final int start = Math.max(0, offset - 10); final int end = Math.min(editor.getContent().getText().length(), offset + 10); // Creates a new String to avoid keeping the whole document in memory final String expressionSurroundings = new String(editor.getContent().getText().substring(start, end)); if (!isRelevant(expressionSurroundings, offset - start)) { shortcut = true; } if (shortcut) { return null; } EObject res = null; int wordStart = -1; int wordLength = -1; /* * This boolean will be used to determine whether we need to compute a smarter region than what's * carried on by the AST/CST node. */ boolean inferWordRegion = true; ASTNode astNode = editor.getContent().getResolvedASTNode(offset, offset); if (astNode != null) { res = OpenDeclarationUtils.findDeclarationFromAST(astNode); if (res instanceof IteratorExp && editor.getContent().getOCLEnvironment() != null) { res = OpenDeclarationUtils.findIteratorEOperation(editor.getContent().getOCLEnvironment(), (IteratorExp)res); } wordStart = astNode.getStartPosition(); wordLength = astNode.getEndPosition() - astNode.getStartPosition(); } if (res == null) { CSTNode cstNode = editor.getContent().getCSTNode(offset, offset); if (cstNode != null) { res = OpenDeclarationUtils.findDeclarationFromCST(editor, astNode, cstNode); wordStart = cstNode.getStartPosition(); wordLength = cstNode.getEndPosition() - cstNode.getStartPosition(); } if (cstNode instanceof TypedModel) { inferWordRegion = false; } } IHyperlink[] links = null; if (res != null) { final IRegion wordRegion; if (inferWordRegion) { wordRegion = getWordRegion(editor, offset, wordStart, wordLength); } else { wordRegion = new Region(wordStart, wordLength); } if (wordRegion != null) { links = new IHyperlink[1]; links[0] = new AcceleoElementHyperlink(editor, wordRegion, res); } } return links; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "detectHyperlinks"
"public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { final ITextEditor textEditor = (ITextEditor)getAdapter(ITextEditor.class); // shortcut : do not show links for non relevant chars (dot, arrows, ...) boolean shortcut = false; if (region == null || !(textEditor instanceof AcceleoEditor)) { shortcut = true; } int offset = region.getOffset(); final AcceleoEditor editor = (AcceleoEditor)textEditor; final int start = Math.max(0, offset - 10); final int end = Math.min(editor.getContent().getText().length(), offset + 10); // Creates a new String to avoid keeping the whole document in memory final String expressionSurroundings = new String(editor.getContent().getText().substring(start, end)); if (!isRelevant(expressionSurroundings, offset - start)) { shortcut = true; } if (shortcut) { return null; } EObject res = null; int wordStart = -1; int wordLength = -1; /* * This boolean will be used to determine whether we need to compute a smarter region than what's * carried on by the AST/CST node. */ boolean inferWordRegion = true; ASTNode astNode = editor.getContent().getResolvedASTNode(offset, offset); if (astNode != null) { res = OpenDeclarationUtils.findDeclarationFromAST(astNode); if (res instanceof IteratorExp && editor.getContent().getOCLEnvironment() != null) { res = OpenDeclarationUtils.findIteratorEOperation(editor.getContent().getOCLEnvironment(), (IteratorExp)res); } wordStart = astNode.getStartPosition(); wordLength = astNode.getEndPosition() - astNode.getStartPosition(); } if (res == null) { CSTNode cstNode = editor.getContent().getCSTNode(offset, offset); if (cstNode != null) { res = OpenDeclarationUtils.findDeclarationFromCST(editor, astNode, cstNode); wordStart = cstNode.getStartPosition(); wordLength = cstNode.getEndPosition() - cstNode.getStartPosition(); } if (cstNode instanceof TypedModel) { inferWordRegion = false; } } IHyperlink[] links = null; if (res != null) { <MASK>links = new IHyperlink[1];</MASK> final IRegion wordRegion; if (inferWordRegion) { wordRegion = getWordRegion(editor, offset, wordStart, wordLength); } else { wordRegion = new Region(wordStart, wordLength); } if (wordRegion != null) { links[0] = new AcceleoElementHyperlink(editor, wordRegion, res); } } return links; }"
Inversion-Mutation
megadiff
"private HazelcastHttpSession getSessionWithId(final String sessionId) { HazelcastHttpSession session = mapSessions.get(sessionId); if (session != null && !session.isValid()) { destroySession(session, true); session = null; } return session; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getSessionWithId"
"private HazelcastHttpSession getSessionWithId(final String sessionId) { HazelcastHttpSession session = mapSessions.get(sessionId); if (session != null && !session.isValid()) { <MASK>session = null;</MASK> destroySession(session, true); } return session; }"
Inversion-Mutation
megadiff
"public void testOverriddenEntityName() { emf.createEntityManager().close(); ClassMetaData meta = JPAFacadeHelper.getMetaData(emf, XmlOverrideEntity.class); assertEquals("XmlOverride", meta.getTypeAlias()); MetaDataRepository repo = emf.getConfiguration() .getMetaDataRepositoryInstance(); assertEquals(meta, repo.getMetaData("XmlOverride", XmlOverrideEntity.class.getClassLoader(), true)); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testOverriddenEntityName"
"public void testOverriddenEntityName() { ClassMetaData meta = JPAFacadeHelper.getMetaData(emf, XmlOverrideEntity.class); assertEquals("XmlOverride", meta.getTypeAlias()); <MASK>emf.createEntityManager().close();</MASK> MetaDataRepository repo = emf.getConfiguration() .getMetaDataRepositoryInstance(); assertEquals(meta, repo.getMetaData("XmlOverride", XmlOverrideEntity.class.getClassLoader(), true)); }"
Inversion-Mutation
megadiff
"@EventHandler(priority = EventPriority.NORMAL) public void explodingArrow(ProjectileHitEvent event) { Entity projectile = event.getEntity(); World w = projectile.getWorld(); Location hit = projectile.getLocation(); if (w.getName().equals(name)) { if (projectile instanceof Arrow) { Arrow arrow = (Arrow) projectile; Entity shooter = arrow.getShooter(); Location l = shooter.getLocation(); Block bl = l.getBlock(); Block b = bl.getRelative(BlockFace.DOWN, 2); Material mat = b.getType(); if (shooter instanceof Player) { Player p = (Player) shooter; ItemStack is = p.getItemInHand(); Material i = is.getType(); if (i == Material.BOW && mat == Material.SPONGE) { p.getInventory().removeItem(new ItemStack(Material.ARROW, 20)); w.createExplosion(hit, 8); int strikes = 0; while (strikes < 20) { strikes++; w.strikeLightning(hit); } } Bukkit.getWorld(name).playEffect(arrow.getLocation(), Effect.STEP_SOUND, 10); } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "explodingArrow"
"@EventHandler(priority = EventPriority.NORMAL) public void explodingArrow(ProjectileHitEvent event) { Entity projectile = event.getEntity(); World w = projectile.getWorld(); Location hit = projectile.getLocation(); if (w.getName().equals(name)) { if (projectile instanceof Arrow) { Arrow arrow = (Arrow) projectile; Entity shooter = arrow.getShooter(); Location l = shooter.getLocation(); Block bl = l.getBlock(); Block b = bl.getRelative(BlockFace.DOWN, 2); Material mat = b.getType(); if (shooter instanceof Player) { Player p = (Player) shooter; ItemStack is = p.getItemInHand(); Material i = is.getType(); <MASK>p.getInventory().removeItem(new ItemStack(Material.ARROW, 20));</MASK> if (i == Material.BOW && mat == Material.SPONGE) { w.createExplosion(hit, 8); int strikes = 0; while (strikes < 20) { strikes++; w.strikeLightning(hit); } } Bukkit.getWorld(name).playEffect(arrow.getLocation(), Effect.STEP_SOUND, 10); } } } }"
Inversion-Mutation
megadiff
"public void decode(String batchFile) { BatchItem batchItem; int count = 0; try { recognizer.allocate(); setBatchFile(batchFile); batchManager.start(); logger.info("BatchDecoder: decoding files in " + batchManager.getFilename()); while (count < totalCount && (batchItem = batchManager.getNextItem()) != null) { setInputStream(batchItem.getFilename()); Result result = recognizer.recognize(batchItem.getTranscript()); logger.info("File : " + batchItem.getFilename()); logger.info("Result: " + result); count++; } batchManager.stop(); recognizer.deallocate(); } catch (IOException io) { logger.severe("I/O error during decoding: " + io.getMessage()); } logger.info("BatchDecoder: " + count + " files decoded"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "decode"
"public void decode(String batchFile) { BatchItem batchItem; int count = 0; try { recognizer.allocate(); setBatchFile(batchFile); batchManager.start(); logger.info("BatchDecoder: decoding files in " + batchManager.getFilename()); while (count < totalCount && (batchItem = batchManager.getNextItem()) != null) { setInputStream(batchItem.getFilename()); Result result = recognizer.recognize(batchItem.getTranscript()); logger.info("File : " + batchItem.getFilename()); logger.info("Result: " + result); count++; } batchManager.stop(); } catch (IOException io) { logger.severe("I/O error during decoding: " + io.getMessage()); } <MASK>recognizer.deallocate();</MASK> logger.info("BatchDecoder: " + count + " files decoded"); }"
Inversion-Mutation
megadiff
"public final void play() { p.pushMatrix(); senescence(); update(); render(); p.popMatrix(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "play"
"public final void play() { senescence(); update(); <MASK>p.pushMatrix();</MASK> render(); p.popMatrix(); }"
Inversion-Mutation
megadiff
"@Override public int onStartCommand(Intent intent, int flags, int startId) { // Debug if (Config.LOGD) { Log.d(TAG, "[fn] onStartCommand"); } super.onStartCommand(intent, flags, startId); initVars(); if (intent.getBooleanExtra(STOP_LOCATION_LISTENING, false)) { stopLocationListening(); scheduleNextService(); } else { if (status.isDataAndLocationEnabled()) { startLocationListening(); } scheduleStopLocationListening(); } // The service stops itself through callbacks set in stopLocationListening or startLocationListening return START_REDELIVER_INTENT; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onStartCommand"
"@Override public int onStartCommand(Intent intent, int flags, int startId) { // Debug if (Config.LOGD) { Log.d(TAG, "[fn] onStartCommand"); } super.onStartCommand(intent, flags, startId); initVars(); if (intent.getBooleanExtra(STOP_LOCATION_LISTENING, false)) { stopLocationListening(); scheduleNextService(); } else { if (status.isDataAndLocationEnabled()) { startLocationListening(); <MASK>scheduleStopLocationListening();</MASK> } } // The service stops itself through callbacks set in stopLocationListening or startLocationListening return START_REDELIVER_INTENT; }"
Inversion-Mutation
megadiff
"public static Object run(String applicationName/*R1.0 compatibility*/, URL pluginPathLocation/*R1.0 compatibility*/, String location, String[] args, Runnable handler) throws Exception { Object result = null; applicationR10 = applicationName; // for R1.0 compatibility String[] applicationArgs = startup(pluginPathLocation, location, args, handler); String application = getCurrentPlatformConfiguration().getApplicationIdentifier(); IPlatformRunnable runnable = getRunnable(application); if (runnable == null) throw new IllegalArgumentException(Policy.bind("application.notFound", application)); //$NON-NLS-1$ try { result = runnable.run(applicationArgs); } catch (Throwable e) { e.printStackTrace(); throw new InvocationTargetException(e); } finally { shutdown(); } return result; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public static Object run(String applicationName/*R1.0 compatibility*/, URL pluginPathLocation/*R1.0 compatibility*/, String location, String[] args, Runnable handler) throws Exception { Object result = null; applicationR10 = applicationName; // for R1.0 compatibility String[] applicationArgs = startup(pluginPathLocation, location, args, handler); String application = getCurrentPlatformConfiguration().getApplicationIdentifier(); IPlatformRunnable runnable = getRunnable(application); if (runnable == null) throw new IllegalArgumentException(Policy.bind("application.notFound", application)); //$NON-NLS-1$ try { result = runnable.run(applicationArgs); } catch (Throwable e) { e.printStackTrace(); throw new InvocationTargetException(e); } finally { shutdown(); <MASK>return result;</MASK> } }"
Inversion-Mutation
megadiff
"public void visitLobject(Lobject frame) { Exp standardClassSymbol = frame.getParent().internString(Constants.STANDARDCLASS); Lobject standardClass; try { standardClass = (Lobject) frame.getParent().lookupVariableValue(standardClassSymbol); if (frame.isTaggedWith(standardClass)) { new ClassWrapper(frame).acceptVisitor(this); return; } } catch (UnboundException ignore) { } try { printLcons((Lcons) frame.getAlist()); } catch (IOException e) { // TODO what to do with these exceptions? } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "visitLobject"
"public void visitLobject(Lobject frame) { Exp standardClassSymbol = frame.getParent().internString(Constants.STANDARDCLASS); Lobject standardClass; try { standardClass = (Lobject) frame.getParent().lookupVariableValue(standardClassSymbol); if (frame.isTaggedWith(standardClass)) { new ClassWrapper(frame).acceptVisitor(this); } <MASK>return;</MASK> } catch (UnboundException ignore) { } try { printLcons((Lcons) frame.getAlist()); } catch (IOException e) { // TODO what to do with these exceptions? } }"
Inversion-Mutation
megadiff
"protected ListItem addItem(Object value, boolean newItem) { ListItem item = createItem(); Editor editor = (Editor) itemElementFactory.createElement( item, getForm(), false); item.setEditor(editor); container.addElement(item); item.setValue(value, newItem); return item; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addItem"
"protected ListItem addItem(Object value, boolean newItem) { ListItem item = createItem(); Editor editor = (Editor) itemElementFactory.createElement( item, getForm(), false); item.setEditor(editor); item.setValue(value, newItem); <MASK>container.addElement(item);</MASK> return item; }"
Inversion-Mutation
megadiff
"public static Date parse(String date, List<String> formats) { Date result = null; if (date == null) { throw new IllegalArgumentException("Date is null"); } String format = null; int formatsSize = formats.size(); for (int i = 0; (result == null) && (i < formatsSize); i++) { format = formats.get(i); // [ifndef gwt] java.text.DateFormat parser = null; if (FORMAT_RFC_3339.get(0).equals(format)) { parser = new InternetDateFormat(TIMEZONE_GMT); } else { parser = new java.text.SimpleDateFormat(format, java.util.Locale.US); parser.setTimeZone(TIMEZONE_GMT); } // [enddef] // [ifdef gwt] /* * GWT difference: DateTimeFormat parser is is not passed a Locale * in the same way as SimpleDateFormat. It derives locale * information from the GWT application's locale. * * Default timezone is GMT unless specified via a GMT:hhmm, * GMT:+hhmm, or GMT:-hhmm string. */ // [enddef] // [ifdef gwt] uncomment // final com.google.gwt.i18n.client.DateTimeFormat parser = // com.google.gwt.i18n.client.DateTimeFormat.getFormat(format); // [enddef] try { result = parser.parse(date); } catch (Exception e) { // Ignores error as the next format may work better } } return result; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parse"
"public static Date parse(String date, List<String> formats) { Date result = null; if (date == null) { throw new IllegalArgumentException("Date is null"); } String format = null; int formatsSize = formats.size(); for (int i = 0; (result == null) && (i < formatsSize); i++) { // [ifndef gwt] java.text.DateFormat parser = null; <MASK>format = formats.get(i);</MASK> if (FORMAT_RFC_3339.get(0).equals(format)) { parser = new InternetDateFormat(TIMEZONE_GMT); } else { parser = new java.text.SimpleDateFormat(format, java.util.Locale.US); parser.setTimeZone(TIMEZONE_GMT); } // [enddef] // [ifdef gwt] /* * GWT difference: DateTimeFormat parser is is not passed a Locale * in the same way as SimpleDateFormat. It derives locale * information from the GWT application's locale. * * Default timezone is GMT unless specified via a GMT:hhmm, * GMT:+hhmm, or GMT:-hhmm string. */ // [enddef] // [ifdef gwt] uncomment // final com.google.gwt.i18n.client.DateTimeFormat parser = // com.google.gwt.i18n.client.DateTimeFormat.getFormat(format); // [enddef] try { result = parser.parse(date); } catch (Exception e) { // Ignores error as the next format may work better } } return result; }"
Inversion-Mutation
megadiff
"@Override public void run() { Thread.currentThread().setName("JobRunner-" + this.jobId + "-" + executionId); // If the job is cancelled, disabled, killed. No log is created in this case if (handleNonReadyStatus()) { return; } createAttachmentFile(); createLogger(); boolean errorFound = false; // Delay execution if necessary. Will return a true if something went wrong. errorFound |= delayExecution(); // For pipelining of jobs. Will watch other jobs. Will return true if // something went wrong. errorFound |= blockOnPipeLine(); // Start the node. node.setStartTime(System.currentTimeMillis()); if (!errorFound && !isKilled()) { fireEvent(Event.create(this, Type.JOB_STARTED, null, false)); try { loader.uploadExecutableNode(node, props); } catch (ExecutorManagerException e1) { logger.error("Error writing initial node properties"); } if (prepareJob()) { // Writes status to the db writeStatus(); fireEvent(Event.create(this, Type.JOB_STATUS_CHANGED), false); runJob(); } else { changeStatus(Status.FAILED); logError("Job run failed preparing the job."); } } node.setEndTime(System.currentTimeMillis()); if (isKilled()) { changeStatus(Status.KILLED); } logInfo("Finishing job " + this.jobId + " at " + node.getEndTime() + " with status " + node.getStatus()); fireEvent(Event.create(this, Type.JOB_FINISHED), false); finalizeLogFile(); finalizeAttachmentFile(); writeStatus(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"@Override public void run() { Thread.currentThread().setName("JobRunner-" + this.jobId + "-" + executionId); // If the job is cancelled, disabled, killed. No log is created in this case if (handleNonReadyStatus()) { return; } createAttachmentFile(); createLogger(); boolean errorFound = false; // Delay execution if necessary. Will return a true if something went wrong. errorFound |= delayExecution(); // For pipelining of jobs. Will watch other jobs. Will return true if // something went wrong. errorFound |= blockOnPipeLine(); // Start the node. node.setStartTime(System.currentTimeMillis()); if (!errorFound && !isKilled()) { fireEvent(Event.create(this, Type.JOB_STARTED, null, false)); try { loader.uploadExecutableNode(node, props); } catch (ExecutorManagerException e1) { logger.error("Error writing initial node properties"); } if (prepareJob()) { // Writes status to the db <MASK>writeStatus();</MASK> fireEvent(Event.create(this, Type.JOB_STATUS_CHANGED), false); runJob(); <MASK>writeStatus();</MASK> } else { changeStatus(Status.FAILED); logError("Job run failed preparing the job."); } } node.setEndTime(System.currentTimeMillis()); if (isKilled()) { changeStatus(Status.KILLED); } logInfo("Finishing job " + this.jobId + " at " + node.getEndTime() + " with status " + node.getStatus()); fireEvent(Event.create(this, Type.JOB_FINISHED), false); finalizeLogFile(); finalizeAttachmentFile(); }"
Inversion-Mutation
megadiff
"public void resumeGame() { gamestate = GameState.RUNNING; stateManager.attach(gameInputAppState); bulletAppState.setEnabled(true); startInputSender(); menuController.actualizeScreen(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "resumeGame"
"public void resumeGame() { gamestate = GameState.RUNNING; <MASK>menuController.actualizeScreen();</MASK> stateManager.attach(gameInputAppState); bulletAppState.setEnabled(true); startInputSender(); }"
Inversion-Mutation
megadiff
"public void onDiceRolled() { // play possible animations/sound here state.activeSelection().roll(); state.rollHistory().add(0, new SetSelection(state.activeSelection())); if (state.rollHistory().size() > 20) state.rollHistory().remove(20); statistics.update(); mViewPager.setCurrentItem(2); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onDiceRolled"
"public void onDiceRolled() { // play possible animations/sound here state.rollHistory().add(0, new SetSelection(state.activeSelection())); if (state.rollHistory().size() > 20) state.rollHistory().remove(20); <MASK>state.activeSelection().roll();</MASK> statistics.update(); mViewPager.setCurrentItem(2); }"
Inversion-Mutation
megadiff
"public void load(Element parent, ICharacter character) throws PersistenceException { try { Element statisticsElement = parent.element(TAG_STATISTICS); if (statisticsElement == null) { return; } ITemplateType templateType = loadTemplateType(statisticsElement); boolean experienced = ElementUtilities.getBooleanAttribute(statisticsElement, ATTRIB_EXPERIENCED, false); IExaltedRuleSet rules = rulesPersister.load(statisticsElement); ICharacterTemplate template = generics.getTemplateRegistry().getTemplate(templateType, rules.getEdition()); ICharacterStatistics statistics = character.createCharacterStatistics(template, generics, rules); ICasteCollection casteCollection = template.getCasteCollection(); characterConceptPersister.load(statisticsElement, statistics.getCharacterConcept(), casteCollection); statistics.setExperienced(experienced); essencePersister.load(statisticsElement, statistics.getTraitConfiguration()); IAdditionalModel virtueFlawModel = statistics.getExtendedConfiguration().getAdditionalModel( IAdditionalTemplate.SOLAR_VIRTUE_FLAW_ID); virtuePersister.load(statisticsElement, statistics.getTraitConfiguration(), virtueFlawModel); attributePersister.load(statisticsElement, statistics.getTraitConfiguration()); abilityPersister.load(statisticsElement, statistics.getTraitConfiguration()); backgroundPersister.load(statisticsElement, statistics.getTraitConfiguration().getBackgrounds()); charmPersister.load(statisticsElement, statistics); spellPersister.load(statisticsElement, statistics.getSpells()); experiencePersister.load(statisticsElement, statistics.getExperiencePoints()); willpowerPersister.load(statisticsElement, statistics.getTraitConfiguration().getTrait(OtherTraitType.Willpower)); additonalModelPersister.load(statisticsElement, statistics.getExtendedConfiguration().getAdditionalModels()); } catch (CharmException e) { throw new PersistenceException(e); } catch (SpellException e) { throw new PersistenceException(e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "load"
"public void load(Element parent, ICharacter character) throws PersistenceException { try { Element statisticsElement = parent.element(TAG_STATISTICS); if (statisticsElement == null) { return; } ITemplateType templateType = loadTemplateType(statisticsElement); boolean experienced = ElementUtilities.getBooleanAttribute(statisticsElement, ATTRIB_EXPERIENCED, false); IExaltedRuleSet rules = rulesPersister.load(statisticsElement); ICharacterTemplate template = generics.getTemplateRegistry().getTemplate(templateType, rules.getEdition()); ICharacterStatistics statistics = character.createCharacterStatistics(template, generics, rules); ICasteCollection casteCollection = template.getCasteCollection(); characterConceptPersister.load(statisticsElement, statistics.getCharacterConcept(), casteCollection); essencePersister.load(statisticsElement, statistics.getTraitConfiguration()); IAdditionalModel virtueFlawModel = statistics.getExtendedConfiguration().getAdditionalModel( IAdditionalTemplate.SOLAR_VIRTUE_FLAW_ID); virtuePersister.load(statisticsElement, statistics.getTraitConfiguration(), virtueFlawModel); attributePersister.load(statisticsElement, statistics.getTraitConfiguration()); abilityPersister.load(statisticsElement, statistics.getTraitConfiguration()); backgroundPersister.load(statisticsElement, statistics.getTraitConfiguration().getBackgrounds()); charmPersister.load(statisticsElement, statistics); spellPersister.load(statisticsElement, statistics.getSpells()); experiencePersister.load(statisticsElement, statistics.getExperiencePoints()); <MASK>statistics.setExperienced(experienced);</MASK> willpowerPersister.load(statisticsElement, statistics.getTraitConfiguration().getTrait(OtherTraitType.Willpower)); additonalModelPersister.load(statisticsElement, statistics.getExtendedConfiguration().getAdditionalModels()); } catch (CharmException e) { throw new PersistenceException(e); } catch (SpellException e) { throw new PersistenceException(e); } }"
Inversion-Mutation
megadiff
"public DialogAdd(final GUI main) { super(main, GUIADD); final BaseXBack pp = new BaseXBack(new TableLayout(7, 2, 0, 4)); pp.add(new BaseXLabel(CREATETITLE)); pp.add(new BaseXLabel(" ")); file = new BaseXTextField(this); pp.add(file); final BaseXButton browse = new BaseXButton(BUTTONBROWSE, this); browse.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { choose(); } }); pp.add(browse); pp.add(new BaseXLabel("Name: ")); pp.add(new BaseXLabel(" ")); name = new BaseXTextField(this); name.addKeyListener(keys); pp.add(name); pp.add(new BaseXLabel(" ")); pp.add(new BaseXLabel("Target Path: ")); pp.add(new BaseXLabel(" ")); path = new BaseXTextField(this); path.addKeyListener(keys); pp.add(path); set(pp, BorderLayout.CENTER); // create buttons BaseXBack p = new BaseXBack(new BorderLayout()); info = new BaseXLabel(" ").border(18, 0, 0, 0); p.add(info, BorderLayout.WEST); buttons = okCancel(this); p.add(buttons, BorderLayout.EAST); set(p, BorderLayout.SOUTH); action(null); finish(null); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "DialogAdd"
"public DialogAdd(final GUI main) { super(main, GUIADD); final BaseXBack pp = new BaseXBack(new TableLayout(7, 2, 0, 4)); pp.add(new BaseXLabel(CREATETITLE)); <MASK>pp.add(new BaseXLabel(" "));</MASK> file = new BaseXTextField(this); pp.add(file); final BaseXButton browse = new BaseXButton(BUTTONBROWSE, this); browse.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { choose(); } }); pp.add(browse); pp.add(new BaseXLabel("Name: ")); <MASK>pp.add(new BaseXLabel(" "));</MASK> name = new BaseXTextField(this); name.addKeyListener(keys); pp.add(name); pp.add(new BaseXLabel("Target Path: ")); <MASK>pp.add(new BaseXLabel(" "));</MASK> path = new BaseXTextField(this); path.addKeyListener(keys); pp.add(path); <MASK>pp.add(new BaseXLabel(" "));</MASK> set(pp, BorderLayout.CENTER); // create buttons BaseXBack p = new BaseXBack(new BorderLayout()); info = new BaseXLabel(" ").border(18, 0, 0, 0); p.add(info, BorderLayout.WEST); buttons = okCancel(this); p.add(buttons, BorderLayout.EAST); set(p, BorderLayout.SOUTH); action(null); finish(null); }"
Inversion-Mutation
megadiff
"public PortShop(NewWindowManager parent,PortEntity pe) { super(parent); parent.add(this); setSize(500, 250); setLoc(390, 275); setText("Port Shop"); port = pe; initItems(); current = null; if(port == null){ super.setVisible(false); } else{ super.setVisible(true); current = ((NavalManager)port.getManager()).getGame().getTurnManager().findPlayer(pe); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "PortShop"
"public PortShop(NewWindowManager parent,PortEntity pe) { super(parent); parent.add(this); setSize(500, 250); setLoc(390, 275); setText("Port Shop"); initItems(); <MASK>port = pe;</MASK> current = null; if(port == null){ super.setVisible(false); } else{ super.setVisible(true); current = ((NavalManager)port.getManager()).getGame().getTurnManager().findPlayer(pe); } }"
Inversion-Mutation
megadiff
"public boolean contains(float x, float y) { checkPoints(); if (points.length == 0) { return false; } boolean result = false; float xnew,ynew; float xold,yold; float x1,y1; float x2,y2; int npoints = points.length; xold=points[npoints - 2]; yold=points[npoints - 1]; for (int i=0;i < npoints;i+=2) { xnew = points[i]; ynew = points[i + 1]; if (xnew > xold) { x1 = xold; x2 = xnew; y1 = yold; y2 = ynew; } else { x1 = xnew; x2 = xold; y1 = ynew; y2 = yold; } if ((xnew < x) == (x <= xold) /* edge "open" at one end */ && ((double)y - (double)y1) * (x2 - x1) < ((double)y2 - (double)y1) * (x - x1)) { result = !result; } xold = xnew; yold = ynew; } return result; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "contains"
"public boolean contains(float x, float y) { if (points.length == 0) { return false; } <MASK>checkPoints();</MASK> boolean result = false; float xnew,ynew; float xold,yold; float x1,y1; float x2,y2; int npoints = points.length; xold=points[npoints - 2]; yold=points[npoints - 1]; for (int i=0;i < npoints;i+=2) { xnew = points[i]; ynew = points[i + 1]; if (xnew > xold) { x1 = xold; x2 = xnew; y1 = yold; y2 = ynew; } else { x1 = xnew; x2 = xold; y1 = ynew; y2 = yold; } if ((xnew < x) == (x <= xold) /* edge "open" at one end */ && ((double)y - (double)y1) * (x2 - x1) < ((double)y2 - (double)y1) * (x - x1)) { result = !result; } xold = xnew; yold = ynew; } return result; }"
Inversion-Mutation
megadiff
"public TMIClient(final String channelName, final String accountName, final String accountPassword) { this.channelName = channelName; this.accountName = accountName; this.accountPassword = accountPassword; setupHandlers(); ops = new HashSet<User>(); connection = new Connection(Twitch.getAddressForChannel(channelName), Twitch.CHAT_PORT); connection.setConnectionListener(this); connection.connect(); connection.setInactivityTimeLimit(45 * 60 * 1000); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "TMIClient"
"public TMIClient(final String channelName, final String accountName, final String accountPassword) { this.channelName = channelName; this.accountName = accountName; this.accountPassword = accountPassword; setupHandlers(); ops = new HashSet<User>(); connection = new Connection(Twitch.getAddressForChannel(channelName), Twitch.CHAT_PORT); connection.setConnectionListener(this); <MASK>connection.setInactivityTimeLimit(45 * 60 * 1000);</MASK> connection.connect(); }"
Inversion-Mutation
megadiff
"@Override protected void onResume() { super.onResume(); mWifiEnabler.resume(); mBtEnabler.resume(); mAirplaneModeEnabler.resume(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onResume"
"@Override protected void onResume() { super.onResume(); mWifiEnabler.resume(); <MASK>mAirplaneModeEnabler.resume();</MASK> mBtEnabler.resume(); }"
Inversion-Mutation
megadiff
"public StarTable[] makeStarTables( DataSource datsrc, StoragePolicy storagePolicy) throws IOException { /* If there is a position, use makeStarTable. Otherwise, we want * all the tables. */ String srcpos = datsrc.getPosition(); if ( srcpos != null && srcpos.trim().length() > 0 ) { return new StarTable[] { makeStarTable( datsrc, false, storagePolicy ) }; } /* See if this looks like a fits-plus table. */ if ( ! isMagic( datsrc.getIntro() ) ) { throw new TableFormatException( "Doesn't look like a FITS-plus file" ); } /* Get an input stream. */ ArrayDataInput in = FitsConstants.getInputStreamStart( datsrc ); try { /* Read the metadata from the primary HDU. */ long[] posptr = new long[ 1 ]; TableElement[] tabEls = readMetadata( in, posptr ); long pos = posptr[ 0 ]; int nTable = tabEls.length; StarTable[] outTables = new StarTable[ nTable ]; /* Read each table HDU in turn. */ for ( int itab = 0; itab < nTable; itab++ ) { /* Make sure we have a usable stream positioned at the start * of the right HDU. */ if ( in == null ) { in = FitsConstants.getInputStreamStart( datsrc ); if ( pos > 0 ) { if ( in instanceof RandomAccess ) { ((RandomAccess) in).seek( pos ); } else { IOUtils.skipBytes( in, pos ); } } } /* Read the HDU header. */ Header hdr = new Header(); int headsize = FitsConstants.readHeader( hdr, in ); long datasize = FitsConstants.getDataSize( hdr ); long datpos = pos + headsize; if ( ! "BINTABLE".equals( hdr.getStringValue( "XTENSION" ) ) ) { throw new TableFormatException( "Non-BINTABLE at ext #" + itab + " - not FITS-plus" ); } /* Read the BINTABLE. */ final StarTable dataTable; if ( in instanceof RandomAccess ) { dataTable = BintableStarTable .makeRandomStarTable( hdr, (RandomAccess) in ); } else { dataTable = BintableStarTable .makeSequentialStarTable( hdr, datsrc, datpos ); in = null; } /* Combine the data from the BINTABLE with the header from * the VOTable to create an output table. */ outTables[ itab ] = createFitsPlusTable( tabEls[ itab ], dataTable ); pos += headsize + datasize; } return outTables; } catch ( FitsException e ) { throw new TableFormatException( e.getMessage(), e ); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "makeStarTables"
"public StarTable[] makeStarTables( DataSource datsrc, StoragePolicy storagePolicy) throws IOException { /* If there is a position, use makeStarTable. Otherwise, we want * all the tables. */ String srcpos = datsrc.getPosition(); if ( srcpos != null && srcpos.trim().length() > 0 ) { return new StarTable[] { makeStarTable( datsrc, false, storagePolicy ) }; } /* See if this looks like a fits-plus table. */ if ( ! isMagic( datsrc.getIntro() ) ) { throw new TableFormatException( "Doesn't look like a FITS-plus file" ); } /* Get an input stream. */ ArrayDataInput in = FitsConstants.getInputStreamStart( datsrc ); try { /* Read the metadata from the primary HDU. */ long[] posptr = new long[ 1 ]; TableElement[] tabEls = readMetadata( in, posptr ); long pos = posptr[ 0 ]; int nTable = tabEls.length; StarTable[] outTables = new StarTable[ nTable ]; /* Read each table HDU in turn. */ for ( int itab = 0; itab < nTable; itab++ ) { /* Make sure we have a usable stream positioned at the start * of the right HDU. */ if ( in == null ) { in = FitsConstants.getInputStreamStart( datsrc ); if ( pos > 0 ) { if ( in instanceof RandomAccess ) { ((RandomAccess) in).seek( pos ); } else { IOUtils.skipBytes( in, pos ); } } } /* Read the HDU header. */ Header hdr = new Header(); int headsize = FitsConstants.readHeader( hdr, in ); long datasize = FitsConstants.getDataSize( hdr ); long datpos = pos + headsize; if ( ! "BINTABLE".equals( hdr.getStringValue( "XTENSION" ) ) ) { throw new TableFormatException( "Non-BINTABLE at ext #" + itab + " - not FITS-plus" ); } /* Read the BINTABLE. */ final StarTable dataTable; if ( in instanceof RandomAccess ) { dataTable = BintableStarTable .makeRandomStarTable( hdr, (RandomAccess) in ); <MASK>in = null;</MASK> } else { dataTable = BintableStarTable .makeSequentialStarTable( hdr, datsrc, datpos ); } /* Combine the data from the BINTABLE with the header from * the VOTable to create an output table. */ outTables[ itab ] = createFitsPlusTable( tabEls[ itab ], dataTable ); pos += headsize + datasize; } return outTables; } catch ( FitsException e ) { throw new TableFormatException( e.getMessage(), e ); } }"
Inversion-Mutation
megadiff
"public void close(){ IStreamService streamService = (IStreamService) getScopeService(scope, IStreamService.STREAM_SERVICE, StreamService.class); if (streamService != null) { synchronized (streams) { for(int i=0; i<streams.length; i++){ IClientStream stream = streams[i]; if(stream != null) { log.debug("Closing stream: "+ stream.getStreamId()); streamService.deleteStream(this, stream.getStreamId()); streams[i] = null; } } } } IFlowControlService fcs = (IFlowControlService) getScope().getContext().getBean( IFlowControlService.KEY); fcs.unregisterFlowControllable(this); super.close(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "close"
"public void close(){ IStreamService streamService = (IStreamService) getScopeService(scope, IStreamService.STREAM_SERVICE, StreamService.class); if (streamService != null) { synchronized (streams) { for(int i=0; i<streams.length; i++){ IClientStream stream = streams[i]; if(stream != null) { log.debug("Closing stream: "+ stream.getStreamId()); streamService.deleteStream(this, stream.getStreamId()); streams[i] = null; } } } } <MASK>super.close();</MASK> IFlowControlService fcs = (IFlowControlService) getScope().getContext().getBean( IFlowControlService.KEY); fcs.unregisterFlowControllable(this); }"
Inversion-Mutation
megadiff
"private FloorState[] initializeFloorStates(ElevatorGame game, Integer floorNb) { final FloorState[] floorStates = new FloorState[floorNb]; for (Integer floor = LOWER_FLOOR; floor <= HIGHER_FLOOR; floor++) { // FIXME things goes wrong if LOWER_FLOOR is not zero floorStates[floor] = new FloorState(floor, game.waitingUsersByFloors()[floor], floorsWhereUpButtonIsLit.contains(floor), floorsWhereDownButtonIsLit.contains(floor), game.getFloorButtonStatesInElevator()[floor]); } return floorStates; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initializeFloorStates"
"private FloorState[] initializeFloorStates(ElevatorGame game, Integer floorNb) { final FloorState[] floorStates = new FloorState[floorNb]; for (Integer floor = LOWER_FLOOR; floor <= HIGHER_FLOOR; floor++) { // FIXME things goes wrong if LOWER_FLOOR is not zero floorStates[floor] = new FloorState(floor, game.waitingUsersByFloors()[floor], <MASK>floorsWhereDownButtonIsLit.contains(floor),</MASK> floorsWhereUpButtonIsLit.contains(floor), game.getFloorButtonStatesInElevator()[floor]); } return floorStates; }"
Inversion-Mutation
megadiff
"@Override public void Act() { if (Input.IsActive(Commands.Start, _parent.GetPlayerIndex())) { _parent.SetPlaying(true); } if (Input.IsActive(Commands.Back, _parent.GetPlayerIndex())) { _parent.SetPlaying(false); } if (_parent.IsPlaying()) { if (!Input.IsContext(Contexts.Inventory, _parent.GetPlayerIndex())) { float leftVelocity = (Input.IsActive(Commands.MoveLeft, _parent.GetPlayerIndex()) ? -Stats.DefaultMoveDistance : 0); float rightVelocity = ((Input.IsActive(Commands.MoveRight, _parent.GetPlayerIndex())) ? Stats.DefaultMoveDistance : 0); _keyVelocity.SetX(rightVelocity + leftVelocity); float downVelocity = ((Input.IsActive(Commands.MoveDown, _parent.GetPlayerIndex())) ? -Stats.DefaultMoveDistance : 0); float upVelocity = ((Input.IsActive(Commands.MoveUp, _parent.GetPlayerIndex())) ? Stats.DefaultMoveDistance : 0); _keyVelocity.SetY(upVelocity + downVelocity); if (Input.IsContext(Contexts.Free, _parent.GetPlayerIndex())) { boolean isPress = Input.IsActive(Commands.Confirm, _parent.GetPlayerIndex()); if (!isPress) { _parent.SetInteraction(false); } if (isPress && !_parent.IsInteracting()) { _parent.SetInteraction(true); } int skillCycleVelocity = ((Input.IsActive(Commands.CycleLeft, _parent.GetPlayerIndex())) ? -1 : 0) + ((Input.IsActive(Commands.CycleRight, _parent.GetPlayerIndex())) ? 1 : 0); _parent.CycleActiveSkill(skillCycleVelocity); if (!_isCasting) { if (!Input.IsActive(Commands.Confirm, _parent.GetPlayerIndex(), false)) { _parent.MoveIfPossible(_keyVelocity.X, _keyVelocity.Y); } if (!_keyVelocity.IsZero()) { _parent.SetSkillVector(_keyVelocity); } } } if (Input.IsActive(Commands.Skill, _parent.GetPlayerIndex())) { _isCasting = true; } for (Commands hotkey : __hotkeys) { if (Input.IsActive(hotkey, _parent.GetPlayerIndex())) { if (!Input.IsActive(Commands.LockSkill, _parent.GetPlayerIndex(), false)) { if (_parent.SetHotSkillActive(hotkey)) { _isCasting = true; } } else { _parent.MarkHotSkill(hotkey); } } } if (_isCasting) { if (_parent.GetSkillVector() == null) { _parent.SetSkillVector(new Point2(1, 0)); } if (!_parent.GetSkillVector().IsZero()) { _parent.UseActiveSkill(); } _isCasting = false; } } if (Input.IsActive(Commands.Inventory, _parent.GetPlayerIndex())) { Input.SetContext(_parent.ToggleInventoryVisibility() ? Contexts.Inventory : Contexts.Free, _parent.GetPlayerIndex()); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Act"
"@Override public void Act() { if (Input.IsActive(Commands.Start, _parent.GetPlayerIndex())) { _parent.SetPlaying(true); } if (Input.IsActive(Commands.Back, _parent.GetPlayerIndex())) { _parent.SetPlaying(false); } if (_parent.IsPlaying()) { if (!Input.IsContext(Contexts.Inventory, _parent.GetPlayerIndex())) { float leftVelocity = (Input.IsActive(Commands.MoveLeft, _parent.GetPlayerIndex()) ? -Stats.DefaultMoveDistance : 0); float rightVelocity = ((Input.IsActive(Commands.MoveRight, _parent.GetPlayerIndex())) ? Stats.DefaultMoveDistance : 0); _keyVelocity.SetX(rightVelocity + leftVelocity); float downVelocity = ((Input.IsActive(Commands.MoveDown, _parent.GetPlayerIndex())) ? -Stats.DefaultMoveDistance : 0); float upVelocity = ((Input.IsActive(Commands.MoveUp, _parent.GetPlayerIndex())) ? Stats.DefaultMoveDistance : 0); _keyVelocity.SetY(upVelocity + downVelocity); if (Input.IsContext(Contexts.Free, _parent.GetPlayerIndex())) { boolean isPress = Input.IsActive(Commands.Confirm, _parent.GetPlayerIndex()); if (!isPress) { _parent.SetInteraction(false); } if (isPress && !_parent.IsInteracting()) { _parent.SetInteraction(true); } int skillCycleVelocity = ((Input.IsActive(Commands.CycleLeft, _parent.GetPlayerIndex())) ? -1 : 0) + ((Input.IsActive(Commands.CycleRight, _parent.GetPlayerIndex())) ? 1 : 0); _parent.CycleActiveSkill(skillCycleVelocity); if (!_isCasting) { if (!Input.IsActive(Commands.Confirm, _parent.GetPlayerIndex(), false)) { _parent.MoveIfPossible(_keyVelocity.X, _keyVelocity.Y); } if (!_keyVelocity.IsZero()) { _parent.SetSkillVector(_keyVelocity); } } } if (Input.IsActive(Commands.Skill, _parent.GetPlayerIndex())) { _isCasting = true; } for (Commands hotkey : __hotkeys) { if (Input.IsActive(hotkey, _parent.GetPlayerIndex())) { if (!Input.IsActive(Commands.LockSkill, _parent.GetPlayerIndex(), false)) { if (_parent.SetHotSkillActive(hotkey)) { _isCasting = true; } } else { _parent.MarkHotSkill(hotkey); } } } if (_isCasting) { if (_parent.GetSkillVector() == null) { _parent.SetSkillVector(new Point2(1, 0)); } if (!_parent.GetSkillVector().IsZero()) { _parent.UseActiveSkill(); <MASK>_isCasting = false;</MASK> } } } if (Input.IsActive(Commands.Inventory, _parent.GetPlayerIndex())) { Input.SetContext(_parent.ToggleInventoryVisibility() ? Contexts.Inventory : Contexts.Free, _parent.GetPlayerIndex()); } } }"
Inversion-Mutation
megadiff
"@EventHandler public void onPlayerHitSign(PlayerInteractEvent event) { if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { Block b = event.getClickedBlock(); if (b.getType().equals(Material.SIGN) || b.getType().equals(Material.SIGN_POST) || b.getType().equals(Material.WALL_SIGN)) { //It's a sign Sign s = (Sign) b.getState(); if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { if (sortalSign(s, event.getPlayer())) { event.setCancelled(true); } return; } int found = -1; for (int i = 0; i < s.getLines().length; i++) { if (s.getLine(i).toLowerCase().contains("[sortal]") || s.getLine(i).toLowerCase().contains(this.getPlugin().getSettings().getSignContains())) { //It's a sortal sign found = i; break; } } if (found == -1) { if (!this.getPlugin().getWarpManager().isSortalSign(s.getLocation())) { return; //nvm it's not a sortal sign of any kind. } if (!event.getPlayer().hasPermission("sortal.warp")) { event.getPlayer().sendMessage(this.getLocalisation().getNoPerms()); event.setCancelled(true); return; } SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation()); if (sign.hasWarp()) { if (!this.getPlugin().pay(event.getPlayer(), sign.getPrice())) { event.setCancelled(true); return; } Warp w = this.getPlugin().getWarpManager().getWarp(sign.getWarp()); event.getPlayer().teleport(w.getLocation(), TeleportCause.PLUGIN); event.getPlayer().sendMessage(this.getLocalisation().getPlayerTeleported(w.getName())); event.setCancelled(true); //Cancel, don't place block. return; } event.getPlayer().sendMessage(this.getLocalisation().getErrorInSign()); //Sign does have a price but no warp -> weird. event.setCancelled(true); return; //have to return, otherwise it'll check the next lines } if (!event.getPlayer().hasPermission("sortal.warp")) { event.getPlayer().sendMessage(this.getLocalisation().getNoPerms()); event.setCancelled(true); return; } String nextLine = s.getLine(found + 1); if (nextLine == null || nextLine.equals("")) { //Well, that didn't really work out well.. event.getPlayer().sendMessage(this.getLocalisation().getErrorInSign()); event.setCancelled(true); return; } if (nextLine.contains("w:")) { //It's a warp String warp = nextLine.split(":")[1]; if (!this.getPlugin().getWarpManager().hasWarp(warp)) { event.getPlayer().sendMessage(this.getLocalisation().getWarpNotFound(warp)); event.setCancelled(true); return; } Warp w = this.getPlugin().getWarpManager().getWarp(warp); int price = w.getPrice(); if(this.getPlugin().getWarpManager().isSortalSign(s.getLocation())){ price = this.getPlugin().getWarpManager().getSign(s.getLocation()).getPrice(); } if (!this.getPlugin().pay(event.getPlayer(), price)) { event.setCancelled(true); return; } event.getPlayer().teleport(w.getLocation(), TeleportCause.PLUGIN); event.getPlayer().sendMessage(this.getLocalisation().getPlayerTeleported(warp)); event.setCancelled(true); return; } if (nextLine.contains(",")) { String[] split = nextLine.split(","); World w; int add = 0; if (split.length == 3) { w = event.getPlayer().getWorld(); } else { w = this.getPlugin().getServer().getWorld(split[0]); if (w == null) { event.getPlayer().sendMessage(this.getLocalisation().getErrorInSign()); event.setCancelled(true); return; } add = 1; } int price = this.getPlugin().getSettings().getWarpUsePrice(); if(this.getPlugin().getWarpManager().isSortalSign(s.getLocation())){ price = this.getPlugin().getWarpManager().getSign(s.getLocation()).getPrice(); } if(!this.getPlugin().pay(event.getPlayer(), price)){ event.setCancelled(true); return; } int x = Integer.parseInt(split[0 + add]), y = Integer.parseInt(split[1 + add]), z = Integer.parseInt(split[2 + add]); Location dest = new Location(w, x, y, z, event.getPlayer().getLocation().getYaw(), event.getPlayer().getLocation().getPitch()); event.getPlayer().teleport(dest, TeleportCause.PLUGIN); event.getPlayer().sendMessage(this.getLocalisation().getPlayerTeleported( dest.getBlockX() + ", " + dest.getBlockY() + ", " + dest.getBlockZ())); event.setCancelled(true); return; } event.getPlayer().sendMessage(this.getLocalisation().getErrorInSign()); event.setCancelled(true); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPlayerHitSign"
"@EventHandler public void onPlayerHitSign(PlayerInteractEvent event) { if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { Block b = event.getClickedBlock(); if (b.getType().equals(Material.SIGN) || b.getType().equals(Material.SIGN_POST) || b.getType().equals(Material.WALL_SIGN)) { //It's a sign Sign s = (Sign) b.getState(); if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { if (sortalSign(s, event.getPlayer())) { event.setCancelled(true); <MASK>return;</MASK> } } int found = -1; for (int i = 0; i < s.getLines().length; i++) { if (s.getLine(i).toLowerCase().contains("[sortal]") || s.getLine(i).toLowerCase().contains(this.getPlugin().getSettings().getSignContains())) { //It's a sortal sign found = i; break; } } if (found == -1) { if (!this.getPlugin().getWarpManager().isSortalSign(s.getLocation())) { <MASK>return;</MASK> //nvm it's not a sortal sign of any kind. } if (!event.getPlayer().hasPermission("sortal.warp")) { event.getPlayer().sendMessage(this.getLocalisation().getNoPerms()); event.setCancelled(true); <MASK>return;</MASK> } SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation()); if (sign.hasWarp()) { if (!this.getPlugin().pay(event.getPlayer(), sign.getPrice())) { event.setCancelled(true); <MASK>return;</MASK> } Warp w = this.getPlugin().getWarpManager().getWarp(sign.getWarp()); event.getPlayer().teleport(w.getLocation(), TeleportCause.PLUGIN); event.getPlayer().sendMessage(this.getLocalisation().getPlayerTeleported(w.getName())); event.setCancelled(true); //Cancel, don't place block. <MASK>return;</MASK> } event.getPlayer().sendMessage(this.getLocalisation().getErrorInSign()); //Sign does have a price but no warp -> weird. event.setCancelled(true); <MASK>return;</MASK> //have to return, otherwise it'll check the next lines } if (!event.getPlayer().hasPermission("sortal.warp")) { event.getPlayer().sendMessage(this.getLocalisation().getNoPerms()); event.setCancelled(true); <MASK>return;</MASK> } String nextLine = s.getLine(found + 1); if (nextLine == null || nextLine.equals("")) { //Well, that didn't really work out well.. event.getPlayer().sendMessage(this.getLocalisation().getErrorInSign()); event.setCancelled(true); <MASK>return;</MASK> } if (nextLine.contains("w:")) { //It's a warp String warp = nextLine.split(":")[1]; if (!this.getPlugin().getWarpManager().hasWarp(warp)) { event.getPlayer().sendMessage(this.getLocalisation().getWarpNotFound(warp)); event.setCancelled(true); <MASK>return;</MASK> } Warp w = this.getPlugin().getWarpManager().getWarp(warp); int price = w.getPrice(); if(this.getPlugin().getWarpManager().isSortalSign(s.getLocation())){ price = this.getPlugin().getWarpManager().getSign(s.getLocation()).getPrice(); } if (!this.getPlugin().pay(event.getPlayer(), price)) { event.setCancelled(true); <MASK>return;</MASK> } event.getPlayer().teleport(w.getLocation(), TeleportCause.PLUGIN); event.getPlayer().sendMessage(this.getLocalisation().getPlayerTeleported(warp)); event.setCancelled(true); <MASK>return;</MASK> } if (nextLine.contains(",")) { String[] split = nextLine.split(","); World w; int add = 0; if (split.length == 3) { w = event.getPlayer().getWorld(); } else { w = this.getPlugin().getServer().getWorld(split[0]); if (w == null) { event.getPlayer().sendMessage(this.getLocalisation().getErrorInSign()); event.setCancelled(true); <MASK>return;</MASK> } add = 1; } int price = this.getPlugin().getSettings().getWarpUsePrice(); if(this.getPlugin().getWarpManager().isSortalSign(s.getLocation())){ price = this.getPlugin().getWarpManager().getSign(s.getLocation()).getPrice(); } if(!this.getPlugin().pay(event.getPlayer(), price)){ event.setCancelled(true); <MASK>return;</MASK> } int x = Integer.parseInt(split[0 + add]), y = Integer.parseInt(split[1 + add]), z = Integer.parseInt(split[2 + add]); Location dest = new Location(w, x, y, z, event.getPlayer().getLocation().getYaw(), event.getPlayer().getLocation().getPitch()); event.getPlayer().teleport(dest, TeleportCause.PLUGIN); event.getPlayer().sendMessage(this.getLocalisation().getPlayerTeleported( dest.getBlockX() + ", " + dest.getBlockY() + ", " + dest.getBlockZ())); event.setCancelled(true); <MASK>return;</MASK> } event.getPlayer().sendMessage(this.getLocalisation().getErrorInSign()); event.setCancelled(true); } } }"
Inversion-Mutation
megadiff
"public void test() throws Exception { testTransaction(false); testCreateDrop(); if (config.memory) { return; } testMultiThreaded(); testStreamLob(); test(false, "VARCHAR"); test(false, "CLOB"); testPerformance(false); testReopen(false); String luceneFullTextClassName = "org.h2.fulltext.FullTextLucene"; try { Class.forName(luceneFullTextClassName); testTransaction(true); test(true, "VARCHAR"); test(true, "CLOB"); testPerformance(true); testReopen(true); } catch (ClassNotFoundException e) { println("Class not found, not tested: " + luceneFullTextClassName); // ok } catch (NoClassDefFoundError e) { println("Class not found, not tested: " + luceneFullTextClassName); // ok } FullText.closeAll(); deleteDb("fullText"); deleteDb("fullTextReopen"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "test"
"public void test() throws Exception { testTransaction(false); <MASK>testTransaction(true);</MASK> testCreateDrop(); if (config.memory) { return; } testMultiThreaded(); testStreamLob(); test(false, "VARCHAR"); test(false, "CLOB"); testPerformance(false); testReopen(false); String luceneFullTextClassName = "org.h2.fulltext.FullTextLucene"; try { Class.forName(luceneFullTextClassName); test(true, "VARCHAR"); test(true, "CLOB"); testPerformance(true); testReopen(true); } catch (ClassNotFoundException e) { println("Class not found, not tested: " + luceneFullTextClassName); // ok } catch (NoClassDefFoundError e) { println("Class not found, not tested: " + luceneFullTextClassName); // ok } FullText.closeAll(); deleteDb("fullText"); deleteDb("fullTextReopen"); }"