type
stringclasses
1 value
dataset
stringclasses
1 value
input
stringlengths
75
160k
instruction
stringlengths
117
171
output
stringlengths
88
168k
Inversion-Mutation
megadiff
"@Override public void onCreate() { mConnectivityManager = new EmailConnectivityManager(this, TAG); // Start up our service thread new Thread(this, "AttachmentDownloadService").start(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate"
"@Override public void onCreate() { // Start up our service thread new Thread(this, "AttachmentDownloadService").start(); <MASK>mConnectivityManager = new EmailConnectivityManager(this, TAG);</MASK> }"
Inversion-Mutation
megadiff
"public long finish() throws IOException { obj_in.clear(); long cnt = super.finish(); return cnt; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "finish"
"public long finish() throws IOException { <MASK>long cnt = super.finish();</MASK> obj_in.clear(); return cnt; }"
Inversion-Mutation
megadiff
"public void processTimeout(final TimeoutEvent timeoutEvent) { Transaction eventTransaction = null; if(timeoutEvent.isServerTransaction()) { eventTransaction = timeoutEvent.getServerTransaction(); } else { eventTransaction = timeoutEvent.getClientTransaction(); } final Transaction transaction = eventTransaction; if(logger.isDebugEnabled()) { logger.debug("transaction " + transaction + " timed out => " + transaction.getRequest().toString()); } final TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData(); if(tad != null && tad.getSipServletMessage() != null) { getAsynchronousExecutor().execute(new Runnable() { public void run() { try { SipServletMessageImpl sipServletMessage = tad.getSipServletMessage(); SipSessionKey sipSessionKey = sipServletMessage.getSipSessionKey(); MobicentsSipSession sipSession = sipServletMessage.getSipSession(); boolean appNotifiedOfPrackNotReceived = false; // session can be null if a message was sent outside of the container by the container itself during Initial request dispatching // but the external host doesn't send any response so we call out to the application only if the session is not null if(sipSession != null) { SipContext sipContext = findSipApplication(sipSessionKey.getApplicationName()); //the context can be null if the server is being shutdown if(sipContext != null) { try { sipContext.enterSipApp(sipSession.getSipApplicationSession(), sipSession); // naoki : Fix for Issue 1618 http://code.google.com/p/mobicents/issues/detail?id=1618 on Timeout don't do the 408 processing for Server Transactions if(sipServletMessage instanceof SipServletRequestImpl && !timeoutEvent.isServerTransaction()) { try { ProxyBranchImpl proxyBranchImpl = tad.getProxyBranch(); if(proxyBranchImpl != null) { ProxyImpl proxy = (ProxyImpl) proxyBranchImpl.getProxy(); if(proxy.getFinalBranchForSubsequentRequests() != null) { tad.cleanUp(); transaction.setApplicationData(null); return; } } SipServletRequestImpl sipServletRequestImpl = (SipServletRequestImpl) sipServletMessage; if(sipServletRequestImpl.visitNextHop()) { return; } sipServletMessage.setTransaction(transaction); SipServletResponseImpl response = (SipServletResponseImpl) sipServletRequestImpl.createResponse(408, null, false); // Fix for Issue 1734 sipServletRequestImpl.setResponse(response); MessageDispatcher.callServlet(response); if(tad.getProxyBranch() != null) { tad.getProxyBranch().setResponse(response); tad.getProxyBranch().onResponse(response, response.getStatus()); } sipSession.updateStateOnResponse(response, true); } catch (Throwable t) { logger.error("Failed to deliver 408 response on transaction timeout" + transaction, t); } } // Guard only invite tx should check that, otherwise proxy might become null http://code.google.com/p/mobicents/issues/detail?id=2350 if(Request.INVITE.equals(sipServletMessage.getMethod())) { checkForAckNotReceived(sipServletMessage); appNotifiedOfPrackNotReceived = checkForPrackNotReceived(sipServletMessage); } } finally { sipSession.removeOngoingTransaction(transaction); sipSession.setRequestsPending(0); sipContext.exitSipApp(sipSession.getSipApplicationSession(), sipSession); } // don't invalidate here because if the application sends a final response on the noPrack received // the ACK to this final response won't be able to get routed since the sip session would have been invalidated if(!appNotifiedOfPrackNotReceived) { tryToInvalidateSession(sipSessionKey, false); } } } // don't clean up for the same reason we don't invalidate the sip session right above tad.cleanUp(); transaction.setApplicationData(null); } catch (Exception e) { logger.error("Problem handling timeout", e); } } }); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processTimeout"
"public void processTimeout(final TimeoutEvent timeoutEvent) { Transaction eventTransaction = null; if(timeoutEvent.isServerTransaction()) { eventTransaction = timeoutEvent.getServerTransaction(); } else { eventTransaction = timeoutEvent.getClientTransaction(); } final Transaction transaction = eventTransaction; if(logger.isDebugEnabled()) { logger.debug("transaction " + transaction + " timed out => " + transaction.getRequest().toString()); } final TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData(); if(tad != null && tad.getSipServletMessage() != null) { getAsynchronousExecutor().execute(new Runnable() { public void run() { try { SipServletMessageImpl sipServletMessage = tad.getSipServletMessage(); SipSessionKey sipSessionKey = sipServletMessage.getSipSessionKey(); MobicentsSipSession sipSession = sipServletMessage.getSipSession(); boolean appNotifiedOfPrackNotReceived = false; // session can be null if a message was sent outside of the container by the container itself during Initial request dispatching // but the external host doesn't send any response so we call out to the application only if the session is not null if(sipSession != null) { SipContext sipContext = findSipApplication(sipSessionKey.getApplicationName()); //the context can be null if the server is being shutdown if(sipContext != null) { try { sipContext.enterSipApp(sipSession.getSipApplicationSession(), sipSession); // naoki : Fix for Issue 1618 http://code.google.com/p/mobicents/issues/detail?id=1618 on Timeout don't do the 408 processing for Server Transactions if(sipServletMessage instanceof SipServletRequestImpl && !timeoutEvent.isServerTransaction()) { try { ProxyBranchImpl proxyBranchImpl = tad.getProxyBranch(); if(proxyBranchImpl != null) { ProxyImpl proxy = (ProxyImpl) proxyBranchImpl.getProxy(); if(proxy.getFinalBranchForSubsequentRequests() != null) { tad.cleanUp(); transaction.setApplicationData(null); return; } } SipServletRequestImpl sipServletRequestImpl = (SipServletRequestImpl) sipServletMessage; if(sipServletRequestImpl.visitNextHop()) { return; } sipServletMessage.setTransaction(transaction); SipServletResponseImpl response = (SipServletResponseImpl) sipServletRequestImpl.createResponse(408, null, false); // Fix for Issue 1734 sipServletRequestImpl.setResponse(response); MessageDispatcher.callServlet(response); if(tad.getProxyBranch() != null) { tad.getProxyBranch().setResponse(response); tad.getProxyBranch().onResponse(response, response.getStatus()); } sipSession.updateStateOnResponse(response, true); } catch (Throwable t) { logger.error("Failed to deliver 408 response on transaction timeout" + transaction, t); } } // Guard only invite tx should check that, otherwise proxy might become null http://code.google.com/p/mobicents/issues/detail?id=2350 if(Request.INVITE.equals(sipServletMessage.getMethod())) { checkForAckNotReceived(sipServletMessage); } <MASK>appNotifiedOfPrackNotReceived = checkForPrackNotReceived(sipServletMessage);</MASK> } finally { sipSession.removeOngoingTransaction(transaction); sipSession.setRequestsPending(0); sipContext.exitSipApp(sipSession.getSipApplicationSession(), sipSession); } // don't invalidate here because if the application sends a final response on the noPrack received // the ACK to this final response won't be able to get routed since the sip session would have been invalidated if(!appNotifiedOfPrackNotReceived) { tryToInvalidateSession(sipSessionKey, false); } } } // don't clean up for the same reason we don't invalidate the sip session right above tad.cleanUp(); transaction.setApplicationData(null); } catch (Exception e) { logger.error("Problem handling timeout", e); } } }); } }"
Inversion-Mutation
megadiff
"public void run() { try { SipServletMessageImpl sipServletMessage = tad.getSipServletMessage(); SipSessionKey sipSessionKey = sipServletMessage.getSipSessionKey(); MobicentsSipSession sipSession = sipServletMessage.getSipSession(); boolean appNotifiedOfPrackNotReceived = false; // session can be null if a message was sent outside of the container by the container itself during Initial request dispatching // but the external host doesn't send any response so we call out to the application only if the session is not null if(sipSession != null) { SipContext sipContext = findSipApplication(sipSessionKey.getApplicationName()); //the context can be null if the server is being shutdown if(sipContext != null) { try { sipContext.enterSipApp(sipSession.getSipApplicationSession(), sipSession); // naoki : Fix for Issue 1618 http://code.google.com/p/mobicents/issues/detail?id=1618 on Timeout don't do the 408 processing for Server Transactions if(sipServletMessage instanceof SipServletRequestImpl && !timeoutEvent.isServerTransaction()) { try { ProxyBranchImpl proxyBranchImpl = tad.getProxyBranch(); if(proxyBranchImpl != null) { ProxyImpl proxy = (ProxyImpl) proxyBranchImpl.getProxy(); if(proxy.getFinalBranchForSubsequentRequests() != null) { tad.cleanUp(); transaction.setApplicationData(null); return; } } SipServletRequestImpl sipServletRequestImpl = (SipServletRequestImpl) sipServletMessage; if(sipServletRequestImpl.visitNextHop()) { return; } sipServletMessage.setTransaction(transaction); SipServletResponseImpl response = (SipServletResponseImpl) sipServletRequestImpl.createResponse(408, null, false); // Fix for Issue 1734 sipServletRequestImpl.setResponse(response); MessageDispatcher.callServlet(response); if(tad.getProxyBranch() != null) { tad.getProxyBranch().setResponse(response); tad.getProxyBranch().onResponse(response, response.getStatus()); } sipSession.updateStateOnResponse(response, true); } catch (Throwable t) { logger.error("Failed to deliver 408 response on transaction timeout" + transaction, t); } } // Guard only invite tx should check that, otherwise proxy might become null http://code.google.com/p/mobicents/issues/detail?id=2350 if(Request.INVITE.equals(sipServletMessage.getMethod())) { checkForAckNotReceived(sipServletMessage); appNotifiedOfPrackNotReceived = checkForPrackNotReceived(sipServletMessage); } } finally { sipSession.removeOngoingTransaction(transaction); sipSession.setRequestsPending(0); sipContext.exitSipApp(sipSession.getSipApplicationSession(), sipSession); } // don't invalidate here because if the application sends a final response on the noPrack received // the ACK to this final response won't be able to get routed since the sip session would have been invalidated if(!appNotifiedOfPrackNotReceived) { tryToInvalidateSession(sipSessionKey, false); } } } // don't clean up for the same reason we don't invalidate the sip session right above tad.cleanUp(); transaction.setApplicationData(null); } catch (Exception e) { logger.error("Problem handling timeout", e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { try { SipServletMessageImpl sipServletMessage = tad.getSipServletMessage(); SipSessionKey sipSessionKey = sipServletMessage.getSipSessionKey(); MobicentsSipSession sipSession = sipServletMessage.getSipSession(); boolean appNotifiedOfPrackNotReceived = false; // session can be null if a message was sent outside of the container by the container itself during Initial request dispatching // but the external host doesn't send any response so we call out to the application only if the session is not null if(sipSession != null) { SipContext sipContext = findSipApplication(sipSessionKey.getApplicationName()); //the context can be null if the server is being shutdown if(sipContext != null) { try { sipContext.enterSipApp(sipSession.getSipApplicationSession(), sipSession); // naoki : Fix for Issue 1618 http://code.google.com/p/mobicents/issues/detail?id=1618 on Timeout don't do the 408 processing for Server Transactions if(sipServletMessage instanceof SipServletRequestImpl && !timeoutEvent.isServerTransaction()) { try { ProxyBranchImpl proxyBranchImpl = tad.getProxyBranch(); if(proxyBranchImpl != null) { ProxyImpl proxy = (ProxyImpl) proxyBranchImpl.getProxy(); if(proxy.getFinalBranchForSubsequentRequests() != null) { tad.cleanUp(); transaction.setApplicationData(null); return; } } SipServletRequestImpl sipServletRequestImpl = (SipServletRequestImpl) sipServletMessage; if(sipServletRequestImpl.visitNextHop()) { return; } sipServletMessage.setTransaction(transaction); SipServletResponseImpl response = (SipServletResponseImpl) sipServletRequestImpl.createResponse(408, null, false); // Fix for Issue 1734 sipServletRequestImpl.setResponse(response); MessageDispatcher.callServlet(response); if(tad.getProxyBranch() != null) { tad.getProxyBranch().setResponse(response); tad.getProxyBranch().onResponse(response, response.getStatus()); } sipSession.updateStateOnResponse(response, true); } catch (Throwable t) { logger.error("Failed to deliver 408 response on transaction timeout" + transaction, t); } } // Guard only invite tx should check that, otherwise proxy might become null http://code.google.com/p/mobicents/issues/detail?id=2350 if(Request.INVITE.equals(sipServletMessage.getMethod())) { checkForAckNotReceived(sipServletMessage); } <MASK>appNotifiedOfPrackNotReceived = checkForPrackNotReceived(sipServletMessage);</MASK> } finally { sipSession.removeOngoingTransaction(transaction); sipSession.setRequestsPending(0); sipContext.exitSipApp(sipSession.getSipApplicationSession(), sipSession); } // don't invalidate here because if the application sends a final response on the noPrack received // the ACK to this final response won't be able to get routed since the sip session would have been invalidated if(!appNotifiedOfPrackNotReceived) { tryToInvalidateSession(sipSessionKey, false); } } } // don't clean up for the same reason we don't invalidate the sip session right above tad.cleanUp(); transaction.setApplicationData(null); } catch (Exception e) { logger.error("Problem handling timeout", e); } }"
Inversion-Mutation
megadiff
"private SpoutChunk setChunk(SpoutChunk newChunk, int x, int y, int z, ChunkDataForRegion dataForRegion, boolean generated, LoadOption loadopt) { final AtomicReference<SpoutChunk> chunkReference = chunks[x][y][z]; while (true) { if (chunkReference.compareAndSet(null, newChunk)) { newChunk.notifyColumn(); if (Spout.getEngine().getPlatform() == Platform.CLIENT) { newChunk.setNeighbourRenderDirty(true); } numberActiveChunks.incrementAndGet(); if (dataForRegion != null) { for (SpoutEntity entity : dataForRegion.loadedEntities) { entity.setupInitialChunk(entity.getTransform().getTransform()); entityManager.addEntity(entity); } dynamicBlockTree.addDynamicBlockUpdates(dataForRegion.loadedUpdates); } Spout.getEventManager().callDelayedEvent(new ChunkLoadEvent(newChunk, generated)); return newChunk; } SpoutChunk oldChunk = chunkReference.get(); if (oldChunk != null) { newChunk.setUnloadedUnchecked(); checkChunkLoaded(oldChunk, loadopt); return oldChunk; } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setChunk"
"private SpoutChunk setChunk(SpoutChunk newChunk, int x, int y, int z, ChunkDataForRegion dataForRegion, boolean generated, LoadOption loadopt) { final AtomicReference<SpoutChunk> chunkReference = chunks[x][y][z]; while (true) { if (chunkReference.compareAndSet(null, newChunk)) { newChunk.notifyColumn(); if (Spout.getEngine().getPlatform() == Platform.CLIENT) { newChunk.setNeighbourRenderDirty(true); } numberActiveChunks.incrementAndGet(); if (dataForRegion != null) { for (SpoutEntity entity : dataForRegion.loadedEntities) { entity.setupInitialChunk(entity.getTransform().getTransform()); entityManager.addEntity(entity); } dynamicBlockTree.addDynamicBlockUpdates(dataForRegion.loadedUpdates); } Spout.getEventManager().callDelayedEvent(new ChunkLoadEvent(newChunk, generated)); return newChunk; } <MASK>newChunk.setUnloadedUnchecked();</MASK> SpoutChunk oldChunk = chunkReference.get(); if (oldChunk != null) { checkChunkLoaded(oldChunk, loadopt); return oldChunk; } } }"
Inversion-Mutation
megadiff
"public void handleCollisionMessage(CollisionServerMessage message) { int bulletID = message.mBulletID; int shipID = message.mShipID; if (shipID != this.mID) { Body bulletBody = this.mBullets.get(bulletID); // delete the bullet if it exists if (bulletBody != null) { bulletBody.setUserData("delete"); this.mBullets.remove(bulletID); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleCollisionMessage"
"public void handleCollisionMessage(CollisionServerMessage message) { int bulletID = message.mBulletID; int shipID = message.mShipID; if (shipID != this.mID) { Body bulletBody = this.mBullets.get(bulletID); // delete the bullet if it exists if (bulletBody != null) { bulletBody.setUserData("delete"); } <MASK>this.mBullets.remove(bulletID);</MASK> } }"
Inversion-Mutation
megadiff
"protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { prefixHTML(out); /* * TODO output your page here out.println("<html>"); * out.println("<head>"); out.println("<title>Servlet * HelloJPACloudBees</title>"); out.println("</head>"); * out.println("<body>"); out.println("<h1>Servlet HelloJPACloudBees * at " + request.getContextPath () + "</h1>"); * out.println("</body>"); out.println("</html>"); * * */ /* Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/postgresql"); Connection conn = ds.getConnection(); Statement stmt = conn.createStatement(); ResultSet rst = stmt.executeQuery("select * from countries"); while (rst.next()) { int id = rst.getInt(1); String foo = rst.getString(2); String bar = rst.getString (3); out.println (id + foo + bar); } conn.close(); */ EntityManagerFactory emf = Persistence.createEntityManagerFactory("PostgresqlPU"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Query queryAll = em.createNamedQuery("Countries.findAll"); out.println("Getting results"); Collection c = queryAll.getResultList(); out.println("DB Size :" + c.size() + "<br/>"); Iterator iterator = c.iterator(); while (iterator.hasNext()) { Countries country = (Countries) iterator.next(); out.println("<b>" + country.getCaptial() + "</b> is the capital of " + country.getCountry() + "<br/>"); } } catch (Exception e) { out.println(e.toString()); } finally { postfixHTML(out); out.close(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processRequest"
"protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { prefixHTML(out); /* * TODO output your page here out.println("<html>"); * out.println("<head>"); out.println("<title>Servlet * HelloJPACloudBees</title>"); out.println("</head>"); * out.println("<body>"); out.println("<h1>Servlet HelloJPACloudBees * at " + request.getContextPath () + "</h1>"); * out.println("</body>"); out.println("</html>"); * * */ /* Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/postgresql"); Connection conn = ds.getConnection(); Statement stmt = conn.createStatement(); ResultSet rst = stmt.executeQuery("select * from countries"); while (rst.next()) { int id = rst.getInt(1); String foo = rst.getString(2); String bar = rst.getString (3); out.println (id + foo + bar); } conn.close(); */ EntityManagerFactory emf = Persistence.createEntityManagerFactory("PostgresqlPU"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Query queryAll = em.createNamedQuery("Countries.findAll"); out.println("Getting results"); Collection c = queryAll.getResultList(); out.println("DB Size :" + c.size() + "<br/>"); Iterator iterator = c.iterator(); <MASK>postfixHTML(out);</MASK> while (iterator.hasNext()) { Countries country = (Countries) iterator.next(); out.println("<b>" + country.getCaptial() + "</b> is the capital of " + country.getCountry() + "<br/>"); } } catch (Exception e) { out.println(e.toString()); } finally { out.close(); } }"
Inversion-Mutation
megadiff
"public Groundplan getOptimalSolution(int maxiter){ double currentvalue,nextvalue; for(int i=0;i<=maxiter;i++) { springembedding.springEmbed(currentplan.getVertices()); //bereken startCurrentValue en startNextValue (deze zijn nodig voor berekenen T) currentvalue=currentplan.getGroundplan().getPlanValue(); nextvalue=nextplan.getGroundplan().getPlanValue(); if(i==0) setT(currentvalue,nextvalue); if(currentvalue<nextvalue){ cloneGroundPlans(nextvalue); } else { if(determineAcception(currentvalue, nextvalue)) cloneGroundPlans(nextvalue); } } return optimalplan.getGroundplan(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getOptimalSolution"
"public Groundplan getOptimalSolution(int maxiter){ double currentvalue,nextvalue; for(int i=0;i<=maxiter;i++) { springembedding.springEmbed(currentplan.getVertices()); //bereken startCurrentValue en startNextValue (deze zijn nodig voor berekenen T) currentvalue=currentplan.getGroundplan().getPlanValue(); nextvalue=nextplan.getGroundplan().getPlanValue(); if(currentvalue<nextvalue){ cloneGroundPlans(nextvalue); } else { if(determineAcception(currentvalue, nextvalue)) cloneGroundPlans(nextvalue); } <MASK>if(i==0) setT(currentvalue,nextvalue);</MASK> } return optimalplan.getGroundplan(); }"
Inversion-Mutation
megadiff
"@Override protected void retrieveContainedJComponentsAndConstraints() { if (placeholders == null) { placeholders = new Vector<PlaceHolder>(); } placeholders.removeAllElements(); super.retrieveContainedJComponentsAndConstraints(); if (!getComponent().getProtectContent()) { // FlowLayout if (getComponent().getLayout() == Layout.flow) { final FlowLayoutConstraints beginPlaceHolderConstraints = new FlowLayoutConstraints(); PlaceHolder beginPlaceHolder = new PlaceHolder(this, "<begin>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginPlaceHolderConstraints, 0); } }; registerComponentWithConstraints(beginPlaceHolder, beginPlaceHolderConstraints, 0); placeholders.add(beginPlaceHolder); beginPlaceHolder.setVisible(false); final FlowLayoutConstraints endPlaceHolderConstraints = new FlowLayoutConstraints(); PlaceHolder endPlaceHolder = new PlaceHolder(this, "<end>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, endPlaceHolderConstraints, FIBEditablePanelView.this.getComponent().getSubComponents().size()); } }; registerComponentWithConstraints(endPlaceHolder, endPlaceHolderConstraints); placeholders.add(endPlaceHolder); endPlaceHolder.setVisible(false); } // BoxLayout if (getComponent().getLayout() == Layout.box) { final BoxLayoutConstraints beginPlaceHolderConstraints = new BoxLayoutConstraints(); PlaceHolder beginPlaceHolder = new PlaceHolder(this, "<begin>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginPlaceHolderConstraints, 0); } }; registerComponentWithConstraints(beginPlaceHolder, beginPlaceHolderConstraints); placeholders.add(beginPlaceHolder); beginPlaceHolder.setVisible(false); final BoxLayoutConstraints endPlaceHolderConstraints = new BoxLayoutConstraints(); PlaceHolder endPlaceHolder = new PlaceHolder(this, "<end>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, endPlaceHolderConstraints); } }; registerComponentWithConstraints(endPlaceHolder); placeholders.add(endPlaceHolder); endPlaceHolder.setVisible(false); } // BorderLayout if (getComponent().getLayout() == Layout.border) { BorderLayout bl = (BorderLayout) getJComponent().getLayout(); BorderLayoutLocation[] placeholderLocations = { BorderLayoutLocation.north, BorderLayoutLocation.south, BorderLayoutLocation.center, BorderLayoutLocation.east, BorderLayoutLocation.west }; for (final BorderLayoutLocation l : placeholderLocations) { boolean found = false; for (FIBComponent subComponent : getComponent().getSubComponents()) { BorderLayoutConstraints blc = (BorderLayoutConstraints) subComponent.getConstraints(); if (blc.getLocation() == l) { found = true; } } if (!found) { PlaceHolder newPlaceHolder = new PlaceHolder(this, "<" + l.getConstraint() + ">") { @Override public void insertComponent(FIBComponent newComponent) { BorderLayoutConstraints blConstraints = new BorderLayoutConstraints(l); newComponent.setConstraints(blConstraints); FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent); } }; registerComponentWithConstraints(newPlaceHolder, l.getConstraint()); newPlaceHolder.setVisible(false); placeholders.add(newPlaceHolder); logger.fine("Made placeholder for " + l.getConstraint()); } } } // TwoColsLayout if (getComponent().getLayout() == Layout.twocols) { final TwoColsLayoutConstraints beginCenterPlaceHolderConstraints = new TwoColsLayoutConstraints( TwoColsLayoutLocation.center, true, false); PlaceHolder beginCenterPlaceHolder = new PlaceHolder(this, "<center>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginCenterPlaceHolderConstraints, 0); } }; registerComponentWithConstraints(beginCenterPlaceHolder, beginCenterPlaceHolderConstraints, 0); placeholders.add(beginCenterPlaceHolder); beginCenterPlaceHolder.setVisible(false); final TwoColsLayoutConstraints beginLeftPlaceHolderConstraints = new TwoColsLayoutConstraints(TwoColsLayoutLocation.left, true, false); final TwoColsLayoutConstraints beginRightPlaceHolderConstraints = new TwoColsLayoutConstraints(TwoColsLayoutLocation.right, true, false); PlaceHolder beginRightPlaceHolder = new PlaceHolder(this, "<right>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginRightPlaceHolderConstraints, 0); FIBEditablePanelView.this.getComponent().addToSubComponents(new FIBLabel("<left>"), beginLeftPlaceHolderConstraints, 0); } }; registerComponentWithConstraints(beginRightPlaceHolder, beginRightPlaceHolderConstraints, 0); placeholders.add(beginRightPlaceHolder); beginRightPlaceHolder.setVisible(false); PlaceHolder beginLeftPlaceHolder = new PlaceHolder(this, "<left>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(new FIBLabel("<right>"), beginRightPlaceHolderConstraints, 0); FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginLeftPlaceHolderConstraints, 0); } }; registerComponentWithConstraints(beginLeftPlaceHolder, beginLeftPlaceHolderConstraints, 0); placeholders.add(beginLeftPlaceHolder); beginLeftPlaceHolder.setVisible(false); final TwoColsLayoutConstraints endCenterPlaceHolderConstraints = new TwoColsLayoutConstraints(TwoColsLayoutLocation.center, true, false); PlaceHolder endCenterPlaceHolder = new PlaceHolder(this, "<center>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, endCenterPlaceHolderConstraints); } }; registerComponentWithConstraints(endCenterPlaceHolder, endCenterPlaceHolderConstraints); placeholders.add(endCenterPlaceHolder); endCenterPlaceHolder.setVisible(false); final TwoColsLayoutConstraints endLeftPlaceHolderConstraints = new TwoColsLayoutConstraints(TwoColsLayoutLocation.left, true, false); final TwoColsLayoutConstraints endRightPlaceHolderConstraints = new TwoColsLayoutConstraints(TwoColsLayoutLocation.right, true, false); PlaceHolder endLeftPlaceHolder = new PlaceHolder(this, "<left>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, endLeftPlaceHolderConstraints); FIBEditablePanelView.this.getComponent() .addToSubComponents(new FIBLabel("<right>"), endRightPlaceHolderConstraints); } }; registerComponentWithConstraints(endLeftPlaceHolder, endLeftPlaceHolderConstraints); placeholders.add(endLeftPlaceHolder); endLeftPlaceHolder.setVisible(false); PlaceHolder endRightPlaceHolder = new PlaceHolder(this, "<right>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(new FIBLabel("<left>"), endLeftPlaceHolderConstraints); FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, endRightPlaceHolderConstraints); } }; registerComponentWithConstraints(endRightPlaceHolder, endRightPlaceHolderConstraints); placeholders.add(endRightPlaceHolder); endRightPlaceHolder.setVisible(false); } // GridBagLayout if (getComponent().getLayout() == Layout.gridbag) { final GridBagLayoutConstraints beginPlaceHolderConstraints = new GridBagLayoutConstraints(); PlaceHolder beginPlaceHolder = new PlaceHolder(this, "<begin>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginPlaceHolderConstraints, 0); } }; registerComponentWithConstraints(beginPlaceHolder, beginPlaceHolderConstraints, 0); placeholders.add(beginPlaceHolder); beginPlaceHolder.setVisible(false); final GridBagLayoutConstraints endPlaceHolderConstraints = new GridBagLayoutConstraints(); PlaceHolder endPlaceHolder = new PlaceHolder(this, "<end>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, endPlaceHolderConstraints); } }; registerComponentWithConstraints(endPlaceHolder); placeholders.add(endPlaceHolder); endPlaceHolder.setVisible(false); } // Now, we sort again subComponents, since we may have added some placeholders /*if (getComponent().getLayout() == Layout.flow || getComponent().getLayout() == Layout.box || getComponent().getLayout() == Layout.twocols || getComponent().getLayout() == Layout.gridbag) { Collections.sort(getSubComponents(), new Comparator<JComponent>() { @Override public int compare(JComponent o1, JComponent o2) { Object c1 = getConstraints().get(o1); Object c2 = getConstraints().get(o2); if (c1 instanceof ComponentConstraints && c2 instanceof ComponentConstraints) { ComponentConstraints cc1 = (ComponentConstraints) c1; ComponentConstraints cc2 = (ComponentConstraints) c2; return cc1.getIndex() - cc2.getIndex(); } return 0; } }); }*/ // logger.info("******** Set DropTargets"); if (getEditorController() != null) { for (PlaceHolder ph : placeholders) { logger.fine("Set DropTarget for " + ph); // Put right drop target new FIBDropTarget(ph); } } /*else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { updateLayout(); } }); }*/ } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "retrieveContainedJComponentsAndConstraints"
"@Override protected void retrieveContainedJComponentsAndConstraints() { if (placeholders == null) { placeholders = new Vector<PlaceHolder>(); } placeholders.removeAllElements(); super.retrieveContainedJComponentsAndConstraints(); if (!getComponent().getProtectContent()) { // FlowLayout if (getComponent().getLayout() == Layout.flow) { final FlowLayoutConstraints beginPlaceHolderConstraints = new FlowLayoutConstraints(); PlaceHolder beginPlaceHolder = new PlaceHolder(this, "<begin>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginPlaceHolderConstraints, 0); } }; registerComponentWithConstraints(beginPlaceHolder, beginPlaceHolderConstraints, 0); placeholders.add(beginPlaceHolder); beginPlaceHolder.setVisible(false); final FlowLayoutConstraints endPlaceHolderConstraints = new FlowLayoutConstraints(); PlaceHolder endPlaceHolder = new PlaceHolder(this, "<end>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, endPlaceHolderConstraints, FIBEditablePanelView.this.getComponent().getSubComponents().size()); } }; registerComponentWithConstraints(endPlaceHolder, endPlaceHolderConstraints); placeholders.add(endPlaceHolder); endPlaceHolder.setVisible(false); } // BoxLayout if (getComponent().getLayout() == Layout.box) { final BoxLayoutConstraints beginPlaceHolderConstraints = new BoxLayoutConstraints(); PlaceHolder beginPlaceHolder = new PlaceHolder(this, "<begin>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginPlaceHolderConstraints, 0); } }; registerComponentWithConstraints(beginPlaceHolder, beginPlaceHolderConstraints); placeholders.add(beginPlaceHolder); beginPlaceHolder.setVisible(false); final BoxLayoutConstraints endPlaceHolderConstraints = new BoxLayoutConstraints(); PlaceHolder endPlaceHolder = new PlaceHolder(this, "<end>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, endPlaceHolderConstraints); } }; registerComponentWithConstraints(endPlaceHolder); placeholders.add(endPlaceHolder); endPlaceHolder.setVisible(false); } // BorderLayout if (getComponent().getLayout() == Layout.border) { BorderLayout bl = (BorderLayout) getJComponent().getLayout(); BorderLayoutLocation[] placeholderLocations = { BorderLayoutLocation.north, BorderLayoutLocation.south, BorderLayoutLocation.center, BorderLayoutLocation.east, BorderLayoutLocation.west }; for (final BorderLayoutLocation l : placeholderLocations) { boolean found = false; for (FIBComponent subComponent : getComponent().getSubComponents()) { BorderLayoutConstraints blc = (BorderLayoutConstraints) subComponent.getConstraints(); if (blc.getLocation() == l) { found = true; } } if (!found) { PlaceHolder newPlaceHolder = new PlaceHolder(this, "<" + l.getConstraint() + ">") { @Override public void insertComponent(FIBComponent newComponent) { BorderLayoutConstraints blConstraints = new BorderLayoutConstraints(l); newComponent.setConstraints(blConstraints); FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent); } }; registerComponentWithConstraints(newPlaceHolder, l.getConstraint()); newPlaceHolder.setVisible(false); placeholders.add(newPlaceHolder); logger.fine("Made placeholder for " + l.getConstraint()); } } } // TwoColsLayout if (getComponent().getLayout() == Layout.twocols) { final TwoColsLayoutConstraints beginCenterPlaceHolderConstraints = new TwoColsLayoutConstraints( TwoColsLayoutLocation.center, true, false); PlaceHolder beginCenterPlaceHolder = new PlaceHolder(this, "<center>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginCenterPlaceHolderConstraints, 0); } }; registerComponentWithConstraints(beginCenterPlaceHolder, beginCenterPlaceHolderConstraints, 0); placeholders.add(beginCenterPlaceHolder); beginCenterPlaceHolder.setVisible(false); final TwoColsLayoutConstraints beginLeftPlaceHolderConstraints = new TwoColsLayoutConstraints(TwoColsLayoutLocation.left, true, false); final TwoColsLayoutConstraints beginRightPlaceHolderConstraints = new TwoColsLayoutConstraints(TwoColsLayoutLocation.right, true, false); PlaceHolder beginRightPlaceHolder = new PlaceHolder(this, "<right>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginRightPlaceHolderConstraints, 0); FIBEditablePanelView.this.getComponent().addToSubComponents(new FIBLabel("<left>"), beginLeftPlaceHolderConstraints, 0); } }; registerComponentWithConstraints(beginRightPlaceHolder, beginRightPlaceHolderConstraints, 0); placeholders.add(beginRightPlaceHolder); beginRightPlaceHolder.setVisible(false); PlaceHolder beginLeftPlaceHolder = new PlaceHolder(this, "<left>") { @Override public void insertComponent(FIBComponent newComponent) { <MASK>FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginLeftPlaceHolderConstraints, 0);</MASK> FIBEditablePanelView.this.getComponent().addToSubComponents(new FIBLabel("<right>"), beginRightPlaceHolderConstraints, 0); } }; registerComponentWithConstraints(beginLeftPlaceHolder, beginLeftPlaceHolderConstraints, 0); placeholders.add(beginLeftPlaceHolder); beginLeftPlaceHolder.setVisible(false); final TwoColsLayoutConstraints endCenterPlaceHolderConstraints = new TwoColsLayoutConstraints(TwoColsLayoutLocation.center, true, false); PlaceHolder endCenterPlaceHolder = new PlaceHolder(this, "<center>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, endCenterPlaceHolderConstraints); } }; registerComponentWithConstraints(endCenterPlaceHolder, endCenterPlaceHolderConstraints); placeholders.add(endCenterPlaceHolder); endCenterPlaceHolder.setVisible(false); final TwoColsLayoutConstraints endLeftPlaceHolderConstraints = new TwoColsLayoutConstraints(TwoColsLayoutLocation.left, true, false); final TwoColsLayoutConstraints endRightPlaceHolderConstraints = new TwoColsLayoutConstraints(TwoColsLayoutLocation.right, true, false); PlaceHolder endLeftPlaceHolder = new PlaceHolder(this, "<left>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, endLeftPlaceHolderConstraints); FIBEditablePanelView.this.getComponent() .addToSubComponents(new FIBLabel("<right>"), endRightPlaceHolderConstraints); } }; registerComponentWithConstraints(endLeftPlaceHolder, endLeftPlaceHolderConstraints); placeholders.add(endLeftPlaceHolder); endLeftPlaceHolder.setVisible(false); PlaceHolder endRightPlaceHolder = new PlaceHolder(this, "<right>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(new FIBLabel("<left>"), endLeftPlaceHolderConstraints); FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, endRightPlaceHolderConstraints); } }; registerComponentWithConstraints(endRightPlaceHolder, endRightPlaceHolderConstraints); placeholders.add(endRightPlaceHolder); endRightPlaceHolder.setVisible(false); } // GridBagLayout if (getComponent().getLayout() == Layout.gridbag) { final GridBagLayoutConstraints beginPlaceHolderConstraints = new GridBagLayoutConstraints(); PlaceHolder beginPlaceHolder = new PlaceHolder(this, "<begin>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginPlaceHolderConstraints, 0); } }; registerComponentWithConstraints(beginPlaceHolder, beginPlaceHolderConstraints, 0); placeholders.add(beginPlaceHolder); beginPlaceHolder.setVisible(false); final GridBagLayoutConstraints endPlaceHolderConstraints = new GridBagLayoutConstraints(); PlaceHolder endPlaceHolder = new PlaceHolder(this, "<end>") { @Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, endPlaceHolderConstraints); } }; registerComponentWithConstraints(endPlaceHolder); placeholders.add(endPlaceHolder); endPlaceHolder.setVisible(false); } // Now, we sort again subComponents, since we may have added some placeholders /*if (getComponent().getLayout() == Layout.flow || getComponent().getLayout() == Layout.box || getComponent().getLayout() == Layout.twocols || getComponent().getLayout() == Layout.gridbag) { Collections.sort(getSubComponents(), new Comparator<JComponent>() { @Override public int compare(JComponent o1, JComponent o2) { Object c1 = getConstraints().get(o1); Object c2 = getConstraints().get(o2); if (c1 instanceof ComponentConstraints && c2 instanceof ComponentConstraints) { ComponentConstraints cc1 = (ComponentConstraints) c1; ComponentConstraints cc2 = (ComponentConstraints) c2; return cc1.getIndex() - cc2.getIndex(); } return 0; } }); }*/ // logger.info("******** Set DropTargets"); if (getEditorController() != null) { for (PlaceHolder ph : placeholders) { logger.fine("Set DropTarget for " + ph); // Put right drop target new FIBDropTarget(ph); } } /*else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { updateLayout(); } }); }*/ } }"
Inversion-Mutation
megadiff
"@Override public void insertComponent(FIBComponent newComponent) { FIBEditablePanelView.this.getComponent().addToSubComponents(new FIBLabel("<right>"), beginRightPlaceHolderConstraints, 0); FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginLeftPlaceHolderConstraints, 0); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "insertComponent"
"@Override public void insertComponent(FIBComponent newComponent) { <MASK>FIBEditablePanelView.this.getComponent().addToSubComponents(newComponent, beginLeftPlaceHolderConstraints, 0);</MASK> FIBEditablePanelView.this.getComponent().addToSubComponents(new FIBLabel("<right>"), beginRightPlaceHolderConstraints, 0); }"
Inversion-Mutation
megadiff
"private static int init() { SessionManager.generateTestSessionFactory(); ModelAccessor.initialize(new Model()); return 0; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "init"
"private static int init() { <MASK>ModelAccessor.initialize(new Model());</MASK> SessionManager.generateTestSessionFactory(); return 0; }"
Inversion-Mutation
megadiff
"@Override protected void onPause() { super.onPause(); updateModel(); try { String action = getIntent().getAction(); if (Intent.ACTION_INSERT.equals(action)) { Uri uri = getContentResolver().insert(DB.CpuProfile.CONTENT_URI, cpu.getValues()); long id = ContentUris.parseId(uri); if (id > 0) { cpu.setDbId(id); } } else if (Intent.ACTION_EDIT.equals(action)) { if (origCpu.equals(cpu)) { return; } getContentResolver().update(DB.CpuProfile.CONTENT_URI, cpu.getValues(), DB.NAME_ID + "=?", new String[] { cpu.getDbId() + "" }); } } catch (Exception e) { Log.w(Logger.TAG, "Cannot insert or update", e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPause"
"@Override protected void onPause() { updateModel(); try { String action = getIntent().getAction(); if (Intent.ACTION_INSERT.equals(action)) { Uri uri = getContentResolver().insert(DB.CpuProfile.CONTENT_URI, cpu.getValues()); long id = ContentUris.parseId(uri); if (id > 0) { cpu.setDbId(id); } } else if (Intent.ACTION_EDIT.equals(action)) { if (origCpu.equals(cpu)) { return; } getContentResolver().update(DB.CpuProfile.CONTENT_URI, cpu.getValues(), DB.NAME_ID + "=?", new String[] { cpu.getDbId() + "" }); } } catch (Exception e) { Log.w(Logger.TAG, "Cannot insert or update", e); } <MASK>super.onPause();</MASK> }"
Inversion-Mutation
megadiff
"public Lists(Sink.Images images) { combo.setVisibleItemCount(1); combo.addChangeListener(this); list.setVisibleItemCount(10); list.setMultipleSelect(true); for (int i = 0; i < stringLists.length; ++i) { combo.addItem("List " + i); } combo.setSelectedIndex(0); fillList(0); list.addChangeListener(this); for (int i = 0; i < words.length; ++i) { oracle.add(words[i]); } VerticalPanel suggestPanel = new VerticalPanel(); suggestPanel.add(new Label("Suggest box:")); suggestPanel.add(suggestBox); HorizontalPanel horz = new HorizontalPanel(); horz.setVerticalAlignment(HorizontalPanel.ALIGN_TOP); horz.setSpacing(8); horz.add(combo); horz.add(list); horz.add(suggestPanel); VerticalPanel panel = new VerticalPanel(); panel.setHorizontalAlignment(VerticalPanel.ALIGN_LEFT); panel.add(horz); initWidget(panel); tree = new Tree(images); for (int i = 0; i < fProto.length; ++i) { createItem(fProto[i]); tree.addItem(fProto[i].item); } tree.addTreeListener(this); tree.setWidth("20em"); horz.add(tree); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Lists"
"public Lists(Sink.Images images) { combo.setVisibleItemCount(1); combo.addChangeListener(this); list.setVisibleItemCount(10); list.setMultipleSelect(true); for (int i = 0; i < stringLists.length; ++i) { combo.addItem("List " + i); } combo.setSelectedIndex(0); fillList(0); list.addChangeListener(this); for (int i = 0; i < words.length; ++i) { oracle.add(words[i]); } VerticalPanel suggestPanel = new VerticalPanel(); suggestPanel.add(new Label("Suggest box:")); suggestPanel.add(suggestBox); HorizontalPanel horz = new HorizontalPanel(); horz.setVerticalAlignment(HorizontalPanel.ALIGN_TOP); horz.setSpacing(8); horz.add(combo); horz.add(list); horz.add(suggestPanel); <MASK>horz.add(tree);</MASK> VerticalPanel panel = new VerticalPanel(); panel.setHorizontalAlignment(VerticalPanel.ALIGN_LEFT); panel.add(horz); initWidget(panel); tree = new Tree(images); for (int i = 0; i < fProto.length; ++i) { createItem(fProto[i]); tree.addItem(fProto[i].item); } tree.addTreeListener(this); tree.setWidth("20em"); }"
Inversion-Mutation
megadiff
"public MediaTypeHandler( HttpServletRequest request, HttpServletResponse response ) { String acceptHeader = request.getHeader("Accept"); String contentTypeHeader = request.getHeader("Content-Type"); // accept defaults to JSON accept = APPLICATION_JSON; if ( acceptHeader != null ) { if ( acceptHeader.contains(APPLICATION_JSON) ) { response.setHeader( "Content-Type", APPLICATION_JSON); } else if ( acceptHeader.contains(APPLICATION_ATOM) ) { accept = APPLICATION_ATOM; } else if ( acceptHeader.contains(TEXT_HTML) ) { accept = TEXT_HTML; } } if ( contentTypeHeader != null ) { if ( contentTypeHeader.equals( FORM_URL_ENCODED ) ) { contentTypeFormUrlEncoded = true; contentTypeApplicationJSON = false; } else if ( contentTypeHeader.equals( APPLICATION_JSON )) { contentTypeFormUrlEncoded = false; contentTypeApplicationJSON = true; } else { if ( !contentTypeHeader.isEmpty() ) throw new UnsupportedMediaTypeException(); // default to JSON contentTypeApplicationJSON = true; } } else { contentTypeApplicationJSON = true; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "MediaTypeHandler"
"public MediaTypeHandler( HttpServletRequest request, HttpServletResponse response ) { String acceptHeader = request.getHeader("Accept"); String contentTypeHeader = request.getHeader("Content-Type"); // accept defaults to JSON if ( acceptHeader != null ) { <MASK>accept = APPLICATION_JSON;</MASK> if ( acceptHeader.contains(APPLICATION_JSON) ) { response.setHeader( "Content-Type", APPLICATION_JSON); } else if ( acceptHeader.contains(APPLICATION_ATOM) ) { accept = APPLICATION_ATOM; } else if ( acceptHeader.contains(TEXT_HTML) ) { accept = TEXT_HTML; } } if ( contentTypeHeader != null ) { if ( contentTypeHeader.equals( FORM_URL_ENCODED ) ) { contentTypeFormUrlEncoded = true; contentTypeApplicationJSON = false; } else if ( contentTypeHeader.equals( APPLICATION_JSON )) { contentTypeFormUrlEncoded = false; contentTypeApplicationJSON = true; } else { if ( !contentTypeHeader.isEmpty() ) throw new UnsupportedMediaTypeException(); // default to JSON contentTypeApplicationJSON = true; } } else { contentTypeApplicationJSON = true; } }"
Inversion-Mutation
megadiff
"public void saveUserAddons(ISdkLog log) { FileOutputStream fos = null; try { String folder = AndroidLocation.getFolder(); File f = new File(folder, SRC_FILENAME); fos = new FileOutputStream(f); Properties props = new Properties(); int count = 0; for (SdkSource s : getSources(SdkSourceCategory.USER_ADDONS)) { props.setProperty(String.format("%s%02d", KEY_SRC, count), s.getUrl()); //$NON-NLS-1$ count++; } props.setProperty(KEY_COUNT, Integer.toString(count)); props.store( fos, "## User Sources for Android tool"); //$NON-NLS-1$ } catch (AndroidLocationException e) { log.error(e, null); } catch (IOException e) { log.error(e, null); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "saveUserAddons"
"public void saveUserAddons(ISdkLog log) { FileOutputStream fos = null; try { String folder = AndroidLocation.getFolder(); File f = new File(folder, SRC_FILENAME); fos = new FileOutputStream(f); Properties props = new Properties(); int count = 0; for (SdkSource s : getSources(SdkSourceCategory.USER_ADDONS)) { <MASK>count++;</MASK> props.setProperty(String.format("%s%02d", KEY_SRC, count), s.getUrl()); //$NON-NLS-1$ } props.setProperty(KEY_COUNT, Integer.toString(count)); props.store( fos, "## User Sources for Android tool"); //$NON-NLS-1$ } catch (AndroidLocationException e) { log.error(e, null); } catch (IOException e) { log.error(e, null); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } } }"
Inversion-Mutation
megadiff
"public synchronized void setOnline(boolean isOnline) throws IOException { // if mode really changed if (online != isOnline) { // switching to ONLINE if (isOnline) { log.info("Setting index back online"); offlineIndex.commit(true); online = true; //invoking offline index invokeOfflineIndex(); } // switching to OFFLINE else { log.info("Setting index offline"); offlineIndex = new OfflinePersistentIndex(handler.getTextAnalyzer(), handler.getSimilarity(), cache, indexingQueue, directoryManager); online = false; flush(); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setOnline"
"public synchronized void setOnline(boolean isOnline) throws IOException { // if mode really changed if (online != isOnline) { // switching to ONLINE if (isOnline) { log.info("Setting index back online"); offlineIndex.commit(true); //invoking offline index invokeOfflineIndex(); <MASK>online = true;</MASK> } // switching to OFFLINE else { log.info("Setting index offline"); offlineIndex = new OfflinePersistentIndex(handler.getTextAnalyzer(), handler.getSimilarity(), cache, indexingQueue, directoryManager); online = false; flush(); } } }"
Inversion-Mutation
megadiff
"public static void main(String[] args) { try { String options[] = { "config:", "help", "loop", "port:", "remote:", "user:", "verbose", "version", }; Options opt = new Options(args, options); opt.handleConfigOption(); boolean verbose = opt.isSet("verbose"); boolean loop = opt.isSet("loop"); if (loop && opt.isSet("remote")) { System.err.println("Option -loop cannot be used with -remote"); System.exit(-1); } if (opt.isSet("help")) { printUsage(System.out); System.exit(0); } if (opt.isSet("version")) { System.out.println("GtpServer " + Version.get()); System.exit(0); } if (! opt.isSet("port")) { System.err.println("Please specify port with option -port"); System.exit(-1); } int port = opt.getInteger("port"); String remoteHost = opt.getString("remote", null); String userFile = opt.getString("user", null); if (userFile != null && remoteHost == null) { System.err.println("Option -user only valid with -remote"); System.exit(-1); } Vector arguments = opt.getArguments(); if (arguments.size() != 1) { printUsage(System.err); System.exit(-1); } String program = (String)arguments.get(0); GtpServer gtpServer = new GtpServer(verbose, loop, program, remoteHost, port, userFile); } catch (Throwable t) { String msg = t.getMessage(); if (msg == null) msg = t.getClass().getName(); System.err.println(msg); System.exit(-1); } }"
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) { try { String options[] = { "config:", "help", "loop", "port:", "remote:", "user:", "verbose", "version", }; Options opt = new Options(args, options); opt.handleConfigOption(); boolean verbose = opt.isSet("verbose"); boolean loop = opt.isSet("loop"); { System.err.println("Option -loop cannot be used with -remote"); System.exit(-1); } <MASK>if (loop && opt.isSet("remote"))</MASK> if (opt.isSet("help")) { printUsage(System.out); System.exit(0); } if (opt.isSet("version")) { System.out.println("GtpServer " + Version.get()); System.exit(0); } if (! opt.isSet("port")) { System.err.println("Please specify port with option -port"); System.exit(-1); } int port = opt.getInteger("port"); String remoteHost = opt.getString("remote", null); String userFile = opt.getString("user", null); if (userFile != null && remoteHost == null) { System.err.println("Option -user only valid with -remote"); System.exit(-1); } Vector arguments = opt.getArguments(); if (arguments.size() != 1) { printUsage(System.err); System.exit(-1); } String program = (String)arguments.get(0); GtpServer gtpServer = new GtpServer(verbose, loop, program, remoteHost, port, userFile); } catch (Throwable t) { String msg = t.getMessage(); if (msg == null) msg = t.getClass().getName(); System.err.println(msg); System.exit(-1); } }"
Inversion-Mutation
megadiff
"Augmentations handleEndElement(QName element, Augmentations augs) { if (DEBUG) { System.out.println("==>handleEndElement:" +element); } // if we are skipping, return if (fSkipValidationDepth >= 0) { // but if this is the top element that we are skipping, // restore the states. if (fSkipValidationDepth == fElementDepth && fSkipValidationDepth > 0) { // set the partial validation depth to the depth of parent fNFullValidationDepth = fSkipValidationDepth-1; fSkipValidationDepth = -1; fElementDepth--; fSubElement = fSubElementStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fNotation = fNotationStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fStrictAssess = fStrictAssessStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawText = fSawTextStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; fSawChildren = fSawChildrenStack[fElementDepth]; } else { fElementDepth--; } // PSVI: validation attempted: // use default values in psvi item for // validation attempted, validity, and error codes // check extra schema constraints on root element if (fElementDepth == -1 && fFullChecking) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // now validate the content of the element processElementContent(element); // Element Locally Valid (Element) // 6 The element information item must be valid with respect to each of the {identity-constraint definitions} as per Identity-constraint Satisfied (3.11.4). // call matchers and de-activate context int oldCount = fMatcherStack.getMatcherCount(); for (int i = oldCount - 1; i >= 0; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.endElement(element, fCurrentElemDecl, fDefaultValue == null ? fValidatedInfo.normalizedValue : fCurrentElemDecl.fDefault.normalizedValue); } if (fMatcherStack.size() > 0) { fMatcherStack.popContext(); } int newCount = fMatcherStack.getMatcherCount(); // handle everything *but* keyref's. for (int i = oldCount - 1; i >= newCount; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if(matcher instanceof Selector.Matcher) { Selector.Matcher selMatcher = (Selector.Matcher)matcher; IdentityConstraint id; if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() != IdentityConstraint.IC_KEYREF) { fValueStoreCache.transplant(id, selMatcher.getInitialDepth()); } } } // now handle keyref's/... for (int i = oldCount - 1; i >= newCount; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if(matcher instanceof Selector.Matcher) { Selector.Matcher selMatcher = (Selector.Matcher)matcher; IdentityConstraint id; if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() == IdentityConstraint.IC_KEYREF) { ValueStoreBase values = fValueStoreCache.getValueStoreFor(id, selMatcher.getInitialDepth()); if (values != null) // nothing to do if nothing matched! values.endDocumentFragment(); } } } fValueStoreCache.endElement(); SchemaGrammar[] grammars = null; // have we reached the end tag of the validation root? if (fElementDepth == 0) { // 7 If the element information item is the validation root, it must be valid per Validation Root Valid (ID/IDREF) (3.3.4). String invIdRef = fValidationState.checkIDRefID(); fValidationState.resetIDTables(); if (invIdRef != null) { reportSchemaError("cvc-id.1", new Object[]{invIdRef}); } // check extra schema constraints if (fFullChecking) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } grammars = fGrammarBucket.getGrammars(); // return the final set of grammars validator ended up with if (fGrammarPool != null) { fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA, grammars); } augs = endElementPSVI(true, grammars, augs); } else { augs = endElementPSVI(false, grammars, augs); // decrease element depth and restore states fElementDepth--; // get the states for the parent element. fSubElement = fSubElementStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fNotation = fNotationStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fStrictAssess = fStrictAssessStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawText = fSawTextStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; fSawChildren = fSawChildrenStack[fElementDepth]; // We should have a stack for whitespace value, and pop it up here. // But when fWhiteSpace != -1, and we see a sub-element, it must be // an error (at least for Schema 1.0). So for valid documents, the // only value we are going to push/pop in the stack is -1. // Here we just mimic the effect of popping -1. -SG fWhiteSpace = -1; // Same for append buffer. Simple types and elements with fixed // value constraint don't allow sub-elements. -SG fAppendBuffer = false; // same here. fUnionType = false; } return augs; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleEndElement"
"Augmentations handleEndElement(QName element, Augmentations augs) { if (DEBUG) { System.out.println("==>handleEndElement:" +element); } // if we are skipping, return if (fSkipValidationDepth >= 0) { // but if this is the top element that we are skipping, // restore the states. if (fSkipValidationDepth == fElementDepth && fSkipValidationDepth > 0) { // set the partial validation depth to the depth of parent fNFullValidationDepth = fSkipValidationDepth-1; fSkipValidationDepth = -1; fElementDepth--; fSubElement = fSubElementStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fNotation = fNotationStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fStrictAssess = fStrictAssessStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawText = fSawTextStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; fSawChildren = fSawChildrenStack[fElementDepth]; } else { fElementDepth--; } // PSVI: validation attempted: // use default values in psvi item for // validation attempted, validity, and error codes // check extra schema constraints on root element if (fElementDepth == -1 && fFullChecking) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // now validate the content of the element processElementContent(element); // Element Locally Valid (Element) // 6 The element information item must be valid with respect to each of the {identity-constraint definitions} as per Identity-constraint Satisfied (3.11.4). // call matchers and de-activate context int oldCount = fMatcherStack.getMatcherCount(); for (int i = oldCount - 1; i >= 0; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.endElement(element, fCurrentElemDecl, fDefaultValue == null ? fValidatedInfo.normalizedValue : fCurrentElemDecl.fDefault.normalizedValue); } if (fMatcherStack.size() > 0) { fMatcherStack.popContext(); } int newCount = fMatcherStack.getMatcherCount(); // handle everything *but* keyref's. for (int i = oldCount - 1; i >= newCount; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if(matcher instanceof Selector.Matcher) { Selector.Matcher selMatcher = (Selector.Matcher)matcher; IdentityConstraint id; if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() != IdentityConstraint.IC_KEYREF) { fValueStoreCache.transplant(id, selMatcher.getInitialDepth()); } } } // now handle keyref's/... for (int i = oldCount - 1; i >= newCount; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if(matcher instanceof Selector.Matcher) { Selector.Matcher selMatcher = (Selector.Matcher)matcher; IdentityConstraint id; if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() == IdentityConstraint.IC_KEYREF) { ValueStoreBase values = fValueStoreCache.getValueStoreFor(id, selMatcher.getInitialDepth()); if (values != null) // nothing to do if nothing matched! values.endDocumentFragment(); } } } fValueStoreCache.endElement(); SchemaGrammar[] grammars = null; // have we reached the end tag of the validation root? if (fElementDepth == 0) { // 7 If the element information item is the validation root, it must be valid per Validation Root Valid (ID/IDREF) (3.3.4). String invIdRef = fValidationState.checkIDRefID(); if (invIdRef != null) { reportSchemaError("cvc-id.1", new Object[]{invIdRef}); } // check extra schema constraints if (fFullChecking) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } <MASK>fValidationState.resetIDTables();</MASK> grammars = fGrammarBucket.getGrammars(); // return the final set of grammars validator ended up with if (fGrammarPool != null) { fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA, grammars); } augs = endElementPSVI(true, grammars, augs); } else { augs = endElementPSVI(false, grammars, augs); // decrease element depth and restore states fElementDepth--; // get the states for the parent element. fSubElement = fSubElementStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fNotation = fNotationStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fStrictAssess = fStrictAssessStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawText = fSawTextStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; fSawChildren = fSawChildrenStack[fElementDepth]; // We should have a stack for whitespace value, and pop it up here. // But when fWhiteSpace != -1, and we see a sub-element, it must be // an error (at least for Schema 1.0). So for valid documents, the // only value we are going to push/pop in the stack is -1. // Here we just mimic the effect of popping -1. -SG fWhiteSpace = -1; // Same for append buffer. Simple types and elements with fixed // value constraint don't allow sub-elements. -SG fAppendBuffer = false; // same here. fUnionType = false; } return augs; }"
Inversion-Mutation
megadiff
"public void run() { try { // Read input BufferedInputStream is = new BufferedInputStream(connection.getInputStream()); InputStreamReader isr = new InputStreamReader(is); int character; StringBuffer process = new StringBuffer(); while((character = isr.read()) != '\n') { process.append((char)character); } String processStr = process.toString(); // Process input // Format: topic;topic;;datetime // let convertedDate be input date String[] processArr = processStr.split(";;"); String[] topicArr = processArr[0].split(";"); BufferedOutputStream os = new BufferedOutputStream(connection.getOutputStream()); OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date convertedDate = dateFormat.parse(processArr[1]); System.out.println(processArr[1]); // Send news - Feedreader for (String topic : topicArr) { for (int i = 0; i < feeds.length; i++) { if (((FeedReader) feeds[i]).getSector().compareTo(topic) == 0) { FeedReader thefeed = ((FeedReader) feeds[i]); for (Story S: thefeed.getStories()) { if (S == null) { continue; } if (convertedDate.compareTo(S.getTimestamp()) < 0) { String title = S.getTitle(); String returnTitle = title ; returnTitle = returnTitle + " ;@; " + S.getDate() + "\n"; osw.write(returnTitle); osw.write("KEYWORDSTART\n"); String returnWords = S.top5keyWords(); osw.write(returnWords); osw.write("KEYWORDEND\n"); } } } } osw.write("NEWSTOP\n"); } osw.write("SPLITINFO\n"); // Send topics - Parse for (String topic : topicArr) { for (int i = 0; i < parsers.length; i++) { if (((Parse) parsers[i]).getSector().compareTo(topic) == 0) { Parse theparse = ((Parse) parsers[i]); for (Topic T: theparse.getTopics()) { if (T == null) { continue; } if (convertedDate.compareTo(T.getTimestamp()) < 0) { String returnTitle = ((Integer) T.getUid()).toString() + ";;\n"; returnTitle += T.getRecentTitle() + ";;\n"; returnTitle += T.getDate() + ";;\n"; returnTitle += T.artsLastHour() + ";;\n"; returnTitle += T.topLinks() + ";;\n"; returnTitle += T.topWords()+ ";;\n"; osw.write(returnTitle); osw.write("SPECTOPS\n"); } } } } osw.write("TOPSTOP\n"); } osw.write("\t"); osw.flush(); } catch (Exception e) { e.printStackTrace(); System.out.println(e); } finally { try { connection.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() { try { // Read input BufferedInputStream is = new BufferedInputStream(connection.getInputStream()); InputStreamReader isr = new InputStreamReader(is); int character; StringBuffer process = new StringBuffer(); while((character = isr.read()) != '\n') { process.append((char)character); } String processStr = process.toString(); // Process input // Format: topic;topic;;datetime // let convertedDate be input date String[] processArr = processStr.split(";;"); String[] topicArr = processArr[0].split(";"); BufferedOutputStream os = new BufferedOutputStream(connection.getOutputStream()); OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date convertedDate = dateFormat.parse(processArr[1]); System.out.println(processArr[1]); // Send news - Feedreader for (String topic : topicArr) { for (int i = 0; i < feeds.length; i++) { if (((FeedReader) feeds[i]).getSector().compareTo(topic) == 0) { FeedReader thefeed = ((FeedReader) feeds[i]); for (Story S: thefeed.getStories()) { if (S == null) { continue; } if (convertedDate.compareTo(S.getTimestamp()) < 0) { String title = S.getTitle(); String returnTitle = title ; returnTitle = returnTitle + " ;@; " + S.getDate() + "\n"; osw.write(returnTitle); osw.write("KEYWORDSTART\n"); String returnWords = S.top5keyWords(); osw.write(returnWords); osw.write("KEYWORDEND\n"); } } } } osw.write("NEWSTOP\n"); } osw.write("SPLITINFO\n"); // Send topics - Parse for (String topic : topicArr) { for (int i = 0; i < parsers.length; i++) { if (((Parse) parsers[i]).getSector().compareTo(topic) == 0) { Parse theparse = ((Parse) parsers[i]); for (Topic T: theparse.getTopics()) { if (T == null) { continue; } if (convertedDate.compareTo(T.getTimestamp()) < 0) { String returnTitle = ((Integer) T.getUid()).toString() + ";;\n"; <MASK>returnTitle += T.artsLastHour() + ";;\n";</MASK> returnTitle += T.getRecentTitle() + ";;\n"; returnTitle += T.getDate() + ";;\n"; returnTitle += T.topLinks() + ";;\n"; returnTitle += T.topWords()+ ";;\n"; osw.write(returnTitle); osw.write("SPECTOPS\n"); } } } } osw.write("TOPSTOP\n"); } osw.write("\t"); osw.flush(); } catch (Exception e) { e.printStackTrace(); System.out.println(e); } finally { try { connection.close(); } catch (IOException e){} } }"
Inversion-Mutation
megadiff
"public MiscDisguise(DisguiseType disguiseType, boolean replaceSounds, int id, int data) { createDisguise(disguiseType, replaceSounds); switch (disguiseType) { // The only disguises which should use a custom data. case FISHING_HOOK: case ARROW: case SPLASH_POTION: case SMALL_FIREBALL: case FIREBALL: case WITHER_SKULL: case PAINTING: case FALLING_BLOCK: break; default: data = -1; break; } if (getType() == DisguiseType.FALLING_BLOCK && id != -1) { this.id = id; } else { this.id = disguiseType.getDefaultId(); } if (data == -1) { if (getType() == DisguiseType.PAINTING) { data = new Random().nextInt(Art.values().length); } else { data = disguiseType.getDefaultData(); } } this.data = data; switch (getType()) { case DROPPED_ITEM: if (id > 0) { ((DroppedItemWatcher) getWatcher()).setItemStack(new ItemStack(id, data)); } break; case FALLING_BLOCK: ((FallingBlockWatcher) getWatcher()).setBlock(new ItemStack(this.id, 1, (short) this.data)); break; case PAINTING: ((PaintingWatcher) getWatcher()).setArtId(this.data); break; case SPLASH_POTION: ((SplashPotionWatcher) getWatcher()).setPotionId(this.data); break; default: break; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "MiscDisguise"
"public MiscDisguise(DisguiseType disguiseType, boolean replaceSounds, int id, int data) { switch (disguiseType) { // The only disguises which should use a custom data. case FISHING_HOOK: case ARROW: case SPLASH_POTION: case SMALL_FIREBALL: case FIREBALL: case WITHER_SKULL: case PAINTING: case FALLING_BLOCK: break; default: data = -1; break; } if (getType() == DisguiseType.FALLING_BLOCK && id != -1) { this.id = id; } else { this.id = disguiseType.getDefaultId(); } if (data == -1) { if (getType() == DisguiseType.PAINTING) { data = new Random().nextInt(Art.values().length); } else { data = disguiseType.getDefaultData(); } } this.data = data; <MASK>createDisguise(disguiseType, replaceSounds);</MASK> switch (getType()) { case DROPPED_ITEM: if (id > 0) { ((DroppedItemWatcher) getWatcher()).setItemStack(new ItemStack(id, data)); } break; case FALLING_BLOCK: ((FallingBlockWatcher) getWatcher()).setBlock(new ItemStack(this.id, 1, (short) this.data)); break; case PAINTING: ((PaintingWatcher) getWatcher()).setArtId(this.data); break; case SPLASH_POTION: ((SplashPotionWatcher) getWatcher()).setPotionId(this.data); break; default: break; } }"
Inversion-Mutation
megadiff
"public void ensureOutOfSync(final IFile file) { modifyInFileSystem(file); touchInFilesystem(file); assertTrue("File not out of sync: " + file.getLocation().toOSString(), file.getLocation().toFile().lastModified() != file.getLocalTimeStamp()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "ensureOutOfSync"
"public void ensureOutOfSync(final IFile file) { <MASK>touchInFilesystem(file);</MASK> modifyInFileSystem(file); assertTrue("File not out of sync: " + file.getLocation().toOSString(), file.getLocation().toFile().lastModified() != file.getLocalTimeStamp()); }"
Inversion-Mutation
megadiff
"public synchronized void setMetadata(T subject, String metadataKey, MetadataValue newMetadataValue) { Validate.notNull(newMetadataValue, "Value cannot be null"); Plugin owningPlugin = newMetadataValue.getOwningPlugin(); Validate.notNull(owningPlugin, "Plugin cannot be null"); String key = disambiguate(subject, metadataKey); Map<Plugin, MetadataValue> entry = metadataMap.get(key); if (entry == null) { entry = new WeakHashMap<Plugin, MetadataValue>(1); metadataMap.put(key, entry); } entry.put(owningPlugin, newMetadataValue); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setMetadata"
"public synchronized void setMetadata(T subject, String metadataKey, MetadataValue newMetadataValue) { <MASK>Plugin owningPlugin = newMetadataValue.getOwningPlugin();</MASK> Validate.notNull(newMetadataValue, "Value cannot be null"); Validate.notNull(owningPlugin, "Plugin cannot be null"); String key = disambiguate(subject, metadataKey); Map<Plugin, MetadataValue> entry = metadataMap.get(key); if (entry == null) { entry = new WeakHashMap<Plugin, MetadataValue>(1); metadataMap.put(key, entry); } entry.put(owningPlugin, newMetadataValue); }"
Inversion-Mutation
megadiff
"public Gson create() { List<TypeAdapter.Factory> factories = new ArrayList<TypeAdapter.Factory>(); factories.addAll(this.factories); Collections.reverse(factories); factories.addAll(this.hierarchyFactories); addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories); return new Gson(excluder, fieldNamingPolicy, instanceCreators, serializeNulls, complexMapKeySerialization, generateNonExecutableJson, escapeHtmlChars, prettyPrinting, serializeSpecialFloatingPointValues, longSerializationPolicy, factories); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "create"
"public Gson create() { List<TypeAdapter.Factory> factories = new ArrayList<TypeAdapter.Factory>(); <MASK>factories.addAll(this.hierarchyFactories);</MASK> factories.addAll(this.factories); Collections.reverse(factories); addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories); return new Gson(excluder, fieldNamingPolicy, instanceCreators, serializeNulls, complexMapKeySerialization, generateNonExecutableJson, escapeHtmlChars, prettyPrinting, serializeSpecialFloatingPointValues, longSerializationPolicy, factories); }"
Inversion-Mutation
megadiff
"protected JComponent createToolbar() { _toolbar = new FolderToolBar(true, _folderChooser.getRecentList()); _folderToolbarListener = new FolderToolBarListener() { // ------------------------------------------------------------------------------ // Implementation of FolderToolBarListener // ------------------------------------------------------------------------------ public void deleteFolderButtonClicked() { // make sure user really wants to do this String text; TreePath path = _fileSystemTree.getSelectionPaths()[0]; List selection = getSelectedFolders(new TreePath[]{path}); final ResourceBundle resourceBundle = FolderChooserResource.getResourceBundle(Locale.getDefault()); if (selection.size() > 1) { text = MessageFormat.format( resourceBundle.getString("FolderChooser.delete.message2"), selection.size()); } else { text = resourceBundle.getString("FolderChooser.delete.message1"); } final String title = resourceBundle.getString("FolderChooser.delete.title"); int result = JOptionPane.showConfirmDialog(_folderChooser, text, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (result == JOptionPane.OK_OPTION) { TreePath parentPath = path.getParentPath(); Object parentObject = parentPath.getLastPathComponent(); Object deletedObject = path.getLastPathComponent(); int index = _fileSystemTree.getModel().getIndexOfChild(parentObject, deletedObject); for (Object s : selection) { File f = (File) s; recursiveDelete(f); } ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).removePath(path, index, deletedObject); TreePath pathToSelect = parentPath; if (index >= ((MutableTreeNode) parentObject).getChildCount()) { index = ((MutableTreeNode) parentObject).getChildCount() - 1; } if (index > 0) { pathToSelect = parentPath.pathByAddingChild(((MutableTreeNode) parentObject).getChildAt(index)); } _fileSystemTree.setSelectionPath(pathToSelect); _fileSystemTree.scrollPathToVisible(pathToSelect); } } /** * Recursively deletes a file/directory. * * @param file The file/folder to delete * @return <code>true</code> only if the file and all children were successfully deleted. */ public final boolean recursiveDelete(File file) { if (isFileSystem(file)) { if (file.isDirectory()) { // delete all children first File[] children = FileSystemView.getFileSystemView().getFiles(file, false); for (File f : children) { if (!recursiveDelete(f)) { return false; } } // delete this file. return file.delete(); } else { return file.delete(); } } else { return false; } } public void newFolderButtonClicked() { // get the selected folder TreePath[] paths = _fileSystemTree.getSelectionPaths(); List selection = getSelectedFolders(paths); if (selection.size() > 1 || selection.size() == 0) return; // should never happen File parent = (File) selection.get(0); final ResourceBundle resourceBundle = FolderChooserResource.getResourceBundle(Locale.getDefault()); String folderName = JOptionPane.showInputDialog(_folderChooser, resourceBundle.getString("FolderChooser.new.folderName"), resourceBundle.getString("FolderChooser.new.title"), JOptionPane.OK_CANCEL_OPTION | JOptionPane.QUESTION_MESSAGE); if (folderName != null) { folderName = eraseBlankInTheEnd(folderName); File newFolder = new File(parent, folderName); boolean success = newFolder.mkdir(); TreePath parentPath = paths[0]; boolean isExpanded = _fileSystemTree.isExpanded(parentPath); if (!isExpanded) { // expand it first _fileSystemTree.expandPath(parentPath); } LazyMutableTreeNode parentTreeNode = (LazyMutableTreeNode) parentPath.getLastPathComponent(); BasicFileSystemTreeNode child = BasicFileSystemTreeNode.createFileSystemTreeNode(newFolder, _folderChooser); // child.setParent(parentTreeNode); if (success) { parentTreeNode.clear(); int insertIndex = _fileSystemTree.getModel().getIndexOfChild(parentTreeNode, child); if (insertIndex != -1) { // ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).insertNodeInto(child, parentTreeNode, insertIndex); ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).nodeStructureChanged(parentTreeNode); // ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).addPath(parentPath, insertIndex, child); } } TreePath newPath = parentPath.pathByAddingChild(child); _fileSystemTree.setSelectionPath(newPath); _fileSystemTree.scrollPathToVisible(newPath); } } private String eraseBlankInTheEnd(String folderName) { int i = folderName.length() - 1; for (; i >= 0; i--) { char c = folderName.charAt(i); if (c != ' ' && c != '\t') { break; } } if (i < 0) { return null; } return folderName.substring(0, i + 1); } public void myDocumentsButtonClicked() { File myDocuments = FileSystemView.getFileSystemView().getDefaultDirectory(); ensureFileIsVisible(myDocuments, true); } public void desktopButtonClicked() { File desktop = FileSystemView.getFileSystemView().getHomeDirectory(); ensureFileIsVisible(desktop, true); } public void refreshButtonClicked() { File folder = _folderChooser.getSelectedFolder(); _folderChooser.updateUI(); while (folder != null) { if (folder.exists()) { _folderChooser.getUI().ensureFileIsVisible(_folderChooser, folder); break; } else { folder = folder.getParentFile(); if (folder == null) { break; } } } } public void recentFolderSelected(final File file) { new Thread(new Runnable() { public void run() { setWaitCursor(true); try { ensureFileIsVisible(file, true); } finally { setWaitCursor(false); } } }).start(); } private Cursor m_oldCursor; private void setWaitCursor(boolean isWait) { Window parentWindow = SwingUtilities.getWindowAncestor(_folderChooser); if (isWait) { Cursor hourglassCursor = new Cursor(Cursor.WAIT_CURSOR); m_oldCursor = parentWindow.getCursor(); parentWindow.setCursor(hourglassCursor); } else { if (m_oldCursor != null) { parentWindow.setCursor(m_oldCursor); m_oldCursor = null; } } } public List getSelectedFolders() { TreePath[] paths = _fileSystemTree.getSelectionPaths(); return getSelectedFolders(paths); } public List getSelectedFolders(TreePath[] paths) { if (paths == null || paths.length == 0) return new ArrayList(); List<File> folders = new ArrayList<File>(paths.length); for (TreePath path : paths) { BasicFileSystemTreeNode f = (BasicFileSystemTreeNode) path.getLastPathComponent(); folders.add(f.getFile()); } return folders; } }; _toolbar.addListener(_folderToolbarListener); updateToolbarButtons(); return _toolbar; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createToolbar"
"protected JComponent createToolbar() { _toolbar = new FolderToolBar(true, _folderChooser.getRecentList()); _folderToolbarListener = new FolderToolBarListener() { // ------------------------------------------------------------------------------ // Implementation of FolderToolBarListener // ------------------------------------------------------------------------------ public void deleteFolderButtonClicked() { // make sure user really wants to do this String text; TreePath path = _fileSystemTree.getSelectionPaths()[0]; List selection = getSelectedFolders(new TreePath[]{path}); final ResourceBundle resourceBundle = FolderChooserResource.getResourceBundle(Locale.getDefault()); if (selection.size() > 1) { text = MessageFormat.format( resourceBundle.getString("FolderChooser.delete.message2"), selection.size()); } else { text = resourceBundle.getString("FolderChooser.delete.message1"); } final String title = resourceBundle.getString("FolderChooser.delete.title"); int result = JOptionPane.showConfirmDialog(_folderChooser, text, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (result == JOptionPane.OK_OPTION) { TreePath parentPath = path.getParentPath(); Object parentObject = parentPath.getLastPathComponent(); Object deletedObject = path.getLastPathComponent(); int index = _fileSystemTree.getModel().getIndexOfChild(parentObject, deletedObject); for (Object s : selection) { File f = (File) s; recursiveDelete(f); } ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).removePath(path, index, deletedObject); TreePath pathToSelect = parentPath; if (index >= ((MutableTreeNode) parentObject).getChildCount()) { index = ((MutableTreeNode) parentObject).getChildCount() - 1; } if (index > 0) { pathToSelect = parentPath.pathByAddingChild(((MutableTreeNode) parentObject).getChildAt(index)); } _fileSystemTree.setSelectionPath(pathToSelect); _fileSystemTree.scrollPathToVisible(pathToSelect); } } /** * Recursively deletes a file/directory. * * @param file The file/folder to delete * @return <code>true</code> only if the file and all children were successfully deleted. */ public final boolean recursiveDelete(File file) { if (isFileSystem(file)) { if (file.isDirectory()) { // delete all children first File[] children = FileSystemView.getFileSystemView().getFiles(file, false); for (File f : children) { if (!recursiveDelete(f)) { return false; } } // delete this file. return file.delete(); } else { return file.delete(); } } else { return false; } } public void newFolderButtonClicked() { // get the selected folder TreePath[] paths = _fileSystemTree.getSelectionPaths(); List selection = getSelectedFolders(paths); if (selection.size() > 1 || selection.size() == 0) return; // should never happen File parent = (File) selection.get(0); final ResourceBundle resourceBundle = FolderChooserResource.getResourceBundle(Locale.getDefault()); String folderName = JOptionPane.showInputDialog(_folderChooser, resourceBundle.getString("FolderChooser.new.folderName"), resourceBundle.getString("FolderChooser.new.title"), JOptionPane.OK_CANCEL_OPTION | JOptionPane.QUESTION_MESSAGE); <MASK>folderName = eraseBlankInTheEnd(folderName);</MASK> if (folderName != null) { File newFolder = new File(parent, folderName); boolean success = newFolder.mkdir(); TreePath parentPath = paths[0]; boolean isExpanded = _fileSystemTree.isExpanded(parentPath); if (!isExpanded) { // expand it first _fileSystemTree.expandPath(parentPath); } LazyMutableTreeNode parentTreeNode = (LazyMutableTreeNode) parentPath.getLastPathComponent(); BasicFileSystemTreeNode child = BasicFileSystemTreeNode.createFileSystemTreeNode(newFolder, _folderChooser); // child.setParent(parentTreeNode); if (success) { parentTreeNode.clear(); int insertIndex = _fileSystemTree.getModel().getIndexOfChild(parentTreeNode, child); if (insertIndex != -1) { // ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).insertNodeInto(child, parentTreeNode, insertIndex); ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).nodeStructureChanged(parentTreeNode); // ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).addPath(parentPath, insertIndex, child); } } TreePath newPath = parentPath.pathByAddingChild(child); _fileSystemTree.setSelectionPath(newPath); _fileSystemTree.scrollPathToVisible(newPath); } } private String eraseBlankInTheEnd(String folderName) { int i = folderName.length() - 1; for (; i >= 0; i--) { char c = folderName.charAt(i); if (c != ' ' && c != '\t') { break; } } if (i < 0) { return null; } return folderName.substring(0, i + 1); } public void myDocumentsButtonClicked() { File myDocuments = FileSystemView.getFileSystemView().getDefaultDirectory(); ensureFileIsVisible(myDocuments, true); } public void desktopButtonClicked() { File desktop = FileSystemView.getFileSystemView().getHomeDirectory(); ensureFileIsVisible(desktop, true); } public void refreshButtonClicked() { File folder = _folderChooser.getSelectedFolder(); _folderChooser.updateUI(); while (folder != null) { if (folder.exists()) { _folderChooser.getUI().ensureFileIsVisible(_folderChooser, folder); break; } else { folder = folder.getParentFile(); if (folder == null) { break; } } } } public void recentFolderSelected(final File file) { new Thread(new Runnable() { public void run() { setWaitCursor(true); try { ensureFileIsVisible(file, true); } finally { setWaitCursor(false); } } }).start(); } private Cursor m_oldCursor; private void setWaitCursor(boolean isWait) { Window parentWindow = SwingUtilities.getWindowAncestor(_folderChooser); if (isWait) { Cursor hourglassCursor = new Cursor(Cursor.WAIT_CURSOR); m_oldCursor = parentWindow.getCursor(); parentWindow.setCursor(hourglassCursor); } else { if (m_oldCursor != null) { parentWindow.setCursor(m_oldCursor); m_oldCursor = null; } } } public List getSelectedFolders() { TreePath[] paths = _fileSystemTree.getSelectionPaths(); return getSelectedFolders(paths); } public List getSelectedFolders(TreePath[] paths) { if (paths == null || paths.length == 0) return new ArrayList(); List<File> folders = new ArrayList<File>(paths.length); for (TreePath path : paths) { BasicFileSystemTreeNode f = (BasicFileSystemTreeNode) path.getLastPathComponent(); folders.add(f.getFile()); } return folders; } }; _toolbar.addListener(_folderToolbarListener); updateToolbarButtons(); return _toolbar; }"
Inversion-Mutation
megadiff
"public void newFolderButtonClicked() { // get the selected folder TreePath[] paths = _fileSystemTree.getSelectionPaths(); List selection = getSelectedFolders(paths); if (selection.size() > 1 || selection.size() == 0) return; // should never happen File parent = (File) selection.get(0); final ResourceBundle resourceBundle = FolderChooserResource.getResourceBundle(Locale.getDefault()); String folderName = JOptionPane.showInputDialog(_folderChooser, resourceBundle.getString("FolderChooser.new.folderName"), resourceBundle.getString("FolderChooser.new.title"), JOptionPane.OK_CANCEL_OPTION | JOptionPane.QUESTION_MESSAGE); if (folderName != null) { folderName = eraseBlankInTheEnd(folderName); File newFolder = new File(parent, folderName); boolean success = newFolder.mkdir(); TreePath parentPath = paths[0]; boolean isExpanded = _fileSystemTree.isExpanded(parentPath); if (!isExpanded) { // expand it first _fileSystemTree.expandPath(parentPath); } LazyMutableTreeNode parentTreeNode = (LazyMutableTreeNode) parentPath.getLastPathComponent(); BasicFileSystemTreeNode child = BasicFileSystemTreeNode.createFileSystemTreeNode(newFolder, _folderChooser); // child.setParent(parentTreeNode); if (success) { parentTreeNode.clear(); int insertIndex = _fileSystemTree.getModel().getIndexOfChild(parentTreeNode, child); if (insertIndex != -1) { // ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).insertNodeInto(child, parentTreeNode, insertIndex); ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).nodeStructureChanged(parentTreeNode); // ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).addPath(parentPath, insertIndex, child); } } TreePath newPath = parentPath.pathByAddingChild(child); _fileSystemTree.setSelectionPath(newPath); _fileSystemTree.scrollPathToVisible(newPath); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "newFolderButtonClicked"
"public void newFolderButtonClicked() { // get the selected folder TreePath[] paths = _fileSystemTree.getSelectionPaths(); List selection = getSelectedFolders(paths); if (selection.size() > 1 || selection.size() == 0) return; // should never happen File parent = (File) selection.get(0); final ResourceBundle resourceBundle = FolderChooserResource.getResourceBundle(Locale.getDefault()); String folderName = JOptionPane.showInputDialog(_folderChooser, resourceBundle.getString("FolderChooser.new.folderName"), resourceBundle.getString("FolderChooser.new.title"), JOptionPane.OK_CANCEL_OPTION | JOptionPane.QUESTION_MESSAGE); <MASK>folderName = eraseBlankInTheEnd(folderName);</MASK> if (folderName != null) { File newFolder = new File(parent, folderName); boolean success = newFolder.mkdir(); TreePath parentPath = paths[0]; boolean isExpanded = _fileSystemTree.isExpanded(parentPath); if (!isExpanded) { // expand it first _fileSystemTree.expandPath(parentPath); } LazyMutableTreeNode parentTreeNode = (LazyMutableTreeNode) parentPath.getLastPathComponent(); BasicFileSystemTreeNode child = BasicFileSystemTreeNode.createFileSystemTreeNode(newFolder, _folderChooser); // child.setParent(parentTreeNode); if (success) { parentTreeNode.clear(); int insertIndex = _fileSystemTree.getModel().getIndexOfChild(parentTreeNode, child); if (insertIndex != -1) { // ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).insertNodeInto(child, parentTreeNode, insertIndex); ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).nodeStructureChanged(parentTreeNode); // ((BasicFileSystemTreeModel) _fileSystemTree.getModel()).addPath(parentPath, insertIndex, child); } } TreePath newPath = parentPath.pathByAddingChild(child); _fileSystemTree.setSelectionPath(newPath); _fileSystemTree.scrollPathToVisible(newPath); } }"
Inversion-Mutation
megadiff
"@Override public Value M(Application app, RunTimeState state) { Log.debug("M Application called,state is:"+state.toString()); Value para = (Value) M(app.param,state); boolean issnaped = state.snapshotState(); AnonymousFunction fun = (AnonymousFunction) M(app.func, state); Value rslt = functionCall(fun, para, state); if(issnaped) { state.recover(); } return rslt; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "M"
"@Override public Value M(Application app, RunTimeState state) { Log.debug("M Application called,state is:"+state.toString()); boolean issnaped = state.snapshotState(); AnonymousFunction fun = (AnonymousFunction) M(app.func, state); <MASK>Value para = (Value) M(app.param,state);</MASK> Value rslt = functionCall(fun, para, state); if(issnaped) { state.recover(); } return rslt; }"
Inversion-Mutation
megadiff
"@EventHandler public void playerPicksUpItem(PlayerPickupItemEvent event){ if (event.isCancelled()){ return; } Player player = event.getPlayer(); Item item = event.getItem(); ItemStack stack = item.getItemStack(); int maxItems = Config.getItemMax(event.getPlayer(), stack.getType(), stack.getDurability()); if (maxItems == 0){ event.setCancelled(true); } else if (maxItems > Config.ITEM_DEFAULT){ int addAmount = addItemsToInventory(player, item); if (addAmount == 0){ collectItem(player, item); item.remove(); } else { stack.setAmount(addAmount); } event.setCancelled(true); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "playerPicksUpItem"
"@EventHandler public void playerPicksUpItem(PlayerPickupItemEvent event){ if (event.isCancelled()){ return; } Player player = event.getPlayer(); Item item = event.getItem(); ItemStack stack = item.getItemStack(); int maxItems = Config.getItemMax(event.getPlayer(), stack.getType(), stack.getDurability()); if (maxItems == 0){ event.setCancelled(true); } else if (maxItems > Config.ITEM_DEFAULT){ int addAmount = addItemsToInventory(player, item); <MASK>collectItem(player, item);</MASK> if (addAmount == 0){ item.remove(); } else { stack.setAmount(addAmount); } event.setCancelled(true); } }"
Inversion-Mutation
megadiff
"@Override public void onAttachedToWindow() { mPrevRotation = Util.getDisplayRotation((Activity) getContext()); // check if there is any rotation before the view is attached to window int currentOrientation = getResources().getConfiguration().orientation; if (mInitialOrientation == currentOrientation) { return; } if (mInitialOrientation == Configuration.ORIENTATION_LANDSCAPE && currentOrientation == Configuration.ORIENTATION_PORTRAIT) { rotateLayout(true); } else if (mInitialOrientation == Configuration.ORIENTATION_PORTRAIT && currentOrientation == Configuration.ORIENTATION_LANDSCAPE) { rotateLayout(false); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onAttachedToWindow"
"@Override public void onAttachedToWindow() { // check if there is any rotation before the view is attached to window int currentOrientation = getResources().getConfiguration().orientation; if (mInitialOrientation == currentOrientation) { return; } if (mInitialOrientation == Configuration.ORIENTATION_LANDSCAPE && currentOrientation == Configuration.ORIENTATION_PORTRAIT) { rotateLayout(true); } else if (mInitialOrientation == Configuration.ORIENTATION_PORTRAIT && currentOrientation == Configuration.ORIENTATION_LANDSCAPE) { rotateLayout(false); } <MASK>mPrevRotation = Util.getDisplayRotation((Activity) getContext());</MASK> }"
Inversion-Mutation
megadiff
"protected void connect () throws IOException { // if we're already connected, we freak out if (_channel != null) { throw new IOException("Already connected."); } // look up the address of the target server InetAddress host = InetAddress.getByName(_client.getHostname()); // obtain the list of available ports on which to attempt our // client connection and determine our preferred port String pportKey = _client.getHostname() + ".preferred_port"; int[] ports = _client.getPorts(); int pport = PresentsPrefs.config.getValue(pportKey, ports[0]); int ppidx = Math.max(0, IntListUtil.indexOf(ports, pport)); // try connecting on each of the ports in succession for (int ii = 0; ii < ports.length; ii++) { int port = ports[(ii+ppidx)%ports.length]; int nextPort = ports[(ii+ppidx+1)%ports.length]; Log.info("Connecting [host=" + host + ", port=" + port + "]."); InetSocketAddress addr = new InetSocketAddress(host, port); try { synchronized (Communicator.this) { clearPPI(true); _prefPortInterval = new PrefPortInterval(pportKey, port, nextPort); _channel = SocketChannel.open(addr); _prefPortInterval.schedule(PREF_PORT_DELAY); } break; } catch (IOException ioe) { if (ioe instanceof ConnectException && ii < (ports.length-1)) { _client.reportLogonTribulations( new LogonException( AuthCodes.TRYING_NEXT_PORT, true)); continue; // try the next port } throw ioe; } } _channel.configureBlocking(true); // our messages are framed (preceded by their length), so we // use these helper streams to manage the framing _fin = new FramedInputStream(); _fout = new FramingOutputStream(); // create our object input and output streams _oin = new ObjectInputStream(_fin); _oin.setClassLoader(_loader); _oout = new ObjectOutputStream(_fout); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "connect"
"protected void connect () throws IOException { // if we're already connected, we freak out if (_channel != null) { throw new IOException("Already connected."); } // look up the address of the target server InetAddress host = InetAddress.getByName(_client.getHostname()); // obtain the list of available ports on which to attempt our // client connection and determine our preferred port String pportKey = _client.getHostname() + ".preferred_port"; int[] ports = _client.getPorts(); int pport = PresentsPrefs.config.getValue(pportKey, ports[0]); int ppidx = Math.max(0, IntListUtil.indexOf(ports, pport)); // try connecting on each of the ports in succession for (int ii = 0; ii < ports.length; ii++) { int port = ports[(ii+ppidx)%ports.length]; int nextPort = ports[(ii+ppidx+1)%ports.length]; Log.info("Connecting [host=" + host + ", port=" + port + "]."); InetSocketAddress addr = new InetSocketAddress(host, port); try { <MASK>_channel = SocketChannel.open(addr);</MASK> synchronized (Communicator.this) { clearPPI(true); _prefPortInterval = new PrefPortInterval(pportKey, port, nextPort); _prefPortInterval.schedule(PREF_PORT_DELAY); } break; } catch (IOException ioe) { if (ioe instanceof ConnectException && ii < (ports.length-1)) { _client.reportLogonTribulations( new LogonException( AuthCodes.TRYING_NEXT_PORT, true)); continue; // try the next port } throw ioe; } } _channel.configureBlocking(true); // our messages are framed (preceded by their length), so we // use these helper streams to manage the framing _fin = new FramedInputStream(); _fout = new FramingOutputStream(); // create our object input and output streams _oin = new ObjectInputStream(_fin); _oin.setClassLoader(_loader); _oout = new ObjectOutputStream(_fout); }"
Inversion-Mutation
megadiff
"public EnvironmentObject(String name, UpdatableLocation center) { super(); setLocation(center); init(name); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "EnvironmentObject"
"public EnvironmentObject(String name, UpdatableLocation center) { super(); <MASK>init(name);</MASK> setLocation(center); }"
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
"public void run() { Image image; while (!interrupted()) { try { Log.d("Input", "Checking for connection in monitor"); monitor.connectionCheck(protocol.getCameraId()); Log.d("Input", "In started to fetch images"); image = protocol.awaitImage(); monitor.putImage(image, protocol.getCameraId()); } catch (IOException e) { try { protocol.disconnect(); } catch (IOException ioe) { System.err.println("Could not disconnect some how."); interrupt(); } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { Image image; while (!interrupted()) { try { Log.d("Input", "Checking for connection in monitor"); monitor.connectionCheck(protocol.getCameraId()); Log.d("Input", "In started to fetch images"); image = protocol.awaitImage(); monitor.putImage(image, protocol.getCameraId()); } catch (IOException e) { try { protocol.disconnect(); } catch (IOException ioe) { System.err.println("Could not disconnect some how."); } <MASK>interrupt();</MASK> } } }"
Inversion-Mutation
megadiff
"public void doCommand(Command c){ boolean b = false; if (c.getCommandWord().equals(CommandWords.UNDO)){ c = playerHistory.undo(); b = true; } else if (c.getCommandWord().equals(CommandWords.REDO)){ c = playerHistory.redo(); b = true; } if(c==null){ return; //TODO tell view about it } if (c.getCommandWord().equals(CommandWords.GO)){ Direction d = (Direction) c.getSecondWord(); Room r = currentRoom.getExit(d); if(r!=null){ currentRoom = r; } // else error TODO if(b == false){ playerHistory.addStep(c); } } else if (c.getCommandWord().equals(CommandWords.FIGHT)){ Monster m = currentRoom.getMonster(); if(m==null){ System.out.println("Nothing to Fight!"); //should probably call the view here..shouldn't be a system.out in this class } else { //if(this.getBestItem().compareTo(m.getBestItem()) == 1){ m.updateHealth(this.getBestItem().getValue()); this.updateHealth(m.getBestItem().getValue()); if(m.getHealth()<=0){ currentRoom.removeMonster(m); } } } else if (c.getCommandWord().equals(CommandWords.HELP)){ System.out.println("You are lost. You are alone. You wander around in a cave.\n"); System.out.println("Your command words are:"); System.out.println("GO, PICKUP, DROP, UNDO, REDO, FIGHT, HELP, QUIT"); //HELP may be implemented in another class. } else if (c.getCommandWord().equals(CommandWords.PICKUP)){ Item i = (Item) c.getSecondWord(); if(currentRoom.hasItem(i)){ addItem(i); currentRoom.removeItem(i); } if(b == false){ playerHistory.addStep(c); } } else if (c.getCommandWord().equals(CommandWords.DROP)){ Item i = (Item) c.getSecondWord(); if(currentRoom.hasItem(i)){ removeItem(i); } currentRoom.addItem(i); if(b == false){ playerHistory.addStep(c); } } else { //TODO some sort of extraneous error checking }//QUIT command does not get passed to the player }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doCommand"
"public void doCommand(Command c){ boolean b = false; if (c.getCommandWord().equals(CommandWords.UNDO)){ c = playerHistory.undo(); b = true; } else if (c.getCommandWord().equals(CommandWords.REDO)){ c = playerHistory.redo(); b = true; } if(c==null){ return; //TODO tell view about it } if (c.getCommandWord().equals(CommandWords.GO)){ Direction d = (Direction) c.getSecondWord(); Room r = currentRoom.getExit(d); if(r!=null){ currentRoom = r; } // else error TODO if(b == false){ playerHistory.addStep(c); } } else if (c.getCommandWord().equals(CommandWords.FIGHT)){ Monster m = currentRoom.getMonster(); if(m==null){ System.out.println("Nothing to Fight!"); //should probably call the view here..shouldn't be a system.out in this class } else { //if(this.getBestItem().compareTo(m.getBestItem()) == 1){ m.updateHealth(this.getBestItem().getValue()); this.updateHealth(m.getBestItem().getValue()); if(m.getHealth()<=0){ currentRoom.removeMonster(m); } } } else if (c.getCommandWord().equals(CommandWords.HELP)){ System.out.println("You are lost. You are alone. You wander around in a cave.\n"); System.out.println("Your command words are:"); System.out.println("GO, PICKUP, DROP, UNDO, REDO, FIGHT, HELP, QUIT"); //HELP may be implemented in another class. } else if (c.getCommandWord().equals(CommandWords.PICKUP)){ Item i = (Item) c.getSecondWord(); if(currentRoom.hasItem(i)){ addItem(i); currentRoom.removeItem(i); } if(b == false){ playerHistory.addStep(c); } } else if (c.getCommandWord().equals(CommandWords.DROP)){ Item i = (Item) c.getSecondWord(); if(currentRoom.hasItem(i)){ removeItem(i); <MASK>currentRoom.addItem(i);</MASK> } if(b == false){ playerHistory.addStep(c); } } else { //TODO some sort of extraneous error checking }//QUIT command does not get passed to the player }"
Inversion-Mutation
megadiff
"public File getCachePath(URL url) { // this.log.logFinest("plasmaHTCache: getCachePath: IN=" + url.toString()); String remotePath = url.getFile(); if (!remotePath.startsWith("/")) { remotePath = "/" + remotePath; } if (remotePath.endsWith("/")) { remotePath = remotePath + "ndx"; } remotePath = remotePath.replaceAll("[?&:]", "_"); // yes this is not reversible, but that is not needed int port = url.getPort(); if (port < 0) { if (url.getProtocol().equalsIgnoreCase("http")) port = 80; else if (url.getProtocol().equalsIgnoreCase("https")) port = 443; else if (url.getProtocol().equalsIgnoreCase("ftp")) port = 21; } if (port == 80) { return new File(this.cachePath, url.getHost() + remotePath); } else { return new File(this.cachePath, url.getHost() + "!" + port + remotePath); } /* File path; if (port == 80) { path = new File(this.cachePath, url.getHost() + remotePath); } else { path = new File(this.cachePath, url.getHost() + "!" + port + remotePath); } this.log.logFinest("plasmaHTCache: getCachePath: OUT=" + path.toString()); return path;*/ }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getCachePath"
"public File getCachePath(URL url) { // this.log.logFinest("plasmaHTCache: getCachePath: IN=" + url.toString()); String remotePath = url.getFile(); <MASK>if (remotePath.endsWith("/")) { remotePath = remotePath + "ndx"; }</MASK> if (!remotePath.startsWith("/")) { remotePath = "/" + remotePath; } remotePath = remotePath.replaceAll("[?&:]", "_"); // yes this is not reversible, but that is not needed int port = url.getPort(); if (port < 0) { if (url.getProtocol().equalsIgnoreCase("http")) port = 80; else if (url.getProtocol().equalsIgnoreCase("https")) port = 443; else if (url.getProtocol().equalsIgnoreCase("ftp")) port = 21; } if (port == 80) { return new File(this.cachePath, url.getHost() + remotePath); } else { return new File(this.cachePath, url.getHost() + "!" + port + remotePath); } /* File path; if (port == 80) { path = new File(this.cachePath, url.getHost() + remotePath); } else { path = new File(this.cachePath, url.getHost() + "!" + port + remotePath); } this.log.logFinest("plasmaHTCache: getCachePath: OUT=" + path.toString()); return path;*/ }"
Inversion-Mutation
megadiff
"public void paintAsArea(PaintContext pc, SingleTile t) { //#if polish.api.bigstyles WayDescription wayDesc = Legend.getWayDescription(type); //#else WayDescription wayDesc = Legend.getWayDescription((short) (type & 0xff)); //#endif //#if polish.api.bigstyles byte om = Legend.getWayOverviewMode(type); //#else byte om = Legend.getWayOverviewMode((short) (type & 0xff)); //#endif switch (om & Legend.OM_MODE_MASK) { case Legend.OM_SHOWNORMAL: // if not in Overview Mode check for scale if (pc.scale > wayDesc.maxScale * Configuration.getDetailBoostMultiplier()) { return; } // building areas if (wayDesc.isBuilding()) { if (!Configuration.getCfgBitState(Configuration.CFGBIT_BUILDINGS)) { return; } // non-building areas } else { if(wayDesc.hideable && !Configuration.getCfgBitState(Configuration.CFGBIT_AREAS)) { return; } } break; case Legend.OM_HIDE: if (wayDesc.hideable) { return; } break; } switch (om & Legend.OM_NAME_MASK) { case Legend.OM_WITH_NAMEPART: if (nameIdx == -1) { return; } String name = pc.trace.getName(nameIdx); String url = pc.trace.getName(urlIdx); if (name == null) { return; } if (name.toUpperCase().indexOf(Legend.get0Poi1Area2WayNamePart((byte) 1).toUpperCase()) == -1) { return; } break; case Legend.OM_WITH_NAME: if (nameIdx == -1) { return; } break; case Legend.OM_NO_NAME: if (nameIdx != -1) { return; } break; } Projection p = pc.getP(); IntPoint p1 = pc.lineP2; IntPoint p2 = pc.swapLineP; IntPoint p3 = pc.tempPoint; Graphics g = pc.g; g.setColor(wayDesc.lineColor); boolean dashed = (wayDesc.getGraphicsLineStyle() == WayDescription.WDFLAG_LINESTYLE_DOTTED); //#if polish.android boolean doNotSimplifyMap = !Configuration.getCfgBitState(Configuration.CFGBIT_SIMPLIFY_MAP_WHEN_BUSY); //#endif int idx; if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_PREFER_OUTLINE_AREAS) && Legend.getLegendMapFlag(Legend.LEGEND_MAPFLAG_OUTLINE_AREA_BLOCK)) { if (path.length > 0) { //#if polish.android //#if polish.api.areaoutlines Path aPath = new Path(); g.getPaint().setStyle(Style.FILL); aPath.setFillType(Path.FillType.EVEN_ODD); //#endif //#endif idx = path[0]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p1,t); //#if polish.android //#if polish.api.areaoutlines aPath.moveTo(p1.x + g.getTranslateX(), p1.y + g.getTranslateY()); //#endif //#endif for (int i1 = 1; i1 < path.length; ){ idx = path[i1++]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p2,t); //#if polish.android //#if polish.api.areaoutlines aPath.lineTo(p2.x + g.getTranslateX(), p2.y + g.getTranslateY()); //#endif //#endif } //#if polish.android //#if polish.api.areaoutlines aPath.lineTo(p1.x + g.getTranslateX(), p1.y + g.getTranslateY()); aPath.close(); if (holes != null) { for (short hole[] : holes) { idx = hole[0]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p1,t); aPath.moveTo(p1.x + g.getTranslateX(), p1.y + g.getTranslateY()); for (int i1 = 1; i1 < hole.length; ) { idx = hole[i1++]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p2,t); aPath.lineTo(p2.x + g.getTranslateX(), p2.y + g.getTranslateY()); } aPath.lineTo(p1.x + g.getTranslateX(), p1.y + g.getTranslateY()); aPath.close(); } } // FIXME set a proper winding method (even-odd?) // FIXME currently this depends on a modified Graphics.java of J2MEPolish to expose the private canvas and paint // variables in Graphics.java to other modules; must find a way to do this with normal J2MEPolish or to // get a modification to J2MEPolish g.getCanvas().drawPath(aPath, g.getPaint()); g.getPaint().setStyle(Style.STROKE); //#endif //#endif } } else { for (int i1 = 0; i1 < path.length; ){ // pc.g.setColor(wayDesc.lineColor); idx = path[i1++]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p1,t); idx = path[i1++]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p2,t); idx = path[i1++]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p3,t); if (dashed) { FilledTriangle.fillTriangle(pc, p1.x,p1.y,p2.x,p2.y,p3.x,p3.y); } else { if (p1.x != p2.x || p2.x != p3.x || p1.y != p2.y || p2.y != p3.y) { g.fillTriangle(p1.x,p1.y,p2.x,p2.y,p3.x,p3.y); // Without these, there are ugly light-color gaps in filled areas on Android devices - but this cuts down on performance, // remove for now on 2012-07-23 for configurations with "simplify map when busy" turned on // possibly could be helped by antialiasing or some other tweaks in J2MEPolish code: // // https://github.com/Enough-Software/j2mepolish/blob/4718fe3b9f55eb8a2c8172316ed416d87f9bf86c/enough-polish-j2me/source/src/de/enough/polish/android/lcdui/Graphics.java // // see also http://stackoverflow.com/questions/7608362/how-to-draw-smooth-rounded-path // though better yet would be to use direct polygons without triangulation // // with 250 m zoom on Sams. Galaxy Note, paint times with the drawLines: // I/System.out( 7740): Painting map took 18176 ms 992/1524 // I/System.out( 7740): Painting map took 19300 ms 992/1524 // I/System.out( 7740): Painting map took 14855 ms 992/1524 // I/System.out( 7740): Painting map took 14030 ms 992/1524 // I/System.out( 7740): Painting map took 14450 ms 992/1524 // I/System.out( 7740): Painting map took 13993 ms 992/1524 // I/System.out( 7740): Painting map took 13572 ms 992/1524 // without drawLines: // I/System.out( 8938): Painting map took 6304 ms 992/1524 // I/System.out( 8938): Painting map took 5430 ms 992/1524 // I/System.out( 8938): Painting map took 5587 ms 992/1524 // I/System.out( 8938): Painting map took 5219 ms 992/1524 // I/System.out( 8938): Painting map took 4609 ms 992/1524 // I/System.out( 8938): Painting map took 4386 ms 992/1524 // I/System.out( 8938): Painting map took 4287 ms 992/1524 //#if polish.android if (doNotSimplifyMap) { g.drawLine(p1.x,p1.y,p2.x,p2.y); g.drawLine(p2.x,p2.y,p3.x,p3.y); g.drawLine(p1.x,p1.y,p3.x,p3.y); } //#endif } else { // optimisation: render triangles consisting of 3 equal coordinates simply as a dot g.drawRect(p1.x, p1.y, 0, 0 ); } } } } paintAreaName(pc,t); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "paintAsArea"
"public void paintAsArea(PaintContext pc, SingleTile t) { //#if polish.api.bigstyles WayDescription wayDesc = Legend.getWayDescription(type); //#else WayDescription wayDesc = Legend.getWayDescription((short) (type & 0xff)); //#endif //#if polish.api.bigstyles byte om = Legend.getWayOverviewMode(type); //#else byte om = Legend.getWayOverviewMode((short) (type & 0xff)); //#endif switch (om & Legend.OM_MODE_MASK) { case Legend.OM_SHOWNORMAL: // if not in Overview Mode check for scale if (pc.scale > wayDesc.maxScale * Configuration.getDetailBoostMultiplier()) { return; } // building areas if (wayDesc.isBuilding()) { if (!Configuration.getCfgBitState(Configuration.CFGBIT_BUILDINGS)) { return; } // non-building areas } else { if(wayDesc.hideable && !Configuration.getCfgBitState(Configuration.CFGBIT_AREAS)) { return; } } break; case Legend.OM_HIDE: if (wayDesc.hideable) { return; } break; } switch (om & Legend.OM_NAME_MASK) { case Legend.OM_WITH_NAMEPART: if (nameIdx == -1) { return; } String name = pc.trace.getName(nameIdx); String url = pc.trace.getName(urlIdx); if (name == null) { return; } if (name.toUpperCase().indexOf(Legend.get0Poi1Area2WayNamePart((byte) 1).toUpperCase()) == -1) { return; } break; case Legend.OM_WITH_NAME: if (nameIdx == -1) { return; } break; case Legend.OM_NO_NAME: if (nameIdx != -1) { return; } break; } Projection p = pc.getP(); IntPoint p1 = pc.lineP2; IntPoint p2 = pc.swapLineP; IntPoint p3 = pc.tempPoint; Graphics g = pc.g; g.setColor(wayDesc.lineColor); boolean dashed = (wayDesc.getGraphicsLineStyle() == WayDescription.WDFLAG_LINESTYLE_DOTTED); //#if polish.android boolean doNotSimplifyMap = !Configuration.getCfgBitState(Configuration.CFGBIT_SIMPLIFY_MAP_WHEN_BUSY); //#endif int idx; if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_PREFER_OUTLINE_AREAS) && Legend.getLegendMapFlag(Legend.LEGEND_MAPFLAG_OUTLINE_AREA_BLOCK)) { if (path.length > 0) { //#if polish.android //#if polish.api.areaoutlines Path aPath = new Path(); <MASK>aPath.setFillType(Path.FillType.EVEN_ODD);</MASK> g.getPaint().setStyle(Style.FILL); //#endif //#endif idx = path[0]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p1,t); //#if polish.android //#if polish.api.areaoutlines aPath.moveTo(p1.x + g.getTranslateX(), p1.y + g.getTranslateY()); //#endif //#endif for (int i1 = 1; i1 < path.length; ){ idx = path[i1++]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p2,t); //#if polish.android //#if polish.api.areaoutlines aPath.lineTo(p2.x + g.getTranslateX(), p2.y + g.getTranslateY()); //#endif //#endif } //#if polish.android //#if polish.api.areaoutlines aPath.lineTo(p1.x + g.getTranslateX(), p1.y + g.getTranslateY()); aPath.close(); if (holes != null) { for (short hole[] : holes) { idx = hole[0]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p1,t); aPath.moveTo(p1.x + g.getTranslateX(), p1.y + g.getTranslateY()); for (int i1 = 1; i1 < hole.length; ) { idx = hole[i1++]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p2,t); aPath.lineTo(p2.x + g.getTranslateX(), p2.y + g.getTranslateY()); } aPath.lineTo(p1.x + g.getTranslateX(), p1.y + g.getTranslateY()); aPath.close(); } } // FIXME set a proper winding method (even-odd?) // FIXME currently this depends on a modified Graphics.java of J2MEPolish to expose the private canvas and paint // variables in Graphics.java to other modules; must find a way to do this with normal J2MEPolish or to // get a modification to J2MEPolish g.getCanvas().drawPath(aPath, g.getPaint()); g.getPaint().setStyle(Style.STROKE); //#endif //#endif } } else { for (int i1 = 0; i1 < path.length; ){ // pc.g.setColor(wayDesc.lineColor); idx = path[i1++]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p1,t); idx = path[i1++]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p2,t); idx = path[i1++]; if (idx < 0) { idx += 65536; } p.forward(t.nodeLat[idx],t.nodeLon[idx],p3,t); if (dashed) { FilledTriangle.fillTriangle(pc, p1.x,p1.y,p2.x,p2.y,p3.x,p3.y); } else { if (p1.x != p2.x || p2.x != p3.x || p1.y != p2.y || p2.y != p3.y) { g.fillTriangle(p1.x,p1.y,p2.x,p2.y,p3.x,p3.y); // Without these, there are ugly light-color gaps in filled areas on Android devices - but this cuts down on performance, // remove for now on 2012-07-23 for configurations with "simplify map when busy" turned on // possibly could be helped by antialiasing or some other tweaks in J2MEPolish code: // // https://github.com/Enough-Software/j2mepolish/blob/4718fe3b9f55eb8a2c8172316ed416d87f9bf86c/enough-polish-j2me/source/src/de/enough/polish/android/lcdui/Graphics.java // // see also http://stackoverflow.com/questions/7608362/how-to-draw-smooth-rounded-path // though better yet would be to use direct polygons without triangulation // // with 250 m zoom on Sams. Galaxy Note, paint times with the drawLines: // I/System.out( 7740): Painting map took 18176 ms 992/1524 // I/System.out( 7740): Painting map took 19300 ms 992/1524 // I/System.out( 7740): Painting map took 14855 ms 992/1524 // I/System.out( 7740): Painting map took 14030 ms 992/1524 // I/System.out( 7740): Painting map took 14450 ms 992/1524 // I/System.out( 7740): Painting map took 13993 ms 992/1524 // I/System.out( 7740): Painting map took 13572 ms 992/1524 // without drawLines: // I/System.out( 8938): Painting map took 6304 ms 992/1524 // I/System.out( 8938): Painting map took 5430 ms 992/1524 // I/System.out( 8938): Painting map took 5587 ms 992/1524 // I/System.out( 8938): Painting map took 5219 ms 992/1524 // I/System.out( 8938): Painting map took 4609 ms 992/1524 // I/System.out( 8938): Painting map took 4386 ms 992/1524 // I/System.out( 8938): Painting map took 4287 ms 992/1524 //#if polish.android if (doNotSimplifyMap) { g.drawLine(p1.x,p1.y,p2.x,p2.y); g.drawLine(p2.x,p2.y,p3.x,p3.y); g.drawLine(p1.x,p1.y,p3.x,p3.y); } //#endif } else { // optimisation: render triangles consisting of 3 equal coordinates simply as a dot g.drawRect(p1.x, p1.y, 0, 0 ); } } } } paintAreaName(pc,t); }"
Inversion-Mutation
megadiff
"@Override void execute(CharWrapper characters, ProductionContext context) throws Exception { characters.removeSpace(); switch(characters.charAt(0)){ case equal: if(characters.charAt(1) == equal){ characters.shift(2); String value = "=="; if(characters.charAt(0) == equal){ characters.shift(1); value = value + "="; } output.prepend(value); context.removeProduction(); return; } break; case exclamation: if(characters.charAt(1) == equal){ characters.shift(2); String value = "!="; if(characters.charAt(0) == equal){ characters.shift(1); value = value + "="; } output.prepend(value); context.removeProduction(); return; } break; case pipe: if(characters.charAt(1) == pipe){ characters.shift(2); output.prepend("||"); context.removeProduction(); return; } break; case amp: if(characters.charAt(1) == amp){ characters.shift(2); output.prepend("&&"); context.removeProduction(); return; } break; case plus: case minus: case mod: case asterisk: case forward: output.prepend(characters.charAt(0)); characters.shift(1); context.removeProduction(); return; } throw new Exception("Invalid Operator."); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute"
"@Override void execute(CharWrapper characters, ProductionContext context) throws Exception { characters.removeSpace(); switch(characters.charAt(0)){ case equal: if(characters.charAt(1) == equal){ characters.shift(2); String value = "=="; if(characters.charAt(0) == equal){ <MASK>characters.shift(1);</MASK> value = value + "="; } output.prepend(value); context.removeProduction(); return; } break; case exclamation: if(characters.charAt(1) == equal){ characters.shift(2); String value = "!="; if(characters.charAt(0) == equal){ <MASK>characters.shift(1);</MASK> value = value + "="; } output.prepend(value); context.removeProduction(); return; } break; case pipe: if(characters.charAt(1) == pipe){ characters.shift(2); output.prepend("||"); context.removeProduction(); return; } break; case amp: if(characters.charAt(1) == amp){ characters.shift(2); output.prepend("&&"); context.removeProduction(); return; } break; case plus: case minus: case mod: case asterisk: case forward: <MASK>characters.shift(1);</MASK> output.prepend(characters.charAt(0)); context.removeProduction(); return; } throw new Exception("Invalid Operator."); }"
Inversion-Mutation
megadiff
"public void idle() { if(state.equals("init")) { System.out.println("Welcome to Bitster! Type \"quit\" to quit."); System.out.println("------------------------------------------"); state = "running"; } String in = s.next(); if(in != null) { if(in.equals("quit")) { Janitor.getInstance().start(); shutdown(); } else if(in.equals("status")) { printProgress(); } else { System.out.println("Usage instructions:"); System.out.println("status - shows download status"); System.out.println("quit - quits bitster"); } System.out.print(prompt); } try { Thread.sleep(100); } catch (InterruptedException e) {} }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "idle"
"public void idle() { if(state.equals("init")) { System.out.println("Welcome to Bitster! Type \"quit\" to quit."); System.out.println("------------------------------------------"); state = "running"; } <MASK>System.out.print(prompt);</MASK> String in = s.next(); if(in != null) { if(in.equals("quit")) { Janitor.getInstance().start(); shutdown(); } else if(in.equals("status")) { printProgress(); } else { System.out.println("Usage instructions:"); System.out.println("status - shows download status"); System.out.println("quit - quits bitster"); } } try { Thread.sleep(100); } catch (InterruptedException e) {} }"
Inversion-Mutation
megadiff
"public void loadWebserver() { InetAddress bindAddress; { String address = configuration.getString("webserver-bindaddress", "0.0.0.0"); try { bindAddress = address.equals("0.0.0.0") ? null : InetAddress.getByName(address); } catch (UnknownHostException e) { bindAddress = null; } } int port = configuration.getInt("webserver-port", 8123); webServer = new HttpServer(bindAddress, port); webServer.handlers.put("/", new FilesystemHandler(getFile(configuration.getString("webpath", "web")))); webServer.handlers.put("/tiles/", new FilesystemHandler(tilesDirectory)); webServer.handlers.put("/up/", new ClientUpdateHandler(mapManager, playerList, getServer())); webServer.handlers.put("/up/configuration", new ClientConfigurationHandler((Map<?, ?>) configuration.getProperty("web"))); boolean allowchat = configuration.getBoolean("allowchat", true); if (allowchat == true) { SendMessageHandler messageHandler = new SendMessageHandler(); messageHandler.onMessageReceived.addListener(new Listener<SendMessageHandler.Message>() { @Override public void triggered(Message t) { mapManager.pushUpdate(new Client.WebChatMessage(t.name, t.message)); log.info("[WEB]" + t.name + ": " + t.message); getServer().broadcastMessage("[WEB]" + t.name + ": " + t.message); } }); webServer.handlers.put("/up/sendmessage", messageHandler); } try { webServer.startServer(); } catch (IOException e) { log.severe("Failed to start WebServer on " + bindAddress + ":" + port + "!"); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "loadWebserver"
"public void loadWebserver() { InetAddress bindAddress; { String address = configuration.getString("webserver-bindaddress", "0.0.0.0"); try { bindAddress = address.equals("0.0.0.0") ? null : InetAddress.getByName(address); } catch (UnknownHostException e) { bindAddress = null; } } int port = configuration.getInt("webserver-port", 8123); webServer = new HttpServer(bindAddress, port); webServer.handlers.put("/", new FilesystemHandler(getFile(configuration.getString("webpath", "web")))); webServer.handlers.put("/tiles/", new FilesystemHandler(tilesDirectory)); webServer.handlers.put("/up/", new ClientUpdateHandler(mapManager, playerList, getServer())); webServer.handlers.put("/up/configuration", new ClientConfigurationHandler((Map<?, ?>) configuration.getProperty("web"))); <MASK>SendMessageHandler messageHandler = new SendMessageHandler();</MASK> boolean allowchat = configuration.getBoolean("allowchat", true); if (allowchat == true) { messageHandler.onMessageReceived.addListener(new Listener<SendMessageHandler.Message>() { @Override public void triggered(Message t) { mapManager.pushUpdate(new Client.WebChatMessage(t.name, t.message)); log.info("[WEB]" + t.name + ": " + t.message); getServer().broadcastMessage("[WEB]" + t.name + ": " + t.message); } }); webServer.handlers.put("/up/sendmessage", messageHandler); } try { webServer.startServer(); } catch (IOException e) { log.severe("Failed to start WebServer on " + bindAddress + ":" + port + "!"); } }"
Inversion-Mutation
megadiff
"static void markAndCopy() { int i, ref; if (!concurrentGc) { getStackRoots(); } getStaticRoots(); for (;;) { // pop one object from the gray list synchronized (mutex) { ref = greyList; if (ref==GREY_END) { break; } greyList = Native.rdMem(ref+OFF_GREY); Native.wrMem(0, ref+OFF_GREY); // mark as not in list } // allready moved // can this happen? - yes, as we do not check it in mark // TODO: no, it's checked in push() // What happens when the actuall scanning object is // again pushed on the grey stack by the mutator? if (Native.rdMem(ref+OFF_SPACE)==toSpace) { // it happens // log("mark/copy allready in toSpace"); continue; } // there should be no null pointers on the mark stack // if (Native.rdMem(ref+OFF_PTR)==0) { // log("mark/copy OFF_PTR=0!!!"); // continue; // } // push all childs // get pointer to object int addr = Native.rdMem(ref); int flags = Native.rdMem(ref+OFF_TYPE); if (flags==IS_REFARR) { // is an array of references int size = Native.rdMem(ref+OFF_MTAB_ALEN); for (i=0; i<size; ++i) { push(Native.rdMem(addr+i)); } // However, multianewarray does probably NOT work } else if (flags==IS_OBJ){ // it's a plain object // get pointer to method table flags = Native.rdMem(ref+OFF_MTAB_ALEN); // get real flags flags = Native.rdMem(flags+Const.MTAB2GC_INFO); for (i=0; flags!=0; ++i) { if ((flags&1)!=0) { push(Native.rdMem(addr+i)); } flags >>>= 1; } } // now copy it - color it BLACK int size; int dest; synchronized(mutex) { size = Native.rdMem(ref+OFF_SIZE); dest = copyPtr; copyPtr += size; // set it BLACK Native.wrMem(toSpace, ref+OFF_SPACE); } if (size>0) { // copy it for (i=0; i<size; i++) { // Native.wrMem(Native.rdMem(addr+i), dest+i); Native.memCopy(dest, addr, i); } } // update object pointer to the new location Native.wrMem(dest, ref+OFF_PTR); // wait until everybody uses the new location for (i = 0; i < 10; i++); // turn off address translation Native.memCopy(dest, dest, -1); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "markAndCopy"
"static void markAndCopy() { int i, ref; <MASK>getStaticRoots();</MASK> if (!concurrentGc) { getStackRoots(); } for (;;) { // pop one object from the gray list synchronized (mutex) { ref = greyList; if (ref==GREY_END) { break; } greyList = Native.rdMem(ref+OFF_GREY); Native.wrMem(0, ref+OFF_GREY); // mark as not in list } // allready moved // can this happen? - yes, as we do not check it in mark // TODO: no, it's checked in push() // What happens when the actuall scanning object is // again pushed on the grey stack by the mutator? if (Native.rdMem(ref+OFF_SPACE)==toSpace) { // it happens // log("mark/copy allready in toSpace"); continue; } // there should be no null pointers on the mark stack // if (Native.rdMem(ref+OFF_PTR)==0) { // log("mark/copy OFF_PTR=0!!!"); // continue; // } // push all childs // get pointer to object int addr = Native.rdMem(ref); int flags = Native.rdMem(ref+OFF_TYPE); if (flags==IS_REFARR) { // is an array of references int size = Native.rdMem(ref+OFF_MTAB_ALEN); for (i=0; i<size; ++i) { push(Native.rdMem(addr+i)); } // However, multianewarray does probably NOT work } else if (flags==IS_OBJ){ // it's a plain object // get pointer to method table flags = Native.rdMem(ref+OFF_MTAB_ALEN); // get real flags flags = Native.rdMem(flags+Const.MTAB2GC_INFO); for (i=0; flags!=0; ++i) { if ((flags&1)!=0) { push(Native.rdMem(addr+i)); } flags >>>= 1; } } // now copy it - color it BLACK int size; int dest; synchronized(mutex) { size = Native.rdMem(ref+OFF_SIZE); dest = copyPtr; copyPtr += size; // set it BLACK Native.wrMem(toSpace, ref+OFF_SPACE); } if (size>0) { // copy it for (i=0; i<size; i++) { // Native.wrMem(Native.rdMem(addr+i), dest+i); Native.memCopy(dest, addr, i); } } // update object pointer to the new location Native.wrMem(dest, ref+OFF_PTR); // wait until everybody uses the new location for (i = 0; i < 10; i++); // turn off address translation Native.memCopy(dest, dest, -1); } }"
Inversion-Mutation
megadiff
"private void writeResult(String sql, String s, SQLException e) throws Exception { assertKnownException(e); s = ("> " + s).trim(); String compare = readLine(); if (compare != null && compare.startsWith(">")) { if (!compare.equals(s)) { if (alwaysReconnect && sql.toUpperCase().startsWith("EXPLAIN")) { return; } errors.append("line: "); errors.append(line); errors.append("\n" + "exp: "); errors.append(compare); errors.append("\n" + "got: "); errors.append(s); errors.append("\n"); if (e != null) { TestBase.logError("script", e); } TestBase.logError(errors.toString(), null); if (failFast) { conn.close(); System.exit(1); } } } else { putBack = compare; } write(s); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "writeResult"
"private void writeResult(String sql, String s, SQLException e) throws Exception { assertKnownException(e); s = ("> " + s).trim(); String compare = readLine(); if (compare != null && compare.startsWith(">")) { if (!compare.equals(s)) { if (alwaysReconnect && sql.toUpperCase().startsWith("EXPLAIN")) { return; } errors.append("line: "); errors.append(line); errors.append("\n" + "exp: "); errors.append(compare); errors.append("\n" + "got: "); errors.append(s); errors.append("\n"); if (e != null) { TestBase.logError("script", e); } if (failFast) { <MASK>TestBase.logError(errors.toString(), null);</MASK> conn.close(); System.exit(1); } } } else { putBack = compare; } write(s); }"
Inversion-Mutation
megadiff
"private static Map<String, Object> markerFromEValidatorDiagnostic(Diagnostic diagnostic) { if (diagnostic.getSeverity() == Diagnostic.OK) return null; Map<String, Object> map = new HashMap<String, Object>(); int sever = IMarker.SEVERITY_ERROR; switch (diagnostic.getSeverity()) { case Diagnostic.WARNING: sever = IMarker.SEVERITY_WARNING; break; case Diagnostic.INFO: sever = IMarker.SEVERITY_INFO; break; } map.put(IMarker.SEVERITY, sever); Iterator<?> data = diagnostic.getData().iterator(); // causer is the first element see Diagnostician.getData Object causer = data.next(); if (causer instanceof EObject) { EObject ele = (EObject) causer; NodeAdapter nodeAdapter = NodeUtil.getNodeAdapter(ele); if (nodeAdapter != null) { AbstractNode parserNode = nodeAdapter.getParserNode(); // feature is the second element see Diagnostician.getData Object feature = data.hasNext() ? data.next() : null; EStructuralFeature structuralFeature = resolveStructuralFeature(ele, feature); if (structuralFeature != null) { List<AbstractNode> nodes = NodeUtil.findNodesForFeature(ele, structuralFeature); if (!nodes.isEmpty()) parserNode = nodes.iterator().next(); } map.put(IMarker.LINE_NUMBER, Integer.valueOf(parserNode.getLine())); int offset = parserNode.getOffset(); map.put(IMarker.CHAR_START, Integer.valueOf(offset)); map.put(IMarker.CHAR_END, Integer.valueOf(offset + parserNode.getLength())); } } map.put(IMarker.MESSAGE, diagnostic.getMessage()); map.put(IMarker.PRIORITY, Integer.valueOf(IMarker.PRIORITY_LOW)); return map; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "markerFromEValidatorDiagnostic"
"private static Map<String, Object> markerFromEValidatorDiagnostic(Diagnostic diagnostic) { if (diagnostic.getSeverity() == Diagnostic.OK) return null; Map<String, Object> map = new HashMap<String, Object>(); int sever = IMarker.SEVERITY_ERROR; switch (diagnostic.getSeverity()) { case Diagnostic.WARNING: sever = IMarker.SEVERITY_WARNING; break; case Diagnostic.INFO: sever = IMarker.SEVERITY_INFO; break; } map.put(IMarker.SEVERITY, sever); Iterator<?> data = diagnostic.getData().iterator(); // causer is the first element see Diagnostician.getData Object causer = data.next(); if (causer instanceof EObject) { EObject ele = (EObject) causer; NodeAdapter nodeAdapter = NodeUtil.getNodeAdapter(ele); if (nodeAdapter != null) { AbstractNode parserNode = nodeAdapter.getParserNode(); // feature is the second element see Diagnostician.getData Object feature = data.hasNext() ? data.next() : null; EStructuralFeature structuralFeature = resolveStructuralFeature(ele, feature); if (structuralFeature != null) { List<AbstractNode> nodes = NodeUtil.findNodesForFeature(ele, structuralFeature); if (!nodes.isEmpty()) parserNode = nodes.iterator().next(); } map.put(IMarker.LINE_NUMBER, Integer.valueOf(parserNode.getLine())); int offset = parserNode.getOffset(); map.put(IMarker.CHAR_START, Integer.valueOf(offset)); map.put(IMarker.CHAR_END, Integer.valueOf(offset + parserNode.getLength())); } <MASK>map.put(IMarker.MESSAGE, diagnostic.getMessage());</MASK> } map.put(IMarker.PRIORITY, Integer.valueOf(IMarker.PRIORITY_LOW)); return map; }"
Inversion-Mutation
megadiff
"public void defineLanguages() { en = new ArrayList<String>(); en.add(STOP, "stop:wait:don't:no:damn"); en.add(EXPLORE, "explore:try"); en.add(FORWARD, "forward:ahead"); en.add(REVERSE, "reverse:back"); en.add(ROTATERIGHT, "rotate&right"); en.add(ROTATELEFT, "rotate&left"); en.add(TURNRIGHT, "right"); en.add(TURNLEFT, "left"); fr = new ArrayList<String>(); fr.add(STOP, "arrter:pas:voyons:merde:zut:non:stop"); fr.add(EXPLORE, "explore"); fr.add(FORWARD, "avance:forward"); fr.add(REVERSE, "recule:reverse"); fr.add(ROTATERIGHT, "rotate&droit"); fr.add(ROTATELEFT, "rotate&gauche"); fr.add(TURNRIGHT, "droit:right"); fr.add(TURNLEFT, "gauche:left"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "defineLanguages"
"public void defineLanguages() { en = new ArrayList<String>(); en.add(STOP, "stop:wait:don't:no:damn"); en.add(EXPLORE, "explore:try"); en.add(FORWARD, "forward:ahead"); en.add(REVERSE, "reverse:back"); en.add(ROTATERIGHT, "rotate&right"); en.add(ROTATELEFT, "rotate&left"); en.add(TURNRIGHT, "right"); en.add(TURNLEFT, "left"); fr = new ArrayList<String>(); fr.add(EXPLORE, "explore"); fr.add(FORWARD, "avance:forward"); fr.add(REVERSE, "recule:reverse"); fr.add(ROTATERIGHT, "rotate&droit"); fr.add(ROTATELEFT, "rotate&gauche"); fr.add(TURNRIGHT, "droit:right"); fr.add(TURNLEFT, "gauche:left"); <MASK>fr.add(STOP, "arrter:pas:voyons:merde:zut:non:stop");</MASK> }"
Inversion-Mutation
megadiff
"private void firePendingTextChangeEvent() { if (textChangeEventPending) { textChangeEventPending = false; fireEvent(new TextChangeEventImpl(this)); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "firePendingTextChangeEvent"
"private void firePendingTextChangeEvent() { if (textChangeEventPending) { <MASK>fireEvent(new TextChangeEventImpl(this));</MASK> textChangeEventPending = false; } }"
Inversion-Mutation
megadiff
"@Override public void tick() { if (--currentTick > 0) return; if(stalled) currentTick = stalledDelay; else currentTick = normalDelay; //Extract Item IInventory targetInventory = _invProvider.getPointedInventory(); if (targetInventory == null) return; if (targetInventory.getSizeInventory() < 27) return; if(!_power.canUseEnergy(500)) { stalled = true; return; } if(lastSuceededStack >= targetInventory.getSizeInventory()) lastSuceededStack = 0; //incremented at the end of the previous loop. if (lastStackLookedAt >= targetInventory.getSizeInventory()) lastStackLookedAt = 0; ItemStack stackToSend = targetInventory.getStackInSlot(lastStackLookedAt); while(stackToSend==null) { lastStackLookedAt++; if (lastStackLookedAt >= targetInventory.getSizeInventory()) lastStackLookedAt = 0; stackToSend = targetInventory.getStackInSlot(lastStackLookedAt); if(lastStackLookedAt == lastSuceededStack) { stalled = true; return; // then we have been around the list without sending, halt for now } } Pair3<Integer, SinkReply, List<IFilter>> reply = _itemSender.hasDestination(stackToSend, false); if (reply == null) { if(lastStackLookedAt == lastSuceededStack) { stalled = true; } lastStackLookedAt++; return; } if(!_power.useEnergy(500)) { stalled = true; lastStackLookedAt++; return; } lastSuceededStack=lastStackLookedAt; lastStackLookedAt++; stalled = false; _itemSender.sendStack(stackToSend, reply); MainProxy.sendSpawnParticlePacket(Particles.OrangeParticle, xCoord, yCoord, zCoord, _world.getWorld(), 8); targetInventory.setInventorySlotContents(lastStackLookedAt, null); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "tick"
"@Override public void tick() { if (--currentTick > 0) return; if(stalled) currentTick = stalledDelay; else currentTick = normalDelay; //Extract Item IInventory targetInventory = _invProvider.getPointedInventory(); if (targetInventory == null) return; if (targetInventory.getSizeInventory() < 27) return; if(!_power.canUseEnergy(500)) { stalled = true; return; } if(lastSuceededStack >= targetInventory.getSizeInventory()) lastSuceededStack = 0; //incremented at the end of the previous loop. if (lastStackLookedAt >= targetInventory.getSizeInventory()) lastStackLookedAt = 0; ItemStack <MASK>stackToSend = targetInventory.getStackInSlot(lastStackLookedAt);</MASK> while(stackToSend==null) { lastStackLookedAt++; <MASK>stackToSend = targetInventory.getStackInSlot(lastStackLookedAt);</MASK> if (lastStackLookedAt >= targetInventory.getSizeInventory()) lastStackLookedAt = 0; if(lastStackLookedAt == lastSuceededStack) { stalled = true; return; // then we have been around the list without sending, halt for now } } Pair3<Integer, SinkReply, List<IFilter>> reply = _itemSender.hasDestination(stackToSend, false); if (reply == null) { if(lastStackLookedAt == lastSuceededStack) { stalled = true; } lastStackLookedAt++; return; } if(!_power.useEnergy(500)) { stalled = true; lastStackLookedAt++; return; } lastSuceededStack=lastStackLookedAt; lastStackLookedAt++; stalled = false; _itemSender.sendStack(stackToSend, reply); MainProxy.sendSpawnParticlePacket(Particles.OrangeParticle, xCoord, yCoord, zCoord, _world.getWorld(), 8); targetInventory.setInventorySlotContents(lastStackLookedAt, null); }"
Inversion-Mutation
megadiff
"@Override protected DataKind addDataKindPhone(Context context) throws DefinitionException { final DataKind kind = super.addDataKindPhone(context); kind.typeColumn = Phone.TYPE; kind.typeList = Lists.newArrayList(); kind.typeList.add(buildPhoneType(Phone.TYPE_MOBILE).setSpecificMax(1)); kind.typeList.add(buildPhoneType(Phone.TYPE_HOME).setSpecificMax(2)); kind.typeList.add(buildPhoneType(Phone.TYPE_WORK).setSpecificMax(2)); kind.typeList.add(buildPhoneType(Phone.TYPE_FAX_WORK).setSecondary(true) .setSpecificMax(1)); kind.typeList.add(buildPhoneType(Phone.TYPE_FAX_HOME).setSecondary(true) .setSpecificMax(1)); kind.typeList .add(buildPhoneType(Phone.TYPE_PAGER).setSecondary(true).setSpecificMax(1)); kind.typeList.add(buildPhoneType(Phone.TYPE_CAR).setSecondary(true).setSpecificMax(1)); kind.typeList.add(buildPhoneType(Phone.TYPE_COMPANY_MAIN).setSecondary(true) .setSpecificMax(1)); kind.typeList.add(buildPhoneType(Phone.TYPE_MMS).setSecondary(true).setSpecificMax(1)); kind.typeList .add(buildPhoneType(Phone.TYPE_RADIO).setSecondary(true).setSpecificMax(1)); kind.typeList.add(buildPhoneType(Phone.TYPE_ASSISTANT).setSecondary(true) .setSpecificMax(1)); kind.fieldList = Lists.newArrayList(); kind.fieldList.add(new EditField(Phone.NUMBER, R.string.phoneLabelsGroup, FLAGS_PHONE)); return kind; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addDataKindPhone"
"@Override protected DataKind addDataKindPhone(Context context) throws DefinitionException { final DataKind kind = super.addDataKindPhone(context); kind.typeColumn = Phone.TYPE; kind.typeList = Lists.newArrayList(); <MASK>kind.typeList.add(buildPhoneType(Phone.TYPE_HOME).setSpecificMax(2));</MASK> kind.typeList.add(buildPhoneType(Phone.TYPE_MOBILE).setSpecificMax(1)); kind.typeList.add(buildPhoneType(Phone.TYPE_WORK).setSpecificMax(2)); kind.typeList.add(buildPhoneType(Phone.TYPE_FAX_WORK).setSecondary(true) .setSpecificMax(1)); kind.typeList.add(buildPhoneType(Phone.TYPE_FAX_HOME).setSecondary(true) .setSpecificMax(1)); kind.typeList .add(buildPhoneType(Phone.TYPE_PAGER).setSecondary(true).setSpecificMax(1)); kind.typeList.add(buildPhoneType(Phone.TYPE_CAR).setSecondary(true).setSpecificMax(1)); kind.typeList.add(buildPhoneType(Phone.TYPE_COMPANY_MAIN).setSecondary(true) .setSpecificMax(1)); kind.typeList.add(buildPhoneType(Phone.TYPE_MMS).setSecondary(true).setSpecificMax(1)); kind.typeList .add(buildPhoneType(Phone.TYPE_RADIO).setSecondary(true).setSpecificMax(1)); kind.typeList.add(buildPhoneType(Phone.TYPE_ASSISTANT).setSecondary(true) .setSpecificMax(1)); kind.fieldList = Lists.newArrayList(); kind.fieldList.add(new EditField(Phone.NUMBER, R.string.phoneLabelsGroup, FLAGS_PHONE)); return kind; }"
Inversion-Mutation
megadiff
"protected long[] logAllocate(long[] physPos) { openLogIfNeeded(); logSize+=1+8+8; //space used for index val long[] ret = new long[physPos.length]; for(int i=0;i<physPos.length;i++){ long size = (physPos[i]&MASK_SIZE)>>>48; //would overlaps Volume Block? logSize+=1+8; //space used for WAL_PHYS_ARRAY ret[i] = (size<<48) | logSize; logSize+=size; checkLogRounding(); } log.ensureAvailable(logSize); return ret; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "logAllocate"
"protected long[] logAllocate(long[] physPos) { openLogIfNeeded(); logSize+=1+8+8; //space used for index val long[] ret = new long[physPos.length]; for(int i=0;i<physPos.length;i++){ long size = (physPos[i]&MASK_SIZE)>>>48; //would overlaps Volume Block? <MASK>checkLogRounding();</MASK> logSize+=1+8; //space used for WAL_PHYS_ARRAY ret[i] = (size<<48) | logSize; logSize+=size; } log.ensureAvailable(logSize); return ret; }"
Inversion-Mutation
megadiff
"@Override public List<BeanMetaData> getBeans() { ArrayList<BeanMetaData> result = new ArrayList<BeanMetaData>(); //Create AspectBinding AbstractBeanMetaData binding = new AbstractBeanMetaData(); if (name == null) { name = GUID.asString(); } binding.setName(name); BeanMetaDataUtil.setSimpleProperty(binding, "name", name); binding.setBean(AspectBinding.class.getName()); BeanMetaDataUtil.setSimpleProperty(binding, "pointcut", pointcut); if (cflow != null) { BeanMetaDataUtil.setSimpleProperty(binding, "cflow", cflow); } util.setAspectManagerProperty(binding, "manager"); result.add(binding); if (interceptors.size() > 0) { AbstractListMetaData almd = new AbstractListMetaData(); int i = 0; for (BaseInterceptorData interceptor : interceptors) { AbstractBeanMetaData bmd = new AbstractBeanMetaData(interceptor.getBeanClassName()); String intName = name + "$" + i++; bmd.setName(intName); util.setAspectManagerProperty(bmd, "manager"); BeanMetaDataUtil.DependencyBuilder builder = new BeanMetaDataUtil.DependencyBuilder(bmd, "binding", name).setState("Instantiated"); BeanMetaDataUtil.setDependencyProperty(builder); if (interceptor instanceof AdviceData) { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "aspect", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); if (((AdviceData)interceptor).getAdviceMethod() != null) { BeanMetaDataUtil.setSimpleProperty(bmd, "aspectMethod", ((AdviceData)interceptor).getAdviceMethod()); } BeanMetaDataUtil.setSimpleProperty(bmd, "type", ((AdviceData)interceptor).getType()); } else { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "stack", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); } result.add(bmd); almd.add(new AbstractInjectionValueMetaData(intName)); } BeanMetaDataUtil.setSimpleProperty(binding, "advices", almd); } return result; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getBeans"
"@Override public List<BeanMetaData> getBeans() { ArrayList<BeanMetaData> result = new ArrayList<BeanMetaData>(); //Create AspectBinding AbstractBeanMetaData binding = new AbstractBeanMetaData(); if (name == null) { name = GUID.asString(); } binding.setName(name); BeanMetaDataUtil.setSimpleProperty(binding, "name", name); binding.setBean(AspectBinding.class.getName()); BeanMetaDataUtil.setSimpleProperty(binding, "pointcut", pointcut); if (cflow != null) { BeanMetaDataUtil.setSimpleProperty(binding, "cflow", cflow); } util.setAspectManagerProperty(binding, "manager"); result.add(binding); if (interceptors.size() > 0) { AbstractListMetaData almd = new AbstractListMetaData(); int i = 0; for (BaseInterceptorData interceptor : interceptors) { AbstractBeanMetaData bmd = new AbstractBeanMetaData(interceptor.getBeanClassName()); String intName = name + "$" + i++; bmd.setName(intName); util.setAspectManagerProperty(bmd, "manager"); BeanMetaDataUtil.DependencyBuilder builder = new BeanMetaDataUtil.DependencyBuilder(bmd, "binding", name).setState("Instantiated"); BeanMetaDataUtil.setDependencyProperty(builder); if (interceptor instanceof AdviceData) { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "aspect", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); if (((AdviceData)interceptor).getAdviceMethod() != null) { BeanMetaDataUtil.setSimpleProperty(bmd, "aspectMethod", ((AdviceData)interceptor).getAdviceMethod()); } BeanMetaDataUtil.setSimpleProperty(bmd, "type", ((AdviceData)interceptor).getType()); } else { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "stack", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); } result.add(bmd); almd.add(new AbstractInjectionValueMetaData(intName)); <MASK>BeanMetaDataUtil.setSimpleProperty(binding, "advices", almd);</MASK> } } return result; }"
Inversion-Mutation
megadiff
"protected void setup(Slot s, Rendered r) { T t = map(r); super.setup(s, r); Location loc = s.os.get(PView.loc); plain.copy(s.os); s.os.put(PView.loc, loc); if(t != null) { Color col = newcol(t); new States.ColState(col).prep(s.os); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setup"
"protected void setup(Slot s, Rendered r) { T t = map(r); Location loc = s.os.get(PView.loc); plain.copy(s.os); s.os.put(PView.loc, loc); if(t != null) { Color col = newcol(t); new States.ColState(col).prep(s.os); } <MASK>super.setup(s, r);</MASK> }"
Inversion-Mutation
megadiff
"private static void startup(String homePath, long startupMemFree, long startupMemTotal) { long startup = System.currentTimeMillis(); int oldRev=0; int newRev=0; try { // start up System.out.println(copyright); System.out.println(hline); // check java version try { /*String[] check =*/ "a,b".split(","); // split needs java 1.4 } catch (NoSuchMethodError e) { System.err.println("STARTUP: Java Version too low. You need at least Java 1.4.2 to run YaCy"); Thread.sleep(3000); System.exit(-1); } // ensure that there is a DATA directory, if not, create one and if that fails warn and die File f = new File(homePath); if (!(f.exists())) f.mkdirs(); f = new File(homePath, "DATA/"); if (!(f.exists())) f.mkdirs(); if (!(f.exists())) { System.err.println("Error creating DATA-directory in " + homePath.toString() + " . Please check your write-permission for this folder. YaCy will now terminate."); System.exit(-1); } f = new File(homePath, "DATA/yacy.running"); if (!f.exists()) f.createNewFile(); f.deleteOnExit(); // setting up logging f = new File(homePath, "DATA/LOG/"); if (!(f.exists())) f.mkdirs(); if (!((new File(homePath, "DATA/LOG/yacy.logging")).exists())) try { serverFileUtils.copy(new File(homePath, "yacy.logging"), new File(homePath, "DATA/LOG/yacy.logging")); }catch (IOException e){ System.out.println("could not copy yacy.logging"); } try{ serverLog.configureLogging(new File(homePath, "DATA/LOG/yacy.logging")); } catch (IOException e) { System.out.println("could not find logging properties in homePath=" + homePath); e.printStackTrace(); } serverLog.logConfig("STARTUP", "java version " + System.getProperty("java.version", "no-java-version")); serverLog.logConfig("STARTUP", "Application Root Path: " + homePath); serverLog.logConfig("STARTUP", "Time Zone: UTC" + serverDate.UTCDiffString() + "; UTC+0000 is " + System.currentTimeMillis()); serverLog.logConfig("STARTUP", "Maximum file system path length: " + serverSystem.maxPathLength); /* // Testing if the yacy archive file were unzipped correctly. // This test is needed because of classfile-names longer than 100 chars // which could cause problems with incompatible unzip software. // See: // - http://www.yacy-forum.de/viewtopic.php?t=1763 // - http://www.yacy-forum.de/viewtopic.php?t=715 // - http://www.yacy-forum.de/viewtopic.php?t=1674 File unzipTest = new File(homePath,"doc/This_is_a_test_if_the_archive_file_containing_YaCy_was_unpacked_correctly_If_not_please_use_gnu_tar_instead.txt"); if (!unzipTest.exists()) { String errorMsg = "The archive file containing YaCy was not unpacked correctly. " + "Please use 'GNU-Tar' or upgrade to a newer version of your unzip software.\n" + "For detailed information on this bug see: " + "http://www.yacy-forum.de/viewtopic.php?t=715"; System.err.println(errorMsg); serverLog.logSevere("STARTUP", errorMsg); System.exit(1); } */ final plasmaSwitchboard sb = new plasmaSwitchboard(homePath, "yacy.init", "DATA/SETTINGS/httpProxy.conf"); // save information about available memory at startup time sb.setConfig("memoryFreeAfterStartup", startupMemFree); sb.setConfig("memoryTotalAfterStartup", startupMemTotal); // hardcoded, forced, temporary value-migration sb.setConfig("htTemplatePath", "htroot/env/templates"); sb.setConfig("parseableExt", "html,htm,txt,php,shtml,asp"); // if we are running an SVN version, we try to detect the used svn revision now ... final Properties buildProp = new Properties(); File buildPropFile = null; try { buildPropFile = new File(homePath,"build.properties"); buildProp.load(new FileInputStream(buildPropFile)); } catch (Exception e) { serverLog.logWarning("STARTUP", buildPropFile.toString() + " not found in settings path"); } oldRev=Integer.parseInt(sb.getConfig("svnRevision", "0")); try { if (buildProp.containsKey("releaseNr")) { // this normally looks like this: $Revision$ final String svnReleaseNrStr = buildProp.getProperty("releaseNr"); final Pattern pattern = Pattern.compile("\\$Revision:\\s(.*)\\s\\$",Pattern.DOTALL+Pattern.CASE_INSENSITIVE); final Matcher matcher = pattern.matcher(svnReleaseNrStr); if (matcher.find()) { final String svrReleaseNr = matcher.group(1); try { try {version = Double.parseDouble(vString);} catch (NumberFormatException e) {version = (float) 0.1;} version = versvn2combinedVersion(version, Integer.parseInt(svrReleaseNr)); } catch (NumberFormatException e) {} sb.setConfig("svnRevision", svrReleaseNr); } } newRev=Integer.parseInt(sb.getConfig("svnRevision", "0")); } catch (Exception e) { System.err.println("Unable to determine the currently used SVN revision number."); } sb.setConfig("version", Double.toString(version)); sb.setConfig("vString", combined2prettyVersion(Double.toString(version))); sb.setConfig("vdate", vDATE); sb.setConfig("applicationRoot", homePath); sb.startupTime = startup; serverLog.logConfig("STARTUP", "YACY Version: " + version + ", Built " + vDATE); yacyCore.latestVersion = version; // read environment int timeout = Integer.parseInt(sb.getConfig("httpdTimeout", "60000")); if (timeout < 60000) timeout = 60000; // create some directories final File htRootPath = new File(homePath, sb.getConfig("htRootPath", "htroot")); final File htDocsPath = new File(homePath, sb.getConfig("htDocsPath", "DATA/HTDOCS")); if (!(htDocsPath.exists())) htDocsPath.mkdir(); //final File htTemplatePath = new File(homePath, sb.getConfig("htTemplatePath","htdocs")); // create default notifier picture //TODO: Use templates instead of copying images ... if (!((new File(htDocsPath, "notifier.gif")).exists())) try { serverFileUtils.copy(new File(htRootPath, "env/grafics/empty.gif"), new File(htDocsPath, "notifier.gif")); } catch (IOException e) {} final File htdocsDefaultReadme = new File(htDocsPath, "readme.txt"); if (!(htdocsDefaultReadme.exists())) try {serverFileUtils.write(( "This is your root directory for individual Web Content\r\n" + "\r\n" + "Please place your html files into the www subdirectory.\r\n" + "The URL of that path is either\r\n" + "http://www.<your-peer-name>.yacy or\r\n" + "http://<your-ip>:<your-port>/www\r\n" + "\r\n" + "Other subdirectories may be created; they map to corresponding sub-domains.\r\n" + "This directory shares it's content with the applications htroot path, so you\r\n" + "may access your yacy search page with\r\n" + "http://<your-peer-name>.yacy/\r\n" + "\r\n").getBytes(), htdocsDefaultReadme);} catch (IOException e) { System.out.println("Error creating htdocs readme: " + e.getMessage()); } final File wwwDefaultPath = new File(htDocsPath, "www"); if (!(wwwDefaultPath.exists())) wwwDefaultPath.mkdir(); final File shareDefaultPath = new File(htDocsPath, "share"); if (!(shareDefaultPath.exists())) shareDefaultPath.mkdir(); migration.migrate(sb, oldRev, newRev); // start main threads final String port = sb.getConfig("port", "8080"); try { final httpd protocolHandler = new httpd(sb, new httpdFileHandler(sb), new httpdProxyHandler(sb)); final serverCore server = new serverCore( timeout /*control socket timeout in milliseconds*/, true /* block attacks (wrong protocol) */, protocolHandler /*command class*/, sb, 30000 /*command max length incl. GET args*/); server.setName("httpd:"+port); server.setPriority(Thread.MAX_PRIORITY); server.setObeyIntermission(false); if (server == null) { serverLog.logSevere("STARTUP", "Failed to start server. Probably port " + port + " already in use."); } else { // first start the server sb.deployThread("10_httpd", "HTTPD Server/Proxy", "the HTTPD, used as web server and proxy", null, server, 0, 0, 0, 0); //server.start(); // open the browser window final boolean browserPopUpTrigger = sb.getConfig("browserPopUpTrigger", "true").equals("true"); if (browserPopUpTrigger) { String browserPopUpPage = sb.getConfig("browserPopUpPage", "ConfigBasic.html"); boolean properPW = (sb.getConfig("adminAccount", "").length() == 0) && (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0); if (!properPW) browserPopUpPage = "ConfigBasic.html"; final String browserPopUpApplication = sb.getConfig("browserPopUpApplication", "netscape"); serverSystem.openBrowser((server.withSSL()?"https":"http") + "://localhost:" + serverCore.getPortNr(port) + "/" + browserPopUpPage, browserPopUpApplication); } //Copy the shipped locales into DATA final File localesPath = new File(homePath, sb.getConfig("localesPath", "DATA/LOCALE")); final File defaultLocalesPath = new File(homePath, "locales"); try{ final File[] defaultLocales = defaultLocalesPath.listFiles(); localesPath.mkdirs(); for(int i=0;i < defaultLocales.length; i++){ if(defaultLocales[i].getName().endsWith(".lng")) serverFileUtils.copy(defaultLocales[i], new File(localesPath, defaultLocales[i].getName())); } serverLog.logInfo("STARTUP", "Copied the default locales to DATA/LOCALE"); }catch(NullPointerException e){ serverLog.logSevere("STARTUP", "Nullpointer Exception while copying the default Locales"); } //regenerate Locales from Translationlist, if needed final String lang = sb.getConfig("htLocaleSelection", ""); if(! lang.equals("") && ! lang.equals("default") ){ //locale is used String currentRev = ""; try{ final BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File( sb.getConfig("htLocalePath", "DATA/HTDOCS/locale"), lang+"/version" )))); currentRev = br.readLine(); br.close(); }catch(IOException e){ //Error } try{ //seperate try, because we want this, even if the file "version" does not exist. if(! currentRev.equals(sb.getConfig("svnRevision", "")) ){ //is this another version?! final File sourceDir = new File(sb.getConfig("htRootPath", "htroot")); final File destDir = new File(sb.getConfig("htLocalePath", "DATA/HTDOCS/locale"), lang); if(translator.translateFilesRecursive(sourceDir, destDir, new File("DATA/LOCALE/"+lang+".lng"), "html,template,inc", "locale")){ //translate it //write the new Versionnumber final BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(new File(destDir, "version")))); bw.write(sb.getConfig("svnRevision", "Error getting Version")); bw.close(); } } }catch(IOException e){ //Error } } // registering shutdown hook serverLog.logConfig("STARTUP", "Registering Shutdown Hook"); final Runtime run = Runtime.getRuntime(); run.addShutdownHook(new shutdownHookThread(Thread.currentThread(), sb)); // save information about available memory after all initializations //try { sb.setConfig("memoryFreeAfterInitBGC", Runtime.getRuntime().freeMemory()); sb.setConfig("memoryTotalAfterInitBGC", Runtime.getRuntime().totalMemory()); System.gc(); sb.setConfig("memoryFreeAfterInitAGC", Runtime.getRuntime().freeMemory()); sb.setConfig("memoryTotalAfterInitAGC", Runtime.getRuntime().totalMemory()); //} catch (ConcurrentModificationException e) {} // wait for server shutdown try { sb.waitForShutdown(); } catch (Exception e) { serverLog.logSevere("MAIN CONTROL LOOP", "PANIC: " + e.getMessage(),e); } // shut down serverLog.logConfig("SHUTDOWN", "caught termination signal"); server.terminate(false); server.interrupt(); if (server.isAlive()) try { URL u = new URL((server.withSSL()?"https":"http")+"://localhost:" + serverCore.getPortNr(port)); httpc.wget(u, u.getHost(), 1000, null, null, null); // kick server serverLog.logConfig("SHUTDOWN", "sent termination signal to server socket"); } catch (IOException ee) { serverLog.logConfig("SHUTDOWN", "termination signal to server socket missed (server shutdown, ok)"); } // idle until the processes are down while (server.isAlive()) { Thread.sleep(2000); // wait a while } serverLog.logConfig("SHUTDOWN", "server has terminated"); sb.close(); } } catch (Exception e) { serverLog.logSevere("STARTUP", "Unexpected Error: " + e.getClass().getName(),e); //System.exit(1); } } catch (Exception ee) { serverLog.logSevere("STARTUP", "FATAL ERROR: " + ee.getMessage(),ee); } serverLog.logConfig("SHUTDOWN", "goodbye. (this is the last line)"); try { System.exit(0); } catch (Exception e) {} // was once stopped by de.anomic.net.ftpc$sm.checkExit(ftpc.java:1790) }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "startup"
"private static void startup(String homePath, long startupMemFree, long startupMemTotal) { long startup = System.currentTimeMillis(); int oldRev=0; int newRev=0; try { // start up System.out.println(copyright); System.out.println(hline); // check java version try { /*String[] check =*/ "a,b".split(","); // split needs java 1.4 } catch (NoSuchMethodError e) { System.err.println("STARTUP: Java Version too low. You need at least Java 1.4.2 to run YaCy"); Thread.sleep(3000); System.exit(-1); } // ensure that there is a DATA directory, if not, create one and if that fails warn and die File f = new File(homePath); if (!(f.exists())) f.mkdirs(); f = new File(homePath, "DATA/"); if (!(f.exists())) f.mkdirs(); if (!(f.exists())) { System.err.println("Error creating DATA-directory in " + homePath.toString() + " . Please check your write-permission for this folder. YaCy will now terminate."); System.exit(-1); } f = new File(homePath, "DATA/yacy.running"); if (!f.exists()) f.createNewFile(); f.deleteOnExit(); // setting up logging f = new File(homePath, "DATA/LOG/"); if (!(f.exists())) f.mkdirs(); if (!((new File(homePath, "DATA/LOG/yacy.logging")).exists())) try { serverFileUtils.copy(new File(homePath, "yacy.logging"), new File(homePath, "DATA/LOG/yacy.logging")); }catch (IOException e){ System.out.println("could not copy yacy.logging"); } try{ serverLog.configureLogging(new File(homePath, "DATA/LOG/yacy.logging")); } catch (IOException e) { System.out.println("could not find logging properties in homePath=" + homePath); e.printStackTrace(); } serverLog.logConfig("STARTUP", "java version " + System.getProperty("java.version", "no-java-version")); serverLog.logConfig("STARTUP", "Application Root Path: " + homePath); serverLog.logConfig("STARTUP", "Time Zone: UTC" + serverDate.UTCDiffString() + "; UTC+0000 is " + System.currentTimeMillis()); serverLog.logConfig("STARTUP", "Maximum file system path length: " + serverSystem.maxPathLength); /* // Testing if the yacy archive file were unzipped correctly. // This test is needed because of classfile-names longer than 100 chars // which could cause problems with incompatible unzip software. // See: // - http://www.yacy-forum.de/viewtopic.php?t=1763 // - http://www.yacy-forum.de/viewtopic.php?t=715 // - http://www.yacy-forum.de/viewtopic.php?t=1674 File unzipTest = new File(homePath,"doc/This_is_a_test_if_the_archive_file_containing_YaCy_was_unpacked_correctly_If_not_please_use_gnu_tar_instead.txt"); if (!unzipTest.exists()) { String errorMsg = "The archive file containing YaCy was not unpacked correctly. " + "Please use 'GNU-Tar' or upgrade to a newer version of your unzip software.\n" + "For detailed information on this bug see: " + "http://www.yacy-forum.de/viewtopic.php?t=715"; System.err.println(errorMsg); serverLog.logSevere("STARTUP", errorMsg); System.exit(1); } */ final plasmaSwitchboard sb = new plasmaSwitchboard(homePath, "yacy.init", "DATA/SETTINGS/httpProxy.conf"); // save information about available memory at startup time sb.setConfig("memoryFreeAfterStartup", startupMemFree); sb.setConfig("memoryTotalAfterStartup", startupMemTotal); // hardcoded, forced, temporary value-migration sb.setConfig("htTemplatePath", "htroot/env/templates"); sb.setConfig("parseableExt", "html,htm,txt,php,shtml,asp"); // if we are running an SVN version, we try to detect the used svn revision now ... final Properties buildProp = new Properties(); File buildPropFile = null; try { buildPropFile = new File(homePath,"build.properties"); buildProp.load(new FileInputStream(buildPropFile)); } catch (Exception e) { serverLog.logWarning("STARTUP", buildPropFile.toString() + " not found in settings path"); } oldRev=Integer.parseInt(sb.getConfig("svnRevision", "0")); try { if (buildProp.containsKey("releaseNr")) { // this normally looks like this: $Revision$ final String svnReleaseNrStr = buildProp.getProperty("releaseNr"); final Pattern pattern = Pattern.compile("\\$Revision:\\s(.*)\\s\\$",Pattern.DOTALL+Pattern.CASE_INSENSITIVE); final Matcher matcher = pattern.matcher(svnReleaseNrStr); if (matcher.find()) { final String svrReleaseNr = matcher.group(1); try { try {version = Double.parseDouble(vString);} catch (NumberFormatException e) {version = (float) 0.1;} version = versvn2combinedVersion(version, Integer.parseInt(svrReleaseNr)); } catch (NumberFormatException e) {} sb.setConfig("svnRevision", svrReleaseNr); } } newRev=Integer.parseInt(sb.getConfig("svnRevision", "0")); } catch (Exception e) { System.err.println("Unable to determine the currently used SVN revision number."); } sb.setConfig("version", Double.toString(version)); sb.setConfig("vString", combined2prettyVersion(Double.toString(version))); sb.setConfig("vdate", vDATE); sb.setConfig("applicationRoot", homePath); sb.startupTime = startup; serverLog.logConfig("STARTUP", "YACY Version: " + version + ", Built " + vDATE); yacyCore.latestVersion = version; // read environment int timeout = Integer.parseInt(sb.getConfig("httpdTimeout", "60000")); if (timeout < 60000) timeout = 60000; // create some directories final File htRootPath = new File(homePath, sb.getConfig("htRootPath", "htroot")); final File htDocsPath = new File(homePath, sb.getConfig("htDocsPath", "DATA/HTDOCS")); //final File htTemplatePath = new File(homePath, sb.getConfig("htTemplatePath","htdocs")); // create default notifier picture //TODO: Use templates instead of copying images ... if (!((new File(htDocsPath, "notifier.gif")).exists())) try { serverFileUtils.copy(new File(htRootPath, "env/grafics/empty.gif"), new File(htDocsPath, "notifier.gif")); } catch (IOException e) {} <MASK>if (!(htDocsPath.exists())) htDocsPath.mkdir();</MASK> final File htdocsDefaultReadme = new File(htDocsPath, "readme.txt"); if (!(htdocsDefaultReadme.exists())) try {serverFileUtils.write(( "This is your root directory for individual Web Content\r\n" + "\r\n" + "Please place your html files into the www subdirectory.\r\n" + "The URL of that path is either\r\n" + "http://www.<your-peer-name>.yacy or\r\n" + "http://<your-ip>:<your-port>/www\r\n" + "\r\n" + "Other subdirectories may be created; they map to corresponding sub-domains.\r\n" + "This directory shares it's content with the applications htroot path, so you\r\n" + "may access your yacy search page with\r\n" + "http://<your-peer-name>.yacy/\r\n" + "\r\n").getBytes(), htdocsDefaultReadme);} catch (IOException e) { System.out.println("Error creating htdocs readme: " + e.getMessage()); } final File wwwDefaultPath = new File(htDocsPath, "www"); if (!(wwwDefaultPath.exists())) wwwDefaultPath.mkdir(); final File shareDefaultPath = new File(htDocsPath, "share"); if (!(shareDefaultPath.exists())) shareDefaultPath.mkdir(); migration.migrate(sb, oldRev, newRev); // start main threads final String port = sb.getConfig("port", "8080"); try { final httpd protocolHandler = new httpd(sb, new httpdFileHandler(sb), new httpdProxyHandler(sb)); final serverCore server = new serverCore( timeout /*control socket timeout in milliseconds*/, true /* block attacks (wrong protocol) */, protocolHandler /*command class*/, sb, 30000 /*command max length incl. GET args*/); server.setName("httpd:"+port); server.setPriority(Thread.MAX_PRIORITY); server.setObeyIntermission(false); if (server == null) { serverLog.logSevere("STARTUP", "Failed to start server. Probably port " + port + " already in use."); } else { // first start the server sb.deployThread("10_httpd", "HTTPD Server/Proxy", "the HTTPD, used as web server and proxy", null, server, 0, 0, 0, 0); //server.start(); // open the browser window final boolean browserPopUpTrigger = sb.getConfig("browserPopUpTrigger", "true").equals("true"); if (browserPopUpTrigger) { String browserPopUpPage = sb.getConfig("browserPopUpPage", "ConfigBasic.html"); boolean properPW = (sb.getConfig("adminAccount", "").length() == 0) && (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0); if (!properPW) browserPopUpPage = "ConfigBasic.html"; final String browserPopUpApplication = sb.getConfig("browserPopUpApplication", "netscape"); serverSystem.openBrowser((server.withSSL()?"https":"http") + "://localhost:" + serverCore.getPortNr(port) + "/" + browserPopUpPage, browserPopUpApplication); } //Copy the shipped locales into DATA final File localesPath = new File(homePath, sb.getConfig("localesPath", "DATA/LOCALE")); final File defaultLocalesPath = new File(homePath, "locales"); try{ final File[] defaultLocales = defaultLocalesPath.listFiles(); localesPath.mkdirs(); for(int i=0;i < defaultLocales.length; i++){ if(defaultLocales[i].getName().endsWith(".lng")) serverFileUtils.copy(defaultLocales[i], new File(localesPath, defaultLocales[i].getName())); } serverLog.logInfo("STARTUP", "Copied the default locales to DATA/LOCALE"); }catch(NullPointerException e){ serverLog.logSevere("STARTUP", "Nullpointer Exception while copying the default Locales"); } //regenerate Locales from Translationlist, if needed final String lang = sb.getConfig("htLocaleSelection", ""); if(! lang.equals("") && ! lang.equals("default") ){ //locale is used String currentRev = ""; try{ final BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File( sb.getConfig("htLocalePath", "DATA/HTDOCS/locale"), lang+"/version" )))); currentRev = br.readLine(); br.close(); }catch(IOException e){ //Error } try{ //seperate try, because we want this, even if the file "version" does not exist. if(! currentRev.equals(sb.getConfig("svnRevision", "")) ){ //is this another version?! final File sourceDir = new File(sb.getConfig("htRootPath", "htroot")); final File destDir = new File(sb.getConfig("htLocalePath", "DATA/HTDOCS/locale"), lang); if(translator.translateFilesRecursive(sourceDir, destDir, new File("DATA/LOCALE/"+lang+".lng"), "html,template,inc", "locale")){ //translate it //write the new Versionnumber final BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(new File(destDir, "version")))); bw.write(sb.getConfig("svnRevision", "Error getting Version")); bw.close(); } } }catch(IOException e){ //Error } } // registering shutdown hook serverLog.logConfig("STARTUP", "Registering Shutdown Hook"); final Runtime run = Runtime.getRuntime(); run.addShutdownHook(new shutdownHookThread(Thread.currentThread(), sb)); // save information about available memory after all initializations //try { sb.setConfig("memoryFreeAfterInitBGC", Runtime.getRuntime().freeMemory()); sb.setConfig("memoryTotalAfterInitBGC", Runtime.getRuntime().totalMemory()); System.gc(); sb.setConfig("memoryFreeAfterInitAGC", Runtime.getRuntime().freeMemory()); sb.setConfig("memoryTotalAfterInitAGC", Runtime.getRuntime().totalMemory()); //} catch (ConcurrentModificationException e) {} // wait for server shutdown try { sb.waitForShutdown(); } catch (Exception e) { serverLog.logSevere("MAIN CONTROL LOOP", "PANIC: " + e.getMessage(),e); } // shut down serverLog.logConfig("SHUTDOWN", "caught termination signal"); server.terminate(false); server.interrupt(); if (server.isAlive()) try { URL u = new URL((server.withSSL()?"https":"http")+"://localhost:" + serverCore.getPortNr(port)); httpc.wget(u, u.getHost(), 1000, null, null, null); // kick server serverLog.logConfig("SHUTDOWN", "sent termination signal to server socket"); } catch (IOException ee) { serverLog.logConfig("SHUTDOWN", "termination signal to server socket missed (server shutdown, ok)"); } // idle until the processes are down while (server.isAlive()) { Thread.sleep(2000); // wait a while } serverLog.logConfig("SHUTDOWN", "server has terminated"); sb.close(); } } catch (Exception e) { serverLog.logSevere("STARTUP", "Unexpected Error: " + e.getClass().getName(),e); //System.exit(1); } } catch (Exception ee) { serverLog.logSevere("STARTUP", "FATAL ERROR: " + ee.getMessage(),ee); } serverLog.logConfig("SHUTDOWN", "goodbye. (this is the last line)"); try { System.exit(0); } catch (Exception e) {} // was once stopped by de.anomic.net.ftpc$sm.checkExit(ftpc.java:1790) }"
Inversion-Mutation
megadiff
"private void fireOnOpen() { if (openHandler_ == null) { return; } final Scriptable scope = openHandler_.getParentScope(); final JavaScriptEngine jsEngine = containingPage_.getWebClient().getJavaScriptEngine(); jsEngine.callFunction(containingPage_, openHandler_, scope, WebSocket.this, ArrayUtils.EMPTY_OBJECT_ARRAY); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "fireOnOpen"
"private void fireOnOpen() { <MASK>final Scriptable scope = openHandler_.getParentScope();</MASK> if (openHandler_ == null) { return; } final JavaScriptEngine jsEngine = containingPage_.getWebClient().getJavaScriptEngine(); jsEngine.callFunction(containingPage_, openHandler_, scope, WebSocket.this, ArrayUtils.EMPTY_OBJECT_ARRAY); }"
Inversion-Mutation
megadiff
"public TextField(String label, String text, int maxSize, int constraints) { super(label); super.setUI(DeviceFactory.getDevice().getUIFactory().createTextFieldUI(this)); if (maxSize <= 0) { throw new IllegalArgumentException(); } setConstraints(constraints); if (!InputMethod.validate(text, constraints)) { throw new IllegalArgumentException(); } stringComponent = new StringComponent(); if (text != null) { setString(text); } else { setString(""); } setMaxSize(maxSize); stringComponent.setWidthDecreaser(8); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "TextField"
"public TextField(String label, String text, int maxSize, int constraints) { super(label); super.setUI(DeviceFactory.getDevice().getUIFactory().createTextFieldUI(this)); if (maxSize <= 0) { throw new IllegalArgumentException(); } setConstraints(constraints); if (!InputMethod.validate(text, constraints)) { throw new IllegalArgumentException(); } <MASK>setMaxSize(maxSize);</MASK> stringComponent = new StringComponent(); if (text != null) { setString(text); } else { setString(""); } stringComponent.setWidthDecreaser(8); }"
Inversion-Mutation
megadiff
"public static void main(String[] args) { DrawingPanel form = new DrawingPanel(); JFrame frame = new JFrame("Bouncy Balls"); frame.setSize(600, 600); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(form); frame.setVisible(true); }"
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) { DrawingPanel form = new DrawingPanel(); JFrame frame = new JFrame("Bouncy Balls"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(form); <MASK>frame.setSize(600, 600);</MASK> frame.setVisible(true); }"
Inversion-Mutation
megadiff
"private static String getCurrentDateString() { Date currentDate; int month, day, year, hour, min, sec; String output=""; currentDate = new Date(); month = (currentDate.getMonth()+1)%12; day = currentDate.getDate(); year = currentDate.getYear()+1900; hour = (currentDate.getHours()+2)%24; min = currentDate.getMinutes(); sec = currentDate.getSeconds(); output+=Integer.toString(year); output +="."; if(month < 10) output += "0"; output += Integer.toString(month); output +="."; if(day < 10) output += "0"; output +=Integer.toString(day); output +="."; if(hour < 10) output += "0"; output +=Integer.toString(hour); output +="."; if(min < 10) output += "0"; output +=Integer.toString(min); output +="."; if(sec < 10) output += "0"; output +=Integer.toString(sec); return output; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getCurrentDateString"
"private static String getCurrentDateString() { Date currentDate; int month, day, year, hour, min, sec; String output=""; currentDate = new Date(); month = (currentDate.getMonth()+1)%12; day = currentDate.getDate(); year = currentDate.getYear()+1900; hour = (currentDate.getHours()+2)%24; min = currentDate.getMinutes(); sec = currentDate.getSeconds(); output+=Integer.toString(year); if(month < 10) output += "0"; output += Integer.toString(month); <MASK>output +=".";</MASK> if(day < 10) output += "0"; output +=Integer.toString(day); <MASK>output +=".";</MASK> <MASK>output +=".";</MASK> if(hour < 10) output += "0"; output +=Integer.toString(hour); <MASK>output +=".";</MASK> if(min < 10) output += "0"; output +=Integer.toString(min); <MASK>output +=".";</MASK> if(sec < 10) output += "0"; output +=Integer.toString(sec); return output; }"
Inversion-Mutation
megadiff
"public static BroadcastGroupConfiguration randomBroadcastGroupConfiguration(List<Pair<String, String>> connectorInfos) { return new BroadcastGroupConfiguration(randomString(), randomPort(), "231.7.7.7", 1199, randomPositiveInt(), connectorInfos); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "randomBroadcastGroupConfiguration"
"public static BroadcastGroupConfiguration randomBroadcastGroupConfiguration(List<Pair<String, String>> connectorInfos) { return new BroadcastGroupConfiguration(randomString(), randomPort(), "231.7.7.7", <MASK>randomPositiveInt(),</MASK> 1199, connectorInfos); }"
Inversion-Mutation
megadiff
"private void saveState() { mDbHelper.updateDiyActions(mRowId, maction_notification_param_www_text.getText().toString(),// maction_notification_param_www_switch.isChecked(),// // TEMPLATE: m{lowercase}.{retrieve}(),// maction_wifi.isChecked(),// maction_wifi_param_turn_on.isChecked(),// maction_wifi_param_turn_off.isChecked(),// maction_wifi_param_ssid.getText().toString(),// maction_notification.isChecked(),// maction_notification_param_title.getText().toString(),// maction_notification_param_text.getText().toString(),// maction_widgettext.isChecked(),// maction_widgettext_param_text.getText().toString(),// maction_widgettext_param_display_date.isChecked(),// maction_widgettext_param_display_coordinates.isChecked(),// maction_widgettext_param_display_address.isChecked(),// maction_widgettext_param_display_wifissid.isChecked(),// maction_widgettext_param_display_action_description.isChecked(),// maction_soundprofile.isChecked(),// maction_soundprofile_param_profile_sound.isChecked(),// maction_soundprofile_param_profile_vibrations.isChecked(),// maction_soundprofile_param_volume.getProgress());// }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "saveState"
"private void saveState() { mDbHelper.updateDiyActions(mRowId, maction_notification_param_www_text.getText().toString(),// maction_notification_param_www_switch.isChecked(),// // TEMPLATE: m{lowercase}.{retrieve}(),// maction_wifi.isChecked(),// maction_wifi_param_turn_on.isChecked(),// maction_wifi_param_turn_off.isChecked(),// maction_wifi_param_ssid.getText().toString(),// maction_notification.isChecked(),// maction_notification_param_title.getText().toString(),// maction_notification_param_text.getText().toString(),// maction_widgettext.isChecked(),// maction_widgettext_param_text.getText().toString(),// maction_widgettext_param_display_date.isChecked(),// maction_widgettext_param_display_coordinates.isChecked(),// maction_widgettext_param_display_address.isChecked(),// maction_widgettext_param_display_wifissid.isChecked(),// maction_widgettext_param_display_action_description.isChecked(),// maction_soundprofile_param_profile_sound.isChecked(),// maction_soundprofile_param_profile_vibrations.isChecked(),// <MASK>maction_soundprofile.isChecked(),//</MASK> maction_soundprofile_param_volume.getProgress());// }"
Inversion-Mutation
megadiff
"@Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); Intent intent = getIntent(); QRCodeUrlAnalyser qrCodeUrlAnalyser = new QRCodeUrlAnalyser(); if(Intent.ACTION_VIEW.equals(intent.getAction()) || NFC_INTENT.equals(intent.getAction())){ qrCodeUrlAnalyser.startWizardCauseOfUriInput(intent.getDataString(), this); }else if (loginmanager.getAllLoginSets().size() < 1) { showStartupWizard(); } Settings settings = ((SchoolPlannerApp)getApplication()).getSettings(); String autoLoginSetString = settings.getAutoLoginSet(); if(settings.isAutoLogin() && !autoLoginSetString.equals("")) { LoginSet loginSet = loginmanager.getLoginSet(autoLoginSetString); // Kann auftreten, wenn LoginSet als AutoLogin ausgewaehlt und dann geloescht wurde if(loginSet != null) { loginListener.performLogin(loginSet); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPostCreate"
"@Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); Intent intent = getIntent(); <MASK>if(Intent.ACTION_VIEW.equals(intent.getAction()) || NFC_INTENT.equals(intent.getAction())){</MASK> QRCodeUrlAnalyser qrCodeUrlAnalyser = new QRCodeUrlAnalyser(); qrCodeUrlAnalyser.startWizardCauseOfUriInput(intent.getDataString(), this); }else if (loginmanager.getAllLoginSets().size() < 1) { showStartupWizard(); } Settings settings = ((SchoolPlannerApp)getApplication()).getSettings(); String autoLoginSetString = settings.getAutoLoginSet(); if(settings.isAutoLogin() && !autoLoginSetString.equals("")) { LoginSet loginSet = loginmanager.getLoginSet(autoLoginSetString); // Kann auftreten, wenn LoginSet als AutoLogin ausgewaehlt und dann geloescht wurde if(loginSet != null) { loginListener.performLogin(loginSet); } } }"
Inversion-Mutation
megadiff
"public ZooKeeperWatcher(Configuration conf, String descriptor, Abortable abortable) throws IOException { this.quorum = ZKConfig.getZKQuorumServersString(conf); // Identifier will get the sessionid appended later below down when we // handle the syncconnect event. this.identifier = descriptor; this.abortable = abortable; setNodeNames(conf); this.zooKeeper = ZKUtil.connect(conf, quorum, this, descriptor); try { // Create all the necessary "directories" of znodes // TODO: Move this to an init method somewhere so not everyone calls it? ZKUtil.createAndFailSilent(this, baseZNode); ZKUtil.createAndFailSilent(this, assignmentZNode); ZKUtil.createAndFailSilent(this, rsZNode); ZKUtil.createAndFailSilent(this, tableZNode); } catch (KeeperException e) { LOG.error(prefix("Unexpected KeeperException creating base node"), e); throw new IOException(e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "ZooKeeperWatcher"
"public ZooKeeperWatcher(Configuration conf, String descriptor, Abortable abortable) throws IOException { this.quorum = ZKConfig.getZKQuorumServersString(conf); <MASK>this.zooKeeper = ZKUtil.connect(conf, quorum, this, descriptor);</MASK> // Identifier will get the sessionid appended later below down when we // handle the syncconnect event. this.identifier = descriptor; this.abortable = abortable; setNodeNames(conf); try { // Create all the necessary "directories" of znodes // TODO: Move this to an init method somewhere so not everyone calls it? ZKUtil.createAndFailSilent(this, baseZNode); ZKUtil.createAndFailSilent(this, assignmentZNode); ZKUtil.createAndFailSilent(this, rsZNode); ZKUtil.createAndFailSilent(this, tableZNode); } catch (KeeperException e) { LOG.error(prefix("Unexpected KeeperException creating base node"), e); throw new IOException(e); } }"
Inversion-Mutation
megadiff
"public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayShowTitleEnabled(false); actionBar.setDisplayShowHomeEnabled(false); setContentView(R.layout.activity_main); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setOnPageChangeListener( new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); TabListener tabListener = new ActionBar.TabListener() { public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabReselected(Tab arg0, FragmentTransaction arg1) { } @Override public void onTabUnselected(Tab arg0, FragmentTransaction arg1) { } }; actionBar.addTab(actionBar.newTab() .setText(R.string.title_server) .setTabListener(tabListener)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_route) .setTabListener(tabListener)); ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); final SharedPreferences prefs = getSharedPreferences("preferences.db", 0); if (!wifi.isConnected() && !prefs.getBoolean("wifi_skip_dialog", false)) { View checkBoxView = View.inflate(this, R.layout.dialog_wifi_disabled, null); CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.dont_show_again); checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { prefs.edit().putBoolean("wifi_skip_dialog", isChecked) .commit(); } }); new AlertDialog.Builder(this) .setView(checkBoxView) .setTitle(R.string.warning_wifi_not_connected) .setPositiveButton(android.R.string.ok, null) .show(); } if (savedInstanceState != null) { FragmentManager fm = getSupportFragmentManager(); mServerFragment = (ServerFragment) fm.getFragment( savedInstanceState, ServerFragment.class.getName()); mRouteFragment = (RouteFragment) fm.getFragment( savedInstanceState, RouteFragment.class.getName()); mViewPager.setCurrentItem(savedInstanceState.getInt("currentTab")); } else { mServerFragment = new ServerFragment(); mRouteFragment = new RouteFragment(); } onNewIntent(getIntent()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate"
"public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); <MASK>onNewIntent(getIntent());</MASK> final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayShowTitleEnabled(false); actionBar.setDisplayShowHomeEnabled(false); setContentView(R.layout.activity_main); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setOnPageChangeListener( new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); TabListener tabListener = new ActionBar.TabListener() { public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabReselected(Tab arg0, FragmentTransaction arg1) { } @Override public void onTabUnselected(Tab arg0, FragmentTransaction arg1) { } }; actionBar.addTab(actionBar.newTab() .setText(R.string.title_server) .setTabListener(tabListener)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_route) .setTabListener(tabListener)); ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); final SharedPreferences prefs = getSharedPreferences("preferences.db", 0); if (!wifi.isConnected() && !prefs.getBoolean("wifi_skip_dialog", false)) { View checkBoxView = View.inflate(this, R.layout.dialog_wifi_disabled, null); CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.dont_show_again); checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { prefs.edit().putBoolean("wifi_skip_dialog", isChecked) .commit(); } }); new AlertDialog.Builder(this) .setView(checkBoxView) .setTitle(R.string.warning_wifi_not_connected) .setPositiveButton(android.R.string.ok, null) .show(); } if (savedInstanceState != null) { FragmentManager fm = getSupportFragmentManager(); mServerFragment = (ServerFragment) fm.getFragment( savedInstanceState, ServerFragment.class.getName()); mRouteFragment = (RouteFragment) fm.getFragment( savedInstanceState, RouteFragment.class.getName()); mViewPager.setCurrentItem(savedInstanceState.getInt("currentTab")); } else { mServerFragment = new ServerFragment(); mRouteFragment = new RouteFragment(); } }"
Inversion-Mutation
megadiff
"public void actionPerformed(ActionEvent event) { logger.debug("About to change atom type of relevant atom!"); IChemObject object = getSource(event); logger.debug("Source of call: ", object); Iterator<IAtom> atomsInRange = null; if (object == null){ //this means the main menu was used if(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection()!=null && jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().isFilled()) atomsInRange=jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().getConnectedAtomContainer().atoms().iterator(); }else if (object instanceof IAtom) { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add((IAtom) object); atomsInRange = atoms.iterator(); } else { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getHighlightedAtom()); atomsInRange = atoms.iterator(); } String s = event.getActionCommand(); String symbol = s.substring(s.indexOf("@") + 1); if(symbol.equals("periodictable")){ if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), IBond.Stereo.NONE); newActiveModule.setID(symbol); jcpPanel.get2DHub().setActiveDrawModule(newActiveModule); // open PeriodicTable panel PeriodicTableDialog dialog = new PeriodicTableDialog(); dialog.setName("periodictabledialog"); symbol=dialog.getChoosenSymbol(); if(symbol.equals("")) return; jcpPanel.get2DHub().getController2DModel().setDrawElement(symbol); jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(0); jcpPanel.get2DHub().getController2DModel().setDrawPseudoAtom(false); }else if(symbol.equals("enterelement")){ newActiveModule=new EnterElementSwingModule(jcpPanel.get2DHub()); newActiveModule.setID(symbol); jcpPanel.get2DHub().setActiveDrawModule(newActiveModule); if(atomsInRange!=null){ String[] funcGroupsKeys=new String[0]; symbol=EnterElementOrGroupDialog.showDialog(null,null, "Enter an element symbol:", "Enter element", funcGroupsKeys, "",""); if(symbol!=null && symbol.length()>0){ if(Character.isLowerCase(symbol.toCharArray()[0])) symbol=Character.toUpperCase(symbol.charAt(0))+symbol.substring(1); IsotopeFactory ifa; try { ifa = IsotopeFactory.getInstance(jcpPanel.getChemModel().getBuilder()); IIsotope iso=ifa.getMajorIsotope(symbol); if(iso==null){ JOptionPane.showMessageDialog(jcpPanel, "No valid element symbol entered", "Invalid symbol", JOptionPane.WARNING_MESSAGE); return; } } catch (IOException e) { e.printStackTrace(); return; } } } }else{ //it must be a symbol if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), IBond.Stereo.NONE); newActiveModule.setID(symbol); jcpPanel.get2DHub().getController2DModel().setDrawElement(symbol); jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(0); jcpPanel.get2DHub().setActiveDrawModule(newActiveModule); } if(atomsInRange!=null){ while(atomsInRange.hasNext()){ IAtom atom = atomsInRange.next(); jcpPanel.get2DHub().setSymbol(atom,symbol); //TODO still needed? should this go in hub? // configure the atom, so that the atomic number matches the symbol try { IsotopeFactory.getInstance(atom.getBuilder()).configure(atom); } catch (Exception exception) { logger.error("Error while configuring atom"); logger.debug(exception); } } } jcpPanel.get2DHub().updateView(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "actionPerformed"
"public void actionPerformed(ActionEvent event) { logger.debug("About to change atom type of relevant atom!"); IChemObject object = getSource(event); logger.debug("Source of call: ", object); Iterator<IAtom> atomsInRange = null; if (object == null){ //this means the main menu was used if(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection()!=null && jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().isFilled()) atomsInRange=jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().getConnectedAtomContainer().atoms().iterator(); }else if (object instanceof IAtom) { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add((IAtom) object); atomsInRange = atoms.iterator(); } else { List<IAtom> atoms = new ArrayList<IAtom>(); atoms.add(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getHighlightedAtom()); atomsInRange = atoms.iterator(); } String s = event.getActionCommand(); String symbol = s.substring(s.indexOf("@") + 1); if(symbol.equals("periodictable")){ if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), IBond.Stereo.NONE); newActiveModule.setID(symbol); <MASK>jcpPanel.get2DHub().setActiveDrawModule(newActiveModule);</MASK> // open PeriodicTable panel PeriodicTableDialog dialog = new PeriodicTableDialog(); dialog.setName("periodictabledialog"); symbol=dialog.getChoosenSymbol(); if(symbol.equals("")) return; jcpPanel.get2DHub().getController2DModel().setDrawElement(symbol); jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(0); jcpPanel.get2DHub().getController2DModel().setDrawPseudoAtom(false); }else if(symbol.equals("enterelement")){ newActiveModule=new EnterElementSwingModule(jcpPanel.get2DHub()); newActiveModule.setID(symbol); <MASK>jcpPanel.get2DHub().setActiveDrawModule(newActiveModule);</MASK> if(atomsInRange!=null){ String[] funcGroupsKeys=new String[0]; symbol=EnterElementOrGroupDialog.showDialog(null,null, "Enter an element symbol:", "Enter element", funcGroupsKeys, "",""); if(symbol!=null && symbol.length()>0){ if(Character.isLowerCase(symbol.toCharArray()[0])) symbol=Character.toUpperCase(symbol.charAt(0))+symbol.substring(1); IsotopeFactory ifa; try { ifa = IsotopeFactory.getInstance(jcpPanel.getChemModel().getBuilder()); IIsotope iso=ifa.getMajorIsotope(symbol); if(iso==null){ JOptionPane.showMessageDialog(jcpPanel, "No valid element symbol entered", "Invalid symbol", JOptionPane.WARNING_MESSAGE); return; } } catch (IOException e) { e.printStackTrace(); return; } } } }else{ //it must be a symbol if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule) newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond()); else newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), IBond.Stereo.NONE); newActiveModule.setID(symbol); <MASK>jcpPanel.get2DHub().setActiveDrawModule(newActiveModule);</MASK> jcpPanel.get2DHub().getController2DModel().setDrawElement(symbol); jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(0); } if(atomsInRange!=null){ while(atomsInRange.hasNext()){ IAtom atom = atomsInRange.next(); jcpPanel.get2DHub().setSymbol(atom,symbol); //TODO still needed? should this go in hub? // configure the atom, so that the atomic number matches the symbol try { IsotopeFactory.getInstance(atom.getBuilder()).configure(atom); } catch (Exception exception) { logger.error("Error while configuring atom"); logger.debug(exception); } } } jcpPanel.get2DHub().updateView(); }"
Inversion-Mutation
megadiff
"@Override public boolean onMenuOpened(int featureId, Menu menu) { if (mInvalidateMenu) { if (menu != null) { menu.clear(); onCreateOptionsMenu(menu); } mInvalidateMenu = false; } return super.onMenuOpened(featureId, menu); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onMenuOpened"
"@Override public boolean onMenuOpened(int featureId, Menu menu) { if (mInvalidateMenu) { if (menu != null) { menu.clear(); } <MASK>onCreateOptionsMenu(menu);</MASK> mInvalidateMenu = false; } return super.onMenuOpened(featureId, menu); }"
Inversion-Mutation
megadiff
"public void run() { while (!stopShipping) { try { synchronized (forceFlushSemaphore) { shipALogChunk(); // Wake up a thread waiting for forceFlush, if any forceFlushSemaphore.notify(); } //calculate the shipping interval (wait time) based on the //fill information obtained from the log buffer. shippingInterval = calculateSIfromFI(); if (shippingInterval != -1) { synchronized(objLSTSync) { objLSTSync.wait(shippingInterval); } } } catch (InterruptedException ie) { //Interrupt the log shipping thread. return; } catch (IOException ioe) { //The transmitter is recreated if the connection to the //slave can be re-established. transmitter = masterController.handleExceptions(ioe); //The transmitter cannot be recreated hence stop the log //shipper thread. if (transmitter != null) { continue; } } catch (StandardException se) { masterController.handleExceptions(se); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { while (!stopShipping) { try { <MASK>shipALogChunk();</MASK> synchronized (forceFlushSemaphore) { // Wake up a thread waiting for forceFlush, if any forceFlushSemaphore.notify(); } //calculate the shipping interval (wait time) based on the //fill information obtained from the log buffer. shippingInterval = calculateSIfromFI(); if (shippingInterval != -1) { synchronized(objLSTSync) { objLSTSync.wait(shippingInterval); } } } catch (InterruptedException ie) { //Interrupt the log shipping thread. return; } catch (IOException ioe) { //The transmitter is recreated if the connection to the //slave can be re-established. transmitter = masterController.handleExceptions(ioe); //The transmitter cannot be recreated hence stop the log //shipper thread. if (transmitter != null) { continue; } } catch (StandardException se) { masterController.handleExceptions(se); } } }"
Inversion-Mutation
megadiff
"public void gotoMarker(IMarker marker) { if(marker == null || getModelObject() == null || !marker.exists()) return; String path = marker.getAttribute("path", null); //$NON-NLS-1$ if(path != null) { XModelObject o = getModelObject().getModel().getByPath(path); if(o == null) return; selectionProvider.setSelection(new StructuredSelection(o)); switchToPage(getSourcePageIndex()); postponedTextSelection.clean(); if(marker.getAttribute(IMarker.LINE_NUMBER, -1) != -1) { if(textEditor != null) textEditor.gotoMarker(marker); } else { String attr = marker.getAttribute("attribute", ""); //$NON-NLS-1$ //$NON-NLS-2$ if(attr == null || attr.length() == 0) { postponedTextSelection.select(o, null); } else { postponedTextSelection.select(o, attr); } } } else { postponedTextSelection.clean(); if(textEditor != null) { switchToPage(getSourcePageIndex()); textEditor.gotoMarker(marker); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "gotoMarker"
"public void gotoMarker(IMarker marker) { if(marker == null || getModelObject() == null || !marker.exists()) return; String path = marker.getAttribute("path", null); //$NON-NLS-1$ if(path != null) { XModelObject o = getModelObject().getModel().getByPath(path); if(o == null) return; selectionProvider.setSelection(new StructuredSelection(o)); switchToPage(getSourcePageIndex()); if(marker.getAttribute(IMarker.LINE_NUMBER, -1) != -1) { <MASK>postponedTextSelection.clean();</MASK> if(textEditor != null) textEditor.gotoMarker(marker); } else { String attr = marker.getAttribute("attribute", ""); //$NON-NLS-1$ //$NON-NLS-2$ if(attr == null || attr.length() == 0) { postponedTextSelection.select(o, null); } else { postponedTextSelection.select(o, attr); } } } else { <MASK>postponedTextSelection.clean();</MASK> if(textEditor != null) { switchToPage(getSourcePageIndex()); textEditor.gotoMarker(marker); } } }"
Inversion-Mutation
megadiff
"@Override public void enable() { addedTabs = new HashMap<WindowComponentPattern, ComponentPattern>(); for (ViewExtension viewExtension : viewExtensions) { ViewDefinition viewDefinition = viewDefinitionService.getWithoutSession(viewExtension.getPluginName(), viewExtension.getViewName()); Preconditions.checkNotNull(viewDefinition, getErrorMessage("reference to view which not exists", viewExtension)); for (Node tabNode : viewDefinitionParser.geElementChildren(viewExtension.getExtesionNode())) { WindowComponentPattern window = viewDefinition.getRootWindow(); Preconditions.checkNotNull(window, getErrorMessage("cannot add ribbon element to view", viewExtension)); ComponentPattern tabPattern = new WindowTabComponentPattern(viewDefinitionParser.getComponentDefinition(tabNode, window, viewDefinition)); tabPattern.parse(tabNode, viewDefinitionParser); window.addChild(tabPattern); addedTabs.put(window, tabPattern); tabPattern.initializeAll(); tabPattern.registerViews(viewDefinitionService); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "enable"
"@Override public void enable() { addedTabs = new HashMap<WindowComponentPattern, ComponentPattern>(); for (ViewExtension viewExtension : viewExtensions) { ViewDefinition viewDefinition = viewDefinitionService.getWithoutSession(viewExtension.getPluginName(), viewExtension.getViewName()); Preconditions.checkNotNull(viewDefinition, getErrorMessage("reference to view which not exists", viewExtension)); for (Node tabNode : viewDefinitionParser.geElementChildren(viewExtension.getExtesionNode())) { WindowComponentPattern window = viewDefinition.getRootWindow(); Preconditions.checkNotNull(window, getErrorMessage("cannot add ribbon element to view", viewExtension)); ComponentPattern tabPattern = new WindowTabComponentPattern(viewDefinitionParser.getComponentDefinition(tabNode, window, viewDefinition)); tabPattern.parse(tabNode, viewDefinitionParser); window.addChild(tabPattern); addedTabs.put(window, tabPattern); <MASK>tabPattern.registerViews(viewDefinitionService);</MASK> tabPattern.initializeAll(); } } }"
Inversion-Mutation
megadiff
"@Override public void onResume() { super.onResume(); setUpAdapter(); doResumeUpdates(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onResume"
"@Override public void onResume() { super.onResume(); <MASK>doResumeUpdates();</MASK> setUpAdapter(); }"
Inversion-Mutation
megadiff
"@Override public void paintComponent(final Graphics graphics) { final Graphics2D g = (Graphics2D) graphics; final Map desktopHints = (Map) Toolkit.getDefaultToolkit(). getDesktopProperty("awt.font.desktophints"); if (desktopHints != null) { g.addRenderingHints(desktopHints); } final float formatWidth = getWidth() - 6; final float formatHeight = getHeight(); float drawPosY = formatHeight; int startLine = scrollBarPosition; int useStartLine; int useStartChar; int useEndLine; int useEndChar; int paragraphStart; int paragraphEnd; LineBreakMeasurer lineMeasurer; g.setColor(textPane.getBackground()); g.fill(g.getClipBounds()); textLayouts.clear(); positions.clear(); //check theres something to draw if (document.getNumLines() == 0) { setCursor(Cursor.getDefaultCursor()); return; } //check there is some space to draw in if (formatWidth < 1) { setCursor(Cursor.getDefaultCursor()); return; } // Check the start line is in range if (startLine >= document.getNumLines()) { startLine = document.getNumLines() - 1; } if (startLine <= 0) { startLine = 0; } //sets the last visible line lastVisibleLine = startLine; firstVisibleLine = startLine; if (selStartLine > selEndLine) { // Swap both useStartLine = selEndLine; useStartChar = selEndChar; useEndLine = selStartLine; useEndChar = selStartChar; } else if (selStartLine == selEndLine && selStartChar > selEndChar) { // Just swap the chars useStartLine = selStartLine; useStartChar = selEndChar; useEndLine = selEndLine; useEndChar = selStartChar; } else { // Swap nothing useStartLine = selStartLine; useStartChar = selStartChar; useEndLine = selEndLine; useEndChar = selEndChar; } // Iterate through the lines for (int i = startLine; i >= 0; i--) { float drawPosX; final AttributedCharacterIterator iterator = document.getLine(i). getIterator(); paragraphStart = iterator.getBeginIndex(); paragraphEnd = iterator.getEndIndex(); lineMeasurer = new LineBreakMeasurer(iterator, g.getFontRenderContext()); lineMeasurer.setPosition(paragraphStart); final int wrappedLine; //do we have the line wrapping in the cache? if (lineWrap.containsKey(i)) { //use it wrappedLine = lineWrap.get(i); } else { //get it and populate the cache wrappedLine = getNumWrappedLines(lineMeasurer, paragraphStart, paragraphEnd, formatWidth); lineWrap.put(i, wrappedLine); } if (wrappedLine > 1) { drawPosY -= lineHeight * wrappedLine; } int j = 0; int chars = 0; // Loop through each wrapped line while (lineMeasurer.getPosition() < paragraphEnd) { final TextLayout layout = lineMeasurer.nextLayout(formatWidth); // Calculate the Y offset if (wrappedLine == 1) { drawPosY -= lineHeight; } else if (j != 0) { drawPosY += lineHeight; } // Calculate the initial X position if (layout.isLeftToRight()) { drawPosX = 3; } else { drawPosX = formatWidth - layout.getAdvance(); } // Check if the target is in range if (drawPosY >= 0 || drawPosY <= formatHeight) { g.setColor(textPane.getForeground()); layout.draw(g, drawPosX, drawPosY + lineHeight / 2f); doHighlight(i, useStartLine, useEndLine, useStartChar, useEndChar, chars, layout, g, drawPosY, drawPosX); firstVisibleLine = i; textLayouts.put(layout, new LineInfo(i, j)); positions.put(new Rectangle(0, (int) drawPosY, (int) formatWidth + 6, lineHeight), layout); } j++; chars += layout.getCharacterCount(); } if (j > 1) { drawPosY -= lineHeight * (wrappedLine - 1); } if (drawPosY <= 0) { break; } } checkForLink(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "paintComponent"
"@Override public void paintComponent(final Graphics graphics) { final Graphics2D g = (Graphics2D) graphics; final Map desktopHints = (Map) Toolkit.getDefaultToolkit(). getDesktopProperty("awt.font.desktophints"); if (desktopHints != null) { g.addRenderingHints(desktopHints); } final float formatWidth = getWidth() - 6; final float formatHeight = getHeight(); float drawPosY = formatHeight; int startLine = scrollBarPosition; int useStartLine; int useStartChar; int useEndLine; int useEndChar; int paragraphStart; int paragraphEnd; LineBreakMeasurer lineMeasurer; g.setColor(textPane.getBackground()); g.fill(g.getClipBounds()); textLayouts.clear(); positions.clear(); //check theres something to draw if (document.getNumLines() == 0) { setCursor(Cursor.getDefaultCursor()); return; } //check there is some space to draw in if (formatWidth < 1) { setCursor(Cursor.getDefaultCursor()); return; } // Check the start line is in range if (startLine >= document.getNumLines()) { startLine = document.getNumLines() - 1; } if (startLine <= 0) { startLine = 0; } //sets the last visible line lastVisibleLine = startLine; firstVisibleLine = startLine; if (selStartLine > selEndLine) { // Swap both useStartLine = selEndLine; useStartChar = selEndChar; useEndLine = selStartLine; useEndChar = selStartChar; } else if (selStartLine == selEndLine && selStartChar > selEndChar) { // Just swap the chars useStartLine = selStartLine; useStartChar = selEndChar; useEndLine = selEndLine; useEndChar = selStartChar; } else { // Swap nothing useStartLine = selStartLine; useStartChar = selStartChar; useEndLine = selEndLine; useEndChar = selEndChar; } // Iterate through the lines for (int i = startLine; i >= 0; i--) { float drawPosX; final AttributedCharacterIterator iterator = document.getLine(i). getIterator(); paragraphStart = iterator.getBeginIndex(); paragraphEnd = iterator.getEndIndex(); lineMeasurer = new LineBreakMeasurer(iterator, g.getFontRenderContext()); lineMeasurer.setPosition(paragraphStart); final int wrappedLine; //do we have the line wrapping in the cache? if (lineWrap.containsKey(i)) { //use it wrappedLine = lineWrap.get(i); } else { //get it and populate the cache wrappedLine = getNumWrappedLines(lineMeasurer, paragraphStart, paragraphEnd, formatWidth); lineWrap.put(i, wrappedLine); } if (wrappedLine > 1) { drawPosY -= lineHeight * wrappedLine; } int j = 0; int chars = 0; // Loop through each wrapped line while (lineMeasurer.getPosition() < paragraphEnd) { final TextLayout layout = lineMeasurer.nextLayout(formatWidth); // Calculate the Y offset if (wrappedLine == 1) { drawPosY -= lineHeight; } else if (j != 0) { drawPosY += lineHeight; } // Calculate the initial X position if (layout.isLeftToRight()) { drawPosX = 3; } else { drawPosX = formatWidth - layout.getAdvance(); } // Check if the target is in range if (drawPosY >= 0 || drawPosY <= formatHeight) { g.setColor(textPane.getForeground()); layout.draw(g, drawPosX, drawPosY + lineHeight / 2f); doHighlight(i, useStartLine, useEndLine, useStartChar, useEndChar, chars, layout, g, drawPosY, drawPosX); firstVisibleLine = i; textLayouts.put(layout, new LineInfo(i, j)); positions.put(new Rectangle(0, (int) drawPosY, (int) formatWidth + 6, lineHeight), layout); } j++; chars += layout.getCharacterCount(); } if (j > 1) { drawPosY -= lineHeight * (wrappedLine - 1); } if (drawPosY <= 0) { <MASK>checkForLink();</MASK> break; } } }"
Inversion-Mutation
megadiff
"private String applyFilter() { try { boolean passing = true; long vcfId = this.connection.getVcfId( this.vcfName); initializeVcf( vcfId ); ResultSet entries = this.connection.getVcfEntries( vcfId ); while (entries.next() ) { long entryId = entries.getLong("EntryId"); processUntestedEntry( entries ); passing = testEntry(entries); if (passing) { processPassingEntry(entries); passing = testIndividual(entries, entryId); if (passing) { finializeEntry(); } } } entries.close(); closeFiltering(); return getSuccessMessage(); } catch (Exception exception) { closeFiltering(); //TODO remove exception.printStackTrace(); return exception.getMessage(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "applyFilter"
"private String applyFilter() { try { boolean passing = true; long vcfId = this.connection.getVcfId( this.vcfName); initializeVcf( vcfId ); ResultSet entries = this.connection.getVcfEntries( vcfId ); while (entries.next() ) { processUntestedEntry( entries ); passing = testEntry(entries); <MASK>long entryId = entries.getLong("EntryId");</MASK> if (passing) { processPassingEntry(entries); passing = testIndividual(entries, entryId); if (passing) { finializeEntry(); } } } entries.close(); closeFiltering(); return getSuccessMessage(); } catch (Exception exception) { closeFiltering(); //TODO remove exception.printStackTrace(); return exception.getMessage(); } }"
Inversion-Mutation
megadiff
"private synchronized ValueTable getFirstTableWithVariable(String variableName) { if(variableNameToTableMap == null) { variableNameToTableMap = new HashMap<String, ValueTable>(); } ValueTable cachedTable = variableNameToTableMap.get(variableName); if(cachedTable != null) { return cachedTable; } else { for(ValueTable vt : tables) { if(vt.hasVariable(variableName)) { variableNameToTableMap.put(variableName, vt); return vt; } } } return null; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getFirstTableWithVariable"
"private synchronized ValueTable getFirstTableWithVariable(String variableName) { if(variableNameToTableMap == null) { variableNameToTableMap = new HashMap<String, ValueTable>(); } ValueTable cachedTable = variableNameToTableMap.get(variableName); if(cachedTable != null) { return cachedTable; } else { for(ValueTable vt : tables) { if(vt.hasVariable(variableName)) { variableNameToTableMap.put(variableName, vt); } <MASK>return vt;</MASK> } } return null; }"
Inversion-Mutation
megadiff
"public void notifyHeartbeat(HeartbeatData hbData) { lastHeartbeatDuration = 0; hbTime[rrdPtr] = System.currentTimeMillis(); if (hbData != null) { heapInitSize[rrdPtr] = hbData.heapInitSize; heapUsedSize[rrdPtr] = hbData.heapUsedSize; heapCommittedSize[rrdPtr] = hbData.heapCommittedSize; heapMaxSize[rrdPtr] = hbData.heapMaxSize; nonheapInitSize[rrdPtr] = hbData.nonheapInitSize; nonheapUsedSize[rrdPtr] = hbData.nonheapUsedSize; nonheapCommittedSize[rrdPtr] = hbData.nonheapCommittedSize; nonheapMaxSize[rrdPtr] = hbData.nonheapMaxSize; threadCount[rrdPtr] = hbData.threadCount; peakThreadCount[rrdPtr] = hbData.peakThreadCount; systemLoadAverage[rrdPtr] = hbData.systemLoadAverage; int gcN = hbSchema.getGarbageCollectorInfos().length; for (int i = 0; i < gcN; ++i) { gcCollectionCounts[i][rrdPtr] = hbData.gcCollectionCounts[i]; gcCollectionTimes[i][rrdPtr] = hbData.gcCollectionTimes[i]; } netPayloadBytesRead[rrdPtr] = hbData.netPayloadBytesRead; netPayloadBytesWritten[rrdPtr] = hbData.netPayloadBytesWritten; netSignalingBytesRead[rrdPtr] = hbData.netSignalingBytesRead; netSignalingBytesWritten[rrdPtr] = hbData.netSignalingBytesWritten; datasetNetPayloadBytesRead[rrdPtr] = hbData.datasetNetPayloadBytesRead; datasetNetPayloadBytesWritten[rrdPtr] = hbData.datasetNetPayloadBytesWritten; datasetNetSignalingBytesRead[rrdPtr] = hbData.datasetNetSignalingBytesRead; datasetNetSignalingBytesWritten[rrdPtr] = hbData.datasetNetSignalingBytesWritten; ipcMessagesSent[rrdPtr] = hbData.ipcMessagesSent; ipcMessageBytesSent[rrdPtr] = hbData.ipcMessageBytesSent; ipcMessagesReceived[rrdPtr] = hbData.ipcMessagesReceived; ipcMessageBytesReceived[rrdPtr] = hbData.ipcMessageBytesReceived; rrdPtr = (rrdPtr + 1) % RRD_SIZE; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "notifyHeartbeat"
"public void notifyHeartbeat(HeartbeatData hbData) { lastHeartbeatDuration = 0; hbTime[rrdPtr] = System.currentTimeMillis(); if (hbData != null) { heapInitSize[rrdPtr] = hbData.heapInitSize; heapUsedSize[rrdPtr] = hbData.heapUsedSize; heapCommittedSize[rrdPtr] = hbData.heapCommittedSize; heapMaxSize[rrdPtr] = hbData.heapMaxSize; nonheapInitSize[rrdPtr] = hbData.nonheapInitSize; nonheapUsedSize[rrdPtr] = hbData.nonheapUsedSize; nonheapCommittedSize[rrdPtr] = hbData.nonheapCommittedSize; nonheapMaxSize[rrdPtr] = hbData.nonheapMaxSize; threadCount[rrdPtr] = hbData.threadCount; peakThreadCount[rrdPtr] = hbData.peakThreadCount; systemLoadAverage[rrdPtr] = hbData.systemLoadAverage; int gcN = hbSchema.getGarbageCollectorInfos().length; for (int i = 0; i < gcN; ++i) { gcCollectionCounts[i][rrdPtr] = hbData.gcCollectionCounts[i]; gcCollectionTimes[i][rrdPtr] = hbData.gcCollectionTimes[i]; } netPayloadBytesRead[rrdPtr] = hbData.netPayloadBytesRead; netPayloadBytesWritten[rrdPtr] = hbData.netPayloadBytesWritten; netSignalingBytesRead[rrdPtr] = hbData.netSignalingBytesRead; netSignalingBytesWritten[rrdPtr] = hbData.netSignalingBytesWritten; datasetNetPayloadBytesRead[rrdPtr] = hbData.datasetNetPayloadBytesRead; datasetNetPayloadBytesWritten[rrdPtr] = hbData.datasetNetPayloadBytesWritten; datasetNetSignalingBytesRead[rrdPtr] = hbData.datasetNetSignalingBytesRead; datasetNetSignalingBytesWritten[rrdPtr] = hbData.datasetNetSignalingBytesWritten; ipcMessagesSent[rrdPtr] = hbData.ipcMessagesSent; ipcMessageBytesSent[rrdPtr] = hbData.ipcMessageBytesSent; ipcMessagesReceived[rrdPtr] = hbData.ipcMessagesReceived; ipcMessageBytesReceived[rrdPtr] = hbData.ipcMessageBytesReceived; } <MASK>rrdPtr = (rrdPtr + 1) % RRD_SIZE;</MASK> }"
Inversion-Mutation
megadiff
"@Override public void channelRead(ChannelHandlerContext ctx, Object m) throws Exception { if (!(m instanceof ByteBuf)) { conn.notifyRead(m); return; } ByteBuf data = (ByteBuf) m; if (remainder == null) { try { passToConnection(data); } finally { if (data.isReadable()) { remainder = data; } else { data.release(); } } return; } if (!bufferHasSufficientCapacity(remainder, data)) { ByteBuf combined = createCombinedBuffer(remainder, data, ctx); remainder.release(); remainder = combined; } else { remainder.writeBytes(data); } data.release(); try { passToConnection(remainder); } finally { if (remainder.isReadable()) { remainder.discardSomeReadBytes(); } else { remainder.release(); remainder = null; } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "channelRead"
"@Override public void channelRead(ChannelHandlerContext ctx, Object m) throws Exception { if (!(m instanceof ByteBuf)) { conn.notifyRead(m); <MASK>return;</MASK> } ByteBuf data = (ByteBuf) m; if (remainder == null) { try { passToConnection(data); } finally { if (data.isReadable()) { remainder = data; } else { data.release(); } <MASK>return;</MASK> } } if (!bufferHasSufficientCapacity(remainder, data)) { ByteBuf combined = createCombinedBuffer(remainder, data, ctx); remainder.release(); remainder = combined; } else { remainder.writeBytes(data); } data.release(); try { passToConnection(remainder); } finally { if (remainder.isReadable()) { remainder.discardSomeReadBytes(); } else { remainder.release(); remainder = null; } } }"
Inversion-Mutation
megadiff
"@Override public void onReceive( final Object msg ) throws Exception { if ( msg instanceof Passenger ) { Passenger p = (Passenger)msg; printMsg("Passenger " + p.getName() + " arrives in line"); // If msg is a Passenger, immediately send their luggage off to BaggageScan // and send them to the BodyScan if it's in a 'ready' state. Otherwise, add // them to the FIFO wait queue to be notified when the BodyScan requests the // next passenger to be scanned. printMsg("Passenger " + p.getName() + " baggage placed on scanner"); bagScanner.tell( msg ); if ( bodyScannerReady ) { printMsg("Passenger " + p.getName() + " enters the body scanner"); bodyScannerReady = false; bodyScanner.tell( msg, getContext() ); } else { passengersWaiting.add( 0, p ); } } else if ( msg instanceof NextMsg ) { // If msg is a NextMsg, the body scanner is marked ready if no passengers // are waiting. Otherwise, the first passenger is sent into the scanner. if ( passengersWaiting.isEmpty() ) { bodyScannerReady = true; // Check if we are trying to shutdown, this would be the right time if ( closeMsgReceived ) { bodyScanner.tell( new CloseMsg() ); printMsg("Close sent to body scanner"); getContext().stop(); printMsg("Closed"); } } else { Passenger p = passengersWaiting.remove( 0 ); bodyScanner.tell( p, getContext() ); } } else if ( msg instanceof CloseMsg ) { // If msg is a CloseMsg, message is relayed to the baggage scanner // immediately, and to the body scanner if it is in the ready state. // If the body scanner is still processing a passenger, and/or if // passengers are waiting in this queue, the CloseMsg must be deferred // until all passengers have been through the body scanner. closeMsgReceived = true; bagScanner.tell( msg ); if ( bodyScannerReady && passengersWaiting.isEmpty() ) { printMsg("Close sent to body scanner"); bodyScanner.tell( msg ); getContext().stop(); printMsg("Closed"); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onReceive"
"@Override public void onReceive( final Object msg ) throws Exception { if ( msg instanceof Passenger ) { Passenger p = (Passenger)msg; printMsg("Passenger " + p.getName() + " arrives in line"); // If msg is a Passenger, immediately send their luggage off to BaggageScan // and send them to the BodyScan if it's in a 'ready' state. Otherwise, add // them to the FIFO wait queue to be notified when the BodyScan requests the // next passenger to be scanned. printMsg("Passenger " + p.getName() + " baggage placed on scanner"); bagScanner.tell( msg ); if ( bodyScannerReady ) { printMsg("Passenger " + p.getName() + " enters the body scanner"); <MASK>bodyScanner.tell( msg, getContext() );</MASK> bodyScannerReady = false; } else { passengersWaiting.add( 0, p ); } } else if ( msg instanceof NextMsg ) { // If msg is a NextMsg, the body scanner is marked ready if no passengers // are waiting. Otherwise, the first passenger is sent into the scanner. if ( passengersWaiting.isEmpty() ) { bodyScannerReady = true; // Check if we are trying to shutdown, this would be the right time if ( closeMsgReceived ) { bodyScanner.tell( new CloseMsg() ); printMsg("Close sent to body scanner"); getContext().stop(); printMsg("Closed"); } } else { Passenger p = passengersWaiting.remove( 0 ); bodyScanner.tell( p, getContext() ); } } else if ( msg instanceof CloseMsg ) { // If msg is a CloseMsg, message is relayed to the baggage scanner // immediately, and to the body scanner if it is in the ready state. // If the body scanner is still processing a passenger, and/or if // passengers are waiting in this queue, the CloseMsg must be deferred // until all passengers have been through the body scanner. closeMsgReceived = true; bagScanner.tell( msg ); if ( bodyScannerReady && passengersWaiting.isEmpty() ) { printMsg("Close sent to body scanner"); bodyScanner.tell( msg ); getContext().stop(); printMsg("Closed"); } } }"
Inversion-Mutation
megadiff
"public IEvaluatedType evaluateGoal(IGoal rootGoal, long timeLimit) { if (rootGoal == null) return null; rootGoal = evaluatorFactory.translateGoal(rootGoal); totalGoalsRequested++; if (isInStack(rootGoal)) { totalRecursiveRequests++; return RecursionTypeCall.INSTANCE; } IEvaluatedType lastObtainedSubgoalResult = (IEvaluatedType) answersCache.get(rootGoal); if (lastObtainedSubgoalResult != null) { if (TRACE_GOALS) System.out.println("DDP root goal cache hit: " + rootGoal.toString()); cacheHits++; return lastObtainedSubgoalResult; } if (TRACE_GOALS) System.out.println("DDP root goal evaluation: " + rootGoal.toString() + (timeLimit > 0 ? " time limit: " + timeLimit : "")); long endTime = System.currentTimeMillis() + timeLimit; GoalEvaluator rootEvaluator = evaluatorFactory.createEvaluator(rootGoal); int emptyStackSize = stackSize; // there might already be some elements there pushToStack(rootEvaluator); IGoal lastFullyEvaluatedGoal = null; while(stackSize > emptyStackSize && (timeLimit == 0 || System.currentTimeMillis() < endTime)) { GoalEvaluator goal = peekStack(); IGoal subgoal = goal.produceNextSubgoal(lastFullyEvaluatedGoal, lastObtainedSubgoalResult); if (subgoal == null) { lastObtainedSubgoalResult = goal.produceType(); lastFullyEvaluatedGoal = goal.getGoal(); popStack(); totalGoalsCalculated++; } else { subgoal = evaluatorFactory.translateGoal(subgoal); totalGoalsRequested++; if (isInStack(subgoal)) { totalRecursiveRequests++; lastFullyEvaluatedGoal = subgoal; lastObtainedSubgoalResult = RecursionTypeCall.INSTANCE; } else { lastObtainedSubgoalResult = (IEvaluatedType) answersCache.get(subgoal); if (lastObtainedSubgoalResult != null) { cacheHits++; lastFullyEvaluatedGoal = subgoal; } else { lastFullyEvaluatedGoal = null; GoalEvaluator evaluator = evaluatorFactory.createEvaluator(subgoal); if (evaluator == null) { if (TRACE_GOALS) System.out.println("DDP no evaluator for goal: " + subgoal); lastFullyEvaluatedGoal = subgoal; } else { pushToStack(evaluator); } } } } } boolean timeLimitCondition = stackSize > emptyStackSize; while (stackSize > emptyStackSize) { GoalEvaluator goal = popStack(); // tell the IGoal subgoal = goal.produceNextSubgoal(lastFullyEvaluatedGoal, lastObtainedSubgoalResult); if (TRACE_TIME_LIMIT_RECOVERY && subgoal != null) System.out.println("DDP goal ignored due to time limit: " + subgoal.toString()); lastObtainedSubgoalResult = goal.produceType(); lastFullyEvaluatedGoal = goal.getGoal(); } if (TRACE_GOALS || SHOW_STATISTICS) System.out.println("DDP root goal done: " + rootGoal.toString() + ", answer is " + String.valueOf(lastObtainedSubgoalResult) + (timeLimitCondition ? " [time limit exceeded]" : "")); if (SHOW_STATISTICS) { System.out.println("Time spent: " + (System.currentTimeMillis() - endTime + timeLimit) + " ms"); System.out.println("Total goals requested: " + totalGoalsRequested); System.out.println("Total goals calculated: " + totalGoalsCalculated); System.out.println("Total cache hits: " + cacheHits); System.out.println("Maximal stack size: " + maxStackSize); System.out.println("Cached goal answers: " + answersCache.size()); System.out.println(); } return lastObtainedSubgoalResult; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "evaluateGoal"
"public IEvaluatedType evaluateGoal(IGoal rootGoal, long timeLimit) { <MASK>rootGoal = evaluatorFactory.translateGoal(rootGoal);</MASK> if (rootGoal == null) return null; totalGoalsRequested++; if (isInStack(rootGoal)) { totalRecursiveRequests++; return RecursionTypeCall.INSTANCE; } IEvaluatedType lastObtainedSubgoalResult = (IEvaluatedType) answersCache.get(rootGoal); if (lastObtainedSubgoalResult != null) { if (TRACE_GOALS) System.out.println("DDP root goal cache hit: " + rootGoal.toString()); cacheHits++; return lastObtainedSubgoalResult; } if (TRACE_GOALS) System.out.println("DDP root goal evaluation: " + rootGoal.toString() + (timeLimit > 0 ? " time limit: " + timeLimit : "")); long endTime = System.currentTimeMillis() + timeLimit; GoalEvaluator rootEvaluator = evaluatorFactory.createEvaluator(rootGoal); int emptyStackSize = stackSize; // there might already be some elements there pushToStack(rootEvaluator); IGoal lastFullyEvaluatedGoal = null; while(stackSize > emptyStackSize && (timeLimit == 0 || System.currentTimeMillis() < endTime)) { GoalEvaluator goal = peekStack(); IGoal subgoal = goal.produceNextSubgoal(lastFullyEvaluatedGoal, lastObtainedSubgoalResult); if (subgoal == null) { lastObtainedSubgoalResult = goal.produceType(); lastFullyEvaluatedGoal = goal.getGoal(); popStack(); totalGoalsCalculated++; } else { subgoal = evaluatorFactory.translateGoal(subgoal); totalGoalsRequested++; if (isInStack(subgoal)) { totalRecursiveRequests++; lastFullyEvaluatedGoal = subgoal; lastObtainedSubgoalResult = RecursionTypeCall.INSTANCE; } else { lastObtainedSubgoalResult = (IEvaluatedType) answersCache.get(subgoal); if (lastObtainedSubgoalResult != null) { cacheHits++; lastFullyEvaluatedGoal = subgoal; } else { lastFullyEvaluatedGoal = null; GoalEvaluator evaluator = evaluatorFactory.createEvaluator(subgoal); if (evaluator == null) { if (TRACE_GOALS) System.out.println("DDP no evaluator for goal: " + subgoal); lastFullyEvaluatedGoal = subgoal; } else { pushToStack(evaluator); } } } } } boolean timeLimitCondition = stackSize > emptyStackSize; while (stackSize > emptyStackSize) { GoalEvaluator goal = popStack(); // tell the IGoal subgoal = goal.produceNextSubgoal(lastFullyEvaluatedGoal, lastObtainedSubgoalResult); if (TRACE_TIME_LIMIT_RECOVERY && subgoal != null) System.out.println("DDP goal ignored due to time limit: " + subgoal.toString()); lastObtainedSubgoalResult = goal.produceType(); lastFullyEvaluatedGoal = goal.getGoal(); } if (TRACE_GOALS || SHOW_STATISTICS) System.out.println("DDP root goal done: " + rootGoal.toString() + ", answer is " + String.valueOf(lastObtainedSubgoalResult) + (timeLimitCondition ? " [time limit exceeded]" : "")); if (SHOW_STATISTICS) { System.out.println("Time spent: " + (System.currentTimeMillis() - endTime + timeLimit) + " ms"); System.out.println("Total goals requested: " + totalGoalsRequested); System.out.println("Total goals calculated: " + totalGoalsCalculated); System.out.println("Total cache hits: " + cacheHits); System.out.println("Maximal stack size: " + maxStackSize); System.out.println("Cached goal answers: " + answersCache.size()); System.out.println(); } return lastObtainedSubgoalResult; }"
Inversion-Mutation
megadiff
"@Override public void run() { int count = 0; int total = 0; String prefix = mVideoListActivity.getResources().getString(R.string.thumbnail); while (!isInterrupted()) { lock.lock(); // Get the id of the file browser item to create its thumbnail. boolean killed = false; while (mItems.size() == 0) { try { Log.i(TAG, "hide ProgressBar!"); MainActivity.hideProgressBar(mVideoListActivity.getActivity()); MainActivity.clearTextInfo(mVideoListActivity.getActivity()); notEmpty.await(); } catch (InterruptedException e) { killed = true; break; } } if (killed) break; total = totalCount; Media item = mItems.poll(); lock.unlock(); MainActivity.showProgressBar(mVideoListActivity.getActivity()); Log.i(TAG, "show ProgressBar!"); MainActivity.sendTextInfo(mVideoListActivity.getActivity(), String.format("%s %s", prefix, item.getFileName()), count, total); count++; int width = (int) (120 * mDensity); int height = (int) (120 * mDensity); // Get the thumbnail. Bitmap thumbnail = Bitmap.createBitmap(width, height, Config.ARGB_8888); //Log.i(TAG, "create new bitmap for: " + item.getName()); byte[] b = mLibVlc.getThumbnail(item.getLocation(), width, height); // Activity stopped & destroyed, abort everything if (isInterrupted()) break; if (b == null) {// We were not able to create a thumbnail for this item. item.setPicture(mVideoListActivity.getActivity(), null); continue; } thumbnail.copyPixelsFromBuffer(ByteBuffer.wrap(b)); thumbnail = Util.cropBorders(thumbnail, width, height); Log.i(TAG, "Thumbnail created!"); item.setPicture(mVideoListActivity.getActivity(), thumbnail); // Post to the file browser the new item. mVideoListActivity.setItemToUpdate(item); // Wait for the file browser to process the change. try { mVideoListActivity.await(); } catch (InterruptedException e) { break; } catch (BrokenBarrierException e) { break; } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"@Override public void run() { int count = 0; int total = 0; String prefix = mVideoListActivity.getResources().getString(R.string.thumbnail); while (!isInterrupted()) { lock.lock(); // Get the id of the file browser item to create its thumbnail. boolean killed = false; while (mItems.size() == 0) { try { Log.i(TAG, "hide ProgressBar!"); MainActivity.hideProgressBar(mVideoListActivity.getActivity()); MainActivity.clearTextInfo(mVideoListActivity.getActivity()); notEmpty.await(); } catch (InterruptedException e) { killed = true; break; } } if (killed) break; total = totalCount; lock.unlock(); <MASK>Media item = mItems.poll();</MASK> MainActivity.showProgressBar(mVideoListActivity.getActivity()); Log.i(TAG, "show ProgressBar!"); MainActivity.sendTextInfo(mVideoListActivity.getActivity(), String.format("%s %s", prefix, item.getFileName()), count, total); count++; int width = (int) (120 * mDensity); int height = (int) (120 * mDensity); // Get the thumbnail. Bitmap thumbnail = Bitmap.createBitmap(width, height, Config.ARGB_8888); //Log.i(TAG, "create new bitmap for: " + item.getName()); byte[] b = mLibVlc.getThumbnail(item.getLocation(), width, height); // Activity stopped & destroyed, abort everything if (isInterrupted()) break; if (b == null) {// We were not able to create a thumbnail for this item. item.setPicture(mVideoListActivity.getActivity(), null); continue; } thumbnail.copyPixelsFromBuffer(ByteBuffer.wrap(b)); thumbnail = Util.cropBorders(thumbnail, width, height); Log.i(TAG, "Thumbnail created!"); item.setPicture(mVideoListActivity.getActivity(), thumbnail); // Post to the file browser the new item. mVideoListActivity.setItemToUpdate(item); // Wait for the file browser to process the change. try { mVideoListActivity.await(); } catch (InterruptedException e) { break; } catch (BrokenBarrierException e) { break; } } }"
Inversion-Mutation
megadiff
"@Override protected void doHandler(HttpServletRequest request, HttpServletResponse response, PageContext pageContext, SectionDefinition sectionDefinition, List<SectionField> sectionFields, SectionField currentField, TangerineForm form, String formFieldName, Object fieldValue, StringBuilder sb) { Picklist picklist = resolvePicklist(currentField, pageContext); createTop(request, pageContext, sb); createContainerBegin(request, pageContext, sb); createMultiPicklistBegin(currentField, formFieldName, picklist, sb); createLeft(sb); String selectedRefs = createMultiPicklistOptions(pageContext, picklist, fieldValue, sb); createLabelTextInput(pageContext, currentField, formFieldName, sb); createRight(sb); /* Add the additional elements - only difference between this and MultiPicklistHandler */ createAdditionalFields(currentField, form, formFieldName, sb); createAdditionalFieldClone(sb); createMultiPicklistEnd(sb); createHiddenInput(currentField, formFieldName, fieldValue, sb); createContainerEnd(sb); createBottom(request, pageContext, sb); createSelectedRefs(formFieldName, selectedRefs, sb); createLookupLink(sb); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doHandler"
"@Override protected void doHandler(HttpServletRequest request, HttpServletResponse response, PageContext pageContext, SectionDefinition sectionDefinition, List<SectionField> sectionFields, SectionField currentField, TangerineForm form, String formFieldName, Object fieldValue, StringBuilder sb) { Picklist picklist = resolvePicklist(currentField, pageContext); createTop(request, pageContext, sb); createContainerBegin(request, pageContext, sb); createMultiPicklistBegin(currentField, formFieldName, picklist, sb); createLeft(sb); String selectedRefs = createMultiPicklistOptions(pageContext, picklist, fieldValue, sb); createLabelTextInput(pageContext, currentField, formFieldName, sb); createRight(sb); <MASK>createMultiPicklistEnd(sb);</MASK> /* Add the additional elements - only difference between this and MultiPicklistHandler */ createAdditionalFields(currentField, form, formFieldName, sb); createAdditionalFieldClone(sb); createHiddenInput(currentField, formFieldName, fieldValue, sb); createContainerEnd(sb); createBottom(request, pageContext, sb); createSelectedRefs(formFieldName, selectedRefs, sb); createLookupLink(sb); }"
Inversion-Mutation
megadiff
"public void encodeBegin(FacesContext context) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.startElement("span", this); writer.writeAttribute("id", getClientId(context), null); writer.startElement("script", this); writer.writeAttribute("type", "text/javascript", null); writer.writeText("ice.setupRefresh('", null); writer.writeText(BridgeSetup.getViewID(context.getExternalContext()), null); writer.writeText("', ", null); writer.writeText(interval, null); writer.writeText(", ", null); writer.writeText(duration, null); writer.writeText(", '", null); writer.writeText(getClientId(context), null); writer.writeText("');", null); writer.endElement("script"); writer.endElement("span"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "encodeBegin"
"public void encodeBegin(FacesContext context) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.startElement("span", this); writer.writeAttribute("id", getClientId(context), null); writer.startElement("script", this); writer.writeAttribute("type", "text/javascript", null); writer.writeText("ice.setupRefresh('", null); writer.writeText(BridgeSetup.getViewID(context.getExternalContext()), null); writer.writeText("', ", null); writer.writeText(interval, null); writer.writeText(", ", null); writer.writeText(duration, null); writer.writeText(", '", null); writer.writeText(getClientId(context), null); writer.writeText("');", null); <MASK>writer.endElement("span");</MASK> writer.endElement("script"); }"
Inversion-Mutation
megadiff
"public DeviceFrame(Application app, AndroidDevice device) { this.app = app; this.device = device; this.log = Logger.getLogger(DeviceFrame.class.getName() + ":" + device.getName()); log.debug(String.format("DeviceFrame(device=%s)", device)); Settings cfg = app.getSettings(); setScale(cfg.getPreferredScale()); setLandscapeMode(cfg.isLandscape()); setTitle(device.getName()); setIconImage(GuiUtil.loadIcon("device").getImage()); setResizable(false); add(canvas = new ImageCanvas(), BorderLayout.CENTER); add(toolBar = createToolBar(), BorderLayout.WEST); add(infoPane = new InfoPane(), BorderLayout.SOUTH); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowStateListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { log.debug("windowClosing"); retriever.cancel(); timer.cancel(); DeviceFrame.this.setVisible(false); } }); setUpsideDown(cfg.isUpsideDown()); timer = new Timer("Screenshot Timer"); timer.schedule(retriever = new Retriever(), 0, 500); pack(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "DeviceFrame"
"public DeviceFrame(Application app, AndroidDevice device) { this.app = app; this.device = device; this.log = Logger.getLogger(DeviceFrame.class.getName() + ":" + device.getName()); log.debug(String.format("DeviceFrame(device=%s)", device)); Settings cfg = app.getSettings(); setScale(cfg.getPreferredScale()); setLandscapeMode(cfg.isLandscape()); <MASK>setUpsideDown(cfg.isUpsideDown());</MASK> setTitle(device.getName()); setIconImage(GuiUtil.loadIcon("device").getImage()); setResizable(false); add(canvas = new ImageCanvas(), BorderLayout.CENTER); add(toolBar = createToolBar(), BorderLayout.WEST); add(infoPane = new InfoPane(), BorderLayout.SOUTH); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowStateListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { log.debug("windowClosing"); retriever.cancel(); timer.cancel(); DeviceFrame.this.setVisible(false); } }); timer = new Timer("Screenshot Timer"); timer.schedule(retriever = new Retriever(), 0, 500); pack(); }"
Inversion-Mutation
megadiff
"public static Test suite() { TestSuite suite = new TestSuite("Test for org.eclipse.mylar.tests"); //$JUnit-BEGIN$ // NOTE: the order of these tests matters // TODO: make tests clear workbench state on completion suite.addTest(AllMonitorTests.suite()); suite.addTest(AllXmlTests.suite()); // HACK: first because it doesn't clean up properly suite.addTest(AllIdeTests.suite()); suite.addTest(AllJavaTests.suite()); suite.addTest(AllCoreTests.suite()); suite.addTest(AllTasklistTests.suite()); suite.addTest(AllBugzillaTests.suite()); suite.addTest(MiscTests.suite()); //$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.mylar.tests"); //$JUnit-BEGIN$ // NOTE: the order of these tests matters // TODO: make tests clear workbench state on completion suite.addTest(AllMonitorTests.suite()); suite.addTest(AllXmlTests.suite()); // HACK: first because it doesn't clean up properly suite.addTest(AllJavaTests.suite()); suite.addTest(AllCoreTests.suite()); suite.addTest(AllTasklistTests.suite()); suite.addTest(AllBugzillaTests.suite()); <MASK>suite.addTest(AllIdeTests.suite());</MASK> suite.addTest(MiscTests.suite()); //$JUnit-END$ return suite; }"
Inversion-Mutation
megadiff
"@Override public void visit(DexInstruction_BinaryOpWide instruction) { assert DexRegisterHelper.isPair(instruction.getRegSourceA1(), instruction.getRegSourceA2()); assert DexRegisterHelper.isPair(instruction.getRegSourceB1(), instruction.getRegSourceB2()); assert DexRegisterHelper.isPair(instruction.getRegTarget1(), instruction.getRegTarget2()); switch(instruction.getInsnOpcode()){ case AddDouble: case SubDouble: case MulDouble: case DivDouble: case RemDouble: useFreezedRegister(instruction.getRegSourceA1(), RopType.DoubleLo); useFreezedRegister(instruction.getRegSourceA2(), RopType.DoubleHi); useFreezedRegister(instruction.getRegSourceB1(), RopType.DoubleLo); useFreezedRegister(instruction.getRegSourceB2(), RopType.DoubleHi); defineFreezedRegister(instruction.getRegTarget1(), RopType.DoubleLo); defineFreezedRegister(instruction.getRegTarget2(), RopType.DoubleHi); break; case AddLong: case AndLong: case DivLong: case MulLong: case OrLong: case RemLong: case SubLong: case XorLong: useFreezedRegister(instruction.getRegSourceA1(), RopType.LongLo); useFreezedRegister(instruction.getRegSourceA2(), RopType.LongHi); useFreezedRegister(instruction.getRegSourceB1(), RopType.LongLo); useFreezedRegister(instruction.getRegSourceB2(), RopType.LongHi); defineFreezedRegister(instruction.getRegTarget1(), RopType.LongLo); defineFreezedRegister(instruction.getRegTarget2(), RopType.LongHi); break; case ShlLong: case ShrLong: case UshrLong: useFreezedRegister(instruction.getRegSourceA1(), RopType.LongLo); useFreezedRegister(instruction.getRegSourceA2(), RopType.LongHi); useFreezedRegister(instruction.getRegSourceB1(), RopType.Integer); defineFreezedRegister(instruction.getRegTarget1(), RopType.LongLo); defineFreezedRegister(instruction.getRegTarget2(), RopType.LongHi); break; default: throw new ValidationException("Unknown opcode for DexInstruction_BinaryOpWide"); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "visit"
"@Override public void visit(DexInstruction_BinaryOpWide instruction) { assert DexRegisterHelper.isPair(instruction.getRegSourceA1(), instruction.getRegSourceA2()); assert DexRegisterHelper.isPair(instruction.getRegSourceB1(), instruction.getRegSourceB2()); assert DexRegisterHelper.isPair(instruction.getRegTarget1(), instruction.getRegTarget2()); switch(instruction.getInsnOpcode()){ case AddDouble: case SubDouble: case MulDouble: case DivDouble: case RemDouble: useFreezedRegister(instruction.getRegSourceA1(), RopType.DoubleLo); useFreezedRegister(instruction.getRegSourceA2(), RopType.DoubleHi); useFreezedRegister(instruction.getRegSourceB1(), RopType.DoubleLo); useFreezedRegister(instruction.getRegSourceB2(), RopType.DoubleHi); defineFreezedRegister(instruction.getRegTarget1(), RopType.DoubleLo); defineFreezedRegister(instruction.getRegTarget2(), RopType.DoubleHi); break; case AddLong: case AndLong: case DivLong: case MulLong: case OrLong: case RemLong: case SubLong: <MASK>case UshrLong:</MASK> case XorLong: useFreezedRegister(instruction.getRegSourceA1(), RopType.LongLo); useFreezedRegister(instruction.getRegSourceA2(), RopType.LongHi); useFreezedRegister(instruction.getRegSourceB1(), RopType.LongLo); useFreezedRegister(instruction.getRegSourceB2(), RopType.LongHi); defineFreezedRegister(instruction.getRegTarget1(), RopType.LongLo); defineFreezedRegister(instruction.getRegTarget2(), RopType.LongHi); break; case ShlLong: case ShrLong: useFreezedRegister(instruction.getRegSourceA1(), RopType.LongLo); useFreezedRegister(instruction.getRegSourceA2(), RopType.LongHi); useFreezedRegister(instruction.getRegSourceB1(), RopType.Integer); defineFreezedRegister(instruction.getRegTarget1(), RopType.LongLo); defineFreezedRegister(instruction.getRegTarget2(), RopType.LongHi); break; default: throw new ValidationException("Unknown opcode for DexInstruction_BinaryOpWide"); } }"
Inversion-Mutation
megadiff
"public void cleanVolume(String volumeId) { try { updateVolumeGroup(); VolumeEntityWrapperManager volumeManager = new VolumeEntityWrapperManager(); LVMVolumeInfo lvmVolInfo = volumeManager.getVolumeInfo(volumeId); if(lvmVolInfo != null) { volumeManager.unexportVolume(lvmVolInfo); String lvName = lvmVolInfo.getLvName(); String absoluteLVName = lvmRootDirectory + PATH_SEPARATOR + volumeGroup + PATH_SEPARATOR + lvName; try { String returnValue = LVMWrapper.removeLogicalVolume(absoluteLVName); } catch(EucalyptusCloudException ex) { volumeManager.abort(); String error = "Unable to run command: " + ex.getMessage(); LOG.error(error); } volumeManager.remove(lvmVolInfo); } volumeManager.finish(); } catch (EucalyptusCloudException e) { LOG.debug("Failed to clean volume: " + volumeId, e); return; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "cleanVolume"
"public void cleanVolume(String volumeId) { try { updateVolumeGroup(); VolumeEntityWrapperManager volumeManager = new VolumeEntityWrapperManager(); LVMVolumeInfo lvmVolInfo = volumeManager.getVolumeInfo(volumeId); if(lvmVolInfo != null) { volumeManager.unexportVolume(lvmVolInfo); String lvName = lvmVolInfo.getLvName(); String absoluteLVName = lvmRootDirectory + PATH_SEPARATOR + volumeGroup + PATH_SEPARATOR + lvName; try { String returnValue = LVMWrapper.removeLogicalVolume(absoluteLVName); } catch(EucalyptusCloudException ex) { volumeManager.abort(); String error = "Unable to run command: " + ex.getMessage(); LOG.error(error); } volumeManager.remove(lvmVolInfo); <MASK>volumeManager.finish();</MASK> } } catch (EucalyptusCloudException e) { LOG.debug("Failed to clean volume: " + volumeId, e); return; } }"
Inversion-Mutation
megadiff
"public void deleteData() throws SQLException, IOException { update("delete from budget_line_items"); update("delete from budget_file_info"); update("delete from role_rights where roleId not in(1)"); update("delete from role_assignments where userId not in (1)"); update("delete from fulfillment_role_assignments"); update("delete from roles where name not in ('Admin')"); update("delete from facility_approved_products"); update("delete from program_product_price_history"); update("delete from pod_line_items"); update("delete from pod"); update("delete from orders"); update("DELETE FROM requisition_status_changes"); update("delete from user_password_reset_tokens"); update("delete from comments"); update("delete from facility_visits"); update("delete from epi_use_line_items"); update("delete from epi_use"); update("delete from epi_inventory_line_items"); update("delete from epi_inventory"); update("delete from refrigerator_problems"); update("delete from refrigerator_readings"); update("delete from distribution_refrigerators"); update("delete from distributions"); update("delete from users where userName not like('Admin%')"); update("DELETE FROM requisition_line_item_losses_adjustments"); update("DELETE FROM requisition_line_items"); update("DELETE FROM regimen_line_items"); update("DELETE FROM requisitions"); update("delete from program_product_isa"); update("delete from facility_approved_products"); update("delete from facility_program_products"); update("delete from program_products"); update("delete from products"); update("delete from product_categories"); update("delete from product_groups"); update("delete from supply_lines"); update("delete from programs_supported"); update("delete from requisition_group_members"); update("delete from program_rnr_columns"); update("delete from requisition_group_program_schedules"); update("delete from requisition_groups"); update("delete from requisition_group_members"); update("delete from delivery_zone_program_schedules"); update("delete from delivery_zone_warehouses"); update("delete from delivery_zone_members"); update("delete from role_assignments where deliveryZoneId in (select id from delivery_zones where code in('DZ1','DZ2'))"); update("delete from delivery_zones"); update("delete from supervisory_nodes"); update("delete from refrigerators"); update("delete from facility_ftp_details"); update("delete from facilities"); update("delete from geographic_zones where code not in ('Root','Arusha','Dodoma', 'Ngorongoro')"); update("delete from processing_periods"); update("delete from processing_schedules"); update("delete from atomfeed.event_records"); update("delete from regimens"); update("delete from program_regimen_columns"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "deleteData"
"public void deleteData() throws SQLException, IOException { update("delete from budget_line_items"); update("delete from budget_file_info"); update("delete from role_rights where roleId not in(1)"); update("delete from role_assignments where userId not in (1)"); update("delete from fulfillment_role_assignments"); update("delete from roles where name not in ('Admin')"); update("delete from facility_approved_products"); update("delete from program_product_price_history"); update("delete from pod_line_items"); update("delete from pod"); update("delete from orders"); update("DELETE FROM requisition_status_changes"); update("delete from user_password_reset_tokens"); update("delete from comments"); update("delete from facility_visits"); update("delete from epi_use_line_items"); update("delete from epi_use"); <MASK>update("delete from epi_inventory");</MASK> update("delete from epi_inventory_line_items"); update("delete from refrigerator_problems"); update("delete from refrigerator_readings"); update("delete from distribution_refrigerators"); update("delete from distributions"); update("delete from users where userName not like('Admin%')"); update("DELETE FROM requisition_line_item_losses_adjustments"); update("DELETE FROM requisition_line_items"); update("DELETE FROM regimen_line_items"); update("DELETE FROM requisitions"); update("delete from program_product_isa"); update("delete from facility_approved_products"); update("delete from facility_program_products"); update("delete from program_products"); update("delete from products"); update("delete from product_categories"); update("delete from product_groups"); update("delete from supply_lines"); update("delete from programs_supported"); update("delete from requisition_group_members"); update("delete from program_rnr_columns"); update("delete from requisition_group_program_schedules"); update("delete from requisition_groups"); update("delete from requisition_group_members"); update("delete from delivery_zone_program_schedules"); update("delete from delivery_zone_warehouses"); update("delete from delivery_zone_members"); update("delete from role_assignments where deliveryZoneId in (select id from delivery_zones where code in('DZ1','DZ2'))"); update("delete from delivery_zones"); update("delete from supervisory_nodes"); update("delete from refrigerators"); update("delete from facility_ftp_details"); update("delete from facilities"); update("delete from geographic_zones where code not in ('Root','Arusha','Dodoma', 'Ngorongoro')"); update("delete from processing_periods"); update("delete from processing_schedules"); update("delete from atomfeed.event_records"); update("delete from regimens"); update("delete from program_regimen_columns"); }"
Inversion-Mutation
megadiff
"private void startup() { // Stop the handler mTimer.removeCallbacks(mTask); // Set the condition to time up Global.GAME_STATE.timerCondition = TimerCondition.STARTING; // Reset the time Global.GAME_STATE.resetTime(); // Enable both buttons mLeftButton.setEnabled(true); mRightButton.setEnabled(true); // Update button's text mLeftButton.setText(Global.GAME_STATE.leftPlayerTime()); mRightButton.setText(Global.GAME_STATE.rightPlayerTime()); mPauseButton.setText( mParentActivity.getString(R.string.settingsMenuLabel)); mDelayLabel.setVisibility(View.INVISIBLE); // Set both layouts to be invisible mPauseLayout.setVisibility(View.INVISIBLE); mAds.setVisibility(View.INVISIBLE); // Display a message Toast.makeText(mParentActivity, mParentActivity.getString(R.string.toastMessage), Toast.LENGTH_LONG).show(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "startup"
"private void startup() { // Stop the handler mTimer.removeCallbacks(mTask); // Set the condition to time up Global.GAME_STATE.timerCondition = TimerCondition.STARTING; // Reset the time Global.GAME_STATE.resetTime(); // Enable both buttons mLeftButton.setEnabled(true); mRightButton.setEnabled(true); // Update button's text mLeftButton.setText(Global.GAME_STATE.leftPlayerTime()); mRightButton.setText(Global.GAME_STATE.rightPlayerTime()); mPauseButton.setText( mParentActivity.getString(R.string.settingsMenuLabel)); mDelayLabel.setVisibility(View.INVISIBLE); // Set both layouts to be invisible <MASK>mAds.setVisibility(View.INVISIBLE);</MASK> mPauseLayout.setVisibility(View.INVISIBLE); // Display a message Toast.makeText(mParentActivity, mParentActivity.getString(R.string.toastMessage), Toast.LENGTH_LONG).show(); }"
Inversion-Mutation
megadiff
"private void enterOverworldMode() { startWorldThread(); ui.switchToOverworldScreen(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "enterOverworldMode"
"private void enterOverworldMode() { <MASK>ui.switchToOverworldScreen();</MASK> startWorldThread(); }"
Inversion-Mutation
megadiff
"private boolean commandRes(String[] args, boolean resadmin, Command command, CommandSender sender){ if (args.length > 0 && args[args.length - 1].equalsIgnoreCase("?") || args.length > 1 && args[args.length - 2].equals("?")) { return commandHelp(args, resadmin, sender); } int page = 1; try{ if(args.length>0) { page = Integer.parseInt(args[args.length-1]); } }catch(Exception ex){} Player player = null; PermissionGroup group = null; String pname = null; if (sender instanceof Player) { player = (Player) sender; group = Residence.getPermissionManager().getGroup(player); pname = player.getName(); } else { resadmin = true; } if (cmanager.allowAdminsOnly()) { if (!resadmin) { player.sendMessage(ChatColor.RED+language.getPhrase("AdminOnly")); return true; } } if(args.length==0) { return false; } if (args.length == 0) { args = new String[1]; args[0] = "?"; } String cmd = args[0].toLowerCase(); if(cmd.equals("remove")||cmd.equals("delete")) { return commandResRemove(args, resadmin, sender, page); } if(cmd.equals("confirm")) { return commandResConfirm(args, resadmin, sender, page); } if (cmd.equals("version")) { sender.sendMessage(ChatColor.GRAY+"------------------------------------"); sender.sendMessage(ChatColor.RED+"This server running "+ChatColor.GOLD+"Residence"+ChatColor.RED+" version: "+ChatColor.BLUE + this.getDescription().getVersion()); sender.sendMessage(ChatColor.GREEN+"Created by: "+ChatColor.YELLOW+"bekvon"); sender.sendMessage(ChatColor.DARK_AQUA+"For a command list, and help, see the wiki:"); sender.sendMessage(ChatColor.GREEN+"http://residencebukkitmod.wikispaces.com/"); sender.sendMessage(ChatColor.AQUA+"Visit the BukkitDev page at:"); sender.sendMessage(ChatColor.BLUE+"http://dev.bukkit.org/server-mods/Residence"); sender.sendMessage(ChatColor.GRAY+"------------------------------------"); return true; } if (cmd.equals("setowner") && args.length==3) { if(!resadmin) { sender.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); return true; } ClaimedResidence area = rmanager.getByName(args[1]); if (area != null) { area.getPermissions().setOwner(args[2], true); if(area.getParent()==null){ sender.sendMessage(ChatColor.GREEN+language.getPhrase("ResidenceOwnerChange",ChatColor.YELLOW+" " + args[1] + " "+ChatColor.GREEN+"."+ChatColor.YELLOW+args[2]+ChatColor.GREEN)); } else { sender.sendMessage(ChatColor.GREEN+language.getPhrase("SubzoneOwnerChange",ChatColor.YELLOW+" " + args[1].split("\\.")[args[1].split("\\.").length - 1] + " "+ChatColor.GREEN+"."+ChatColor.YELLOW+args[2]+ChatColor.GREEN)); } } else { sender.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); } return true; } if(player==null){ return true; } if(command.getName().equals("resadmin")) { if(args.length == 1 && args[0].equals("on")) { resadminToggle.add(player.getName()); player.sendMessage(ChatColor.YELLOW + language.getPhrase("AdminToggle",language.getPhrase("TurnOn"))); return true; } else if(args.length == 1 && args[0].equals("off")) { resadminToggle.remove(player.getName()); player.sendMessage(ChatColor.YELLOW + language.getPhrase("AdminToggle",language.getPhrase("TurnOff"))); return true; } } if(!resadmin && resadminToggle.contains(player.getName())) { resadmin = gmanager.isResidenceAdmin(player); if(!resadmin) { resadminToggle.remove(player.getName()); } } if(cmd.equals("select")) { return commandResSelect(args, resadmin, player, page); } if(cmd.equals("create")) { return commandResCreate(args, resadmin, player, page); } if(cmd.equals("subzone")||cmd.equals("sz")) { return commandResSubzone(args, resadmin, player, page); } if(cmd.equals("gui")) { return commandResGui(args, resadmin, player, page); } if(cmd.equals("sublist")) { return commandResSublist(args, resadmin, player, page); } if(cmd.equals("removeall")){ if(args.length!=2) { return false; } if(resadmin || args[1].endsWith(pname)) { rmanager.removeAllByOwner(args[1]); player.sendMessage(ChatColor.GREEN+language.getPhrase("RemovePlayersResidences",ChatColor.YELLOW+args[1]+ChatColor.GREEN)); } else { player.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); } return true; } if(cmd.equals("compass")) { return commandResCompass(args, resadmin, player, page); } if(cmd.equals("area")) { return commandResArea(args, resadmin, player, page); } if(cmd.equals("lists")) { return commandResList(args, resadmin, player, page); } if(cmd.equals("default")){ if (args.length == 2) { ClaimedResidence res = rmanager.getByName(args[1]); res.getPermissions().applyDefaultFlags(player, resadmin); return true; } return false; } if(cmd.equals("limits")){ if (args.length == 1) { gmanager.getGroup(player).printLimits(player); return true; } return false; } if(cmd.equals("info")){ if (args.length == 1) { String area = rmanager.getNameByLoc(player.getLocation()); if (area != null) { rmanager.printAreaInfo(area, player); } else { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); } return true; } else if (args.length == 2) { rmanager.printAreaInfo(args[1], player); return true; } return false; } if(cmd.equals("check")){ if(args.length == 3 || args.length == 4) { if(args.length == 4) { pname = args[3]; } ClaimedResidence res = rmanager.getByName(args[1]); if(res==null) { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); return true; } if(!res.getPermissions().hasApplicableFlag(pname, args[2])) { player.sendMessage(language.getPhrase("FlagCheckFalse",ChatColor.YELLOW + args[2] + ChatColor.RED+"."+ChatColor.YELLOW + pname +ChatColor.RED+"."+ChatColor.YELLOW+args[1]+ChatColor.RED)); } else { player.sendMessage(language.getPhrase("FlagCheckTrue",ChatColor.GREEN+args[2]+ChatColor.YELLOW+"."+ChatColor.GREEN+pname+ChatColor.YELLOW+"."+ChatColor.YELLOW+args[1]+ChatColor.RED+"."+(res.getPermissions().playerHas(pname, res.getPermissions().getWorld(), args[2], false) ? ChatColor.GREEN+"TRUE" : ChatColor.RED+"FALSE"))); } return true; } return false; } if(cmd.equals("current")){ if(args.length!=1) { return false; } String res = rmanager.getNameByLoc(player.getLocation()); if(res==null) { player.sendMessage(ChatColor.RED+language.getPhrase("NotInResidence")); } else { player.sendMessage(ChatColor.GREEN+language.getPhrase("InResidence",ChatColor.YELLOW + res + ChatColor.GREEN)); } return true; } if(cmd.equals("set")) { return commandResSet(args, resadmin, player, page); } if(cmd.equals("pset")) { return commandResPset(args, resadmin, player, page); } if(cmd.equals("gset")) { return commandResGset(args, resadmin, player, page); } if(cmd.equals("lset")) { return commandResLset(args, resadmin, player, page); } if (cmd.equals("list")) { if(args.length == 1) { rmanager.listResidences(player); return true; } else if (args.length == 2) { try { Integer.parseInt(args[1]); rmanager.listResidences(player, page); } catch (Exception ex) { rmanager.listResidences(player, args[1]); } return true; } else if(args.length == 3) { rmanager.listResidences(player, args[1], page); return true; } return false; } if (cmd.equals("listhidden")) { if(!resadmin) { player.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); return true; } if(args.length == 1) { rmanager.listResidences(player,1,true); return true; } else if (args.length == 2) { try { Integer.parseInt(args[1]); rmanager.listResidences(player, page, true); } catch (Exception ex) { rmanager.listResidences(player, args[1],1, true); } return true; } else if(args.length == 3) { rmanager.listResidences(player, args[1], page, true); return true; } return false; } if(cmd.equals("rename")) { if(args.length==3) { rmanager.renameResidence(player, args[1], args[2], resadmin); return true; } return false; } if(cmd.equals("renamearea")) { if(args.length==4) { ClaimedResidence res = rmanager.getByName(args[1]); if(res==null) { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); return true; } res.renameArea(player, args[2], args[3], resadmin); return true; } return false; } if (cmd.equals("unstuck")) { if (args.length != 1) { return false; } group = gmanager.getGroup(player); if(!group.hasUnstuckAccess()) { player.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); return true; } ClaimedResidence res = rmanager.getByLoc(player.getLocation()); if (res == null) { player.sendMessage(ChatColor.RED+language.getPhrase("NotInResidence")); } else { player.sendMessage(ChatColor.YELLOW+language.getPhrase("Moved")+"..."); player.teleport(res.getOutsideFreeLoc(player.getLocation())); } return true; } if (cmd.equals("mirror")) { if (args.length != 3) { return false; } rmanager.mirrorPerms(player, args[2], args[1], resadmin); return true; } if (cmd.equals("listall")) { if (args.length == 1) { rmanager.listAllResidences(player, 1); } else if (args.length == 2) { try { rmanager.listAllResidences(player, page); } catch (Exception ex) { } } else { return false; } return true; } if(cmd.equals("listallhidden")) { if(!resadmin) { player.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); return true; } if (args.length == 1) { rmanager.listAllResidences(player, 1, true); } else if (args.length == 2) { try { rmanager.listAllResidences(player, page, true); } catch (Exception ex) { } } else { return false; } return true; } if(cmd.equals("material")) { if(args.length!=2) { return false; } try { player.sendMessage(ChatColor.GREEN+language.getPhrase("MaterialGet",ChatColor.GOLD + args[1] + ChatColor.GREEN+"."+ChatColor.RED + Material.getMaterial(Integer.parseInt(args[1])).name()+ChatColor.GREEN)); } catch (Exception ex) { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidMaterial")); } return true; } if (cmd.equals("tpset")) { ClaimedResidence res = rmanager.getByLoc(player.getLocation()); if (res != null) { res.setTpLoc(player, resadmin); } else { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); } return true; } if (cmd.equals("tp")) { if (args.length != 2) { return false; } ClaimedResidence res = rmanager.getByName(args[1]); if (res == null) { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); return true; } res.tpToResidence(player, player, resadmin); return true; } if (cmd.equals("lease")) { return commandResLease(args, resadmin, player, page); } if(cmd.equals("bank")) { return commandResBank(args, resadmin, player, page); } if (cmd.equals("market")) { return commandResMarket(args, resadmin, player, page); } if (cmd.equals("message")) { return commandResMessage(args, resadmin, player, page); } if(cmd.equals("give") && args.length==3) { rmanager.giveResidence(player, args[2], args[1], resadmin); return true; } if(cmd.equals("server")) { if(!resadmin) { player.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); return true; } if(args.length==2) { ClaimedResidence res = rmanager.getByName(args[1]); if(res == null) { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); return true; } res.getPermissions().setOwner("Server Land", false); player.sendMessage(ChatColor.GREEN+language.getPhrase("ResidenceOwnerChange",ChatColor.YELLOW + args[1] + ChatColor.GREEN+"."+ChatColor.YELLOW+"Server Land"+ChatColor.GREEN)); return true; } else { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); return true; } } if(cmd.equals("clearflags")) { if(!resadmin) { player.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); return true; } ClaimedResidence area = rmanager.getByName(args[1]); if (area != null) { area.getPermissions().clearFlags(); player.sendMessage(ChatColor.GREEN+language.getPhrase("FlagsCleared")); } else { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); } return true; } if(cmd.equals("tool")) { player.sendMessage(ChatColor.YELLOW+language.getPhrase("SelectionTool")+":"+ChatColor.GREEN + Material.getMaterial(cmanager.getSelectionTooldID())); player.sendMessage(ChatColor.YELLOW+language.getPhrase("InfoTool")+": "+ChatColor.GREEN + Material.getMaterial(cmanager.getInfoToolID())); return true; } if(cmd.equals("donotrunmeonliveserver")) { if(sender instanceof ConsoleCommandSender) { System.out.println("Started..."); PerformanceTester.runHIGHLYDESTRUCTIVEToLiveServerPerformanceTest(); return true; } } return false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "commandRes"
"private boolean commandRes(String[] args, boolean resadmin, Command command, CommandSender sender){ if (args.length > 0 && args[args.length - 1].equalsIgnoreCase("?") || args.length > 1 && args[args.length - 2].equals("?")) { return commandHelp(args, resadmin, sender); } int page = 1; try{ if(args.length>0) { page = Integer.parseInt(args[args.length-1]); } }catch(Exception ex){} Player player = null; PermissionGroup group = null; String pname = null; if (sender instanceof Player) { player = (Player) sender; group = Residence.getPermissionManager().getGroup(player); pname = player.getName(); } else { resadmin = true; } if (cmanager.allowAdminsOnly()) { if (!resadmin) { player.sendMessage(ChatColor.RED+language.getPhrase("AdminOnly")); return true; } } if(args.length==0) { return false; } if (args.length == 0) { args = new String[1]; args[0] = "?"; } String cmd = args[0].toLowerCase(); if(cmd.equals("remove")||cmd.equals("delete")) { return commandResRemove(args, resadmin, sender, page); } if(cmd.equals("confirm")) { return commandResConfirm(args, resadmin, sender, page); } if (cmd.equals("version")) { sender.sendMessage(ChatColor.GRAY+"------------------------------------"); sender.sendMessage(ChatColor.RED+"This server running "+ChatColor.GOLD+"Residence"+ChatColor.RED+" version: "+ChatColor.BLUE + this.getDescription().getVersion()); sender.sendMessage(ChatColor.GREEN+"Created by: "+ChatColor.YELLOW+"bekvon"); sender.sendMessage(ChatColor.DARK_AQUA+"For a command list, and help, see the wiki:"); sender.sendMessage(ChatColor.GREEN+"http://residencebukkitmod.wikispaces.com/"); sender.sendMessage(ChatColor.AQUA+"Visit the BukkitDev page at:"); sender.sendMessage(ChatColor.BLUE+"http://dev.bukkit.org/server-mods/Residence"); sender.sendMessage(ChatColor.GRAY+"------------------------------------"); return true; } if (cmd.equals("setowner") && args.length==3) { if(!resadmin) { sender.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); return true; } ClaimedResidence area = rmanager.getByName(args[1]); if (area != null) { area.getPermissions().setOwner(args[2], true); if(area.getParent()==null){ sender.sendMessage(ChatColor.GREEN+language.getPhrase("ResidenceOwnerChange",ChatColor.YELLOW+" " + args[1] + " "+ChatColor.GREEN+"."+ChatColor.YELLOW+args[2]+ChatColor.GREEN)); } else { sender.sendMessage(ChatColor.GREEN+language.getPhrase("SubzoneOwnerChange",ChatColor.YELLOW+" " + args[1].split("\\.")[args[1].split("\\.").length - 1] + " "+ChatColor.GREEN+"."+ChatColor.YELLOW+args[2]+ChatColor.GREEN)); } } else { sender.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); } return true; } if(player==null){ return true; } if(command.getName().equals("resadmin")) { if(args.length == 1 && args[0].equals("on")) { resadminToggle.add(player.getName()); player.sendMessage(ChatColor.YELLOW + language.getPhrase("AdminToggle",language.getPhrase("TurnOn"))); return true; } else if(args.length == 1 && args[0].equals("off")) { resadminToggle.remove(player.getName()); player.sendMessage(ChatColor.YELLOW + language.getPhrase("AdminToggle",language.getPhrase("TurnOff"))); return true; } } if(!resadmin && resadminToggle.contains(player.getName())) { resadmin = gmanager.isResidenceAdmin(player); if(!resadmin) { resadminToggle.remove(player.getName()); } } if(cmd.equals("select")) { return commandResSelect(args, resadmin, player, page); } if(cmd.equals("create")) { return commandResCreate(args, resadmin, player, page); } if(cmd.equals("subzone")||cmd.equals("sz")) { return commandResSubzone(args, resadmin, player, page); } if(cmd.equals("gui")) { return commandResGui(args, resadmin, player, page); } if(cmd.equals("sublist")) { return commandResSublist(args, resadmin, player, page); } if(cmd.equals("removeall")){ if(args.length!=2) { return false; } if(resadmin || args[1].endsWith(pname)) { rmanager.removeAllByOwner(args[1]); player.sendMessage(ChatColor.GREEN+language.getPhrase("RemovePlayersResidences",ChatColor.YELLOW+args[1]+ChatColor.GREEN)); } else { player.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); } return true; } if(cmd.equals("compass")) { return commandResCompass(args, resadmin, player, page); } if(cmd.equals("area")) { return commandResArea(args, resadmin, player, page); } if(cmd.equals("lists")) { return commandResList(args, resadmin, player, page); } if(cmd.equals("default")){ if (args.length == 2) { ClaimedResidence res = rmanager.getByName(args[1]); res.getPermissions().applyDefaultFlags(player, resadmin); return true; } return false; } if(cmd.equals("limits")){ if (args.length == 1) { gmanager.getGroup(player).printLimits(player); return true; } return false; } if(cmd.equals("info")){ if (args.length == 1) { String area = rmanager.getNameByLoc(player.getLocation()); if (area != null) { rmanager.printAreaInfo(area, player); } else { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); } return true; } else if (args.length == 2) { rmanager.printAreaInfo(args[1], player); return true; } return false; } if(cmd.equals("check")){ if(args.length == 3 || args.length == 4) { if(args.length == 4) { pname = args[3]; } ClaimedResidence res = rmanager.getByName(args[1]); if(res==null) { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); return true; } if(!res.getPermissions().hasApplicableFlag(pname, args[2])) { player.sendMessage(language.getPhrase("FlagCheckFalse",ChatColor.YELLOW + args[2] + ChatColor.RED+"."+ChatColor.YELLOW + pname +ChatColor.RED+"."+ChatColor.YELLOW+args[1]+ChatColor.RED)); } else { player.sendMessage(language.getPhrase("FlagCheckTrue",ChatColor.GREEN+args[2]+ChatColor.YELLOW+"."+ChatColor.GREEN+pname+ChatColor.YELLOW+"."+ChatColor.YELLOW+args[1]+ChatColor.RED+"."+(res.getPermissions().playerHas(pname, res.getPermissions().getWorld(), args[2], false) ? ChatColor.GREEN+"TRUE" : ChatColor.RED+"FALSE"))); } return true; } return false; } if(cmd.equals("current")){ if(args.length!=1) { return false; } String res = rmanager.getNameByLoc(player.getLocation()); if(res==null) { player.sendMessage(ChatColor.RED+language.getPhrase("NotInResidence")); } else { player.sendMessage(ChatColor.GREEN+language.getPhrase("InResidence",ChatColor.YELLOW + res + ChatColor.GREEN)); } return true; } if(cmd.equals("set")) { return commandResSet(args, resadmin, player, page); } if(cmd.equals("pset")) { return commandResPset(args, resadmin, player, page); } if(cmd.equals("gset")) { return commandResGset(args, resadmin, player, page); } if(cmd.equals("lset")) { return commandResLset(args, resadmin, player, page); } if (cmd.equals("list")) { if(args.length == 1) { rmanager.listResidences(player); return true; } else if (args.length == 2) { try { Integer.parseInt(args[1]); rmanager.listResidences(player, page); } catch (Exception ex) { rmanager.listResidences(player, args[1]); } return true; } else if(args.length == 3) { rmanager.listResidences(player, args[1], page); return true; } return false; } if (cmd.equals("listhidden")) { if(!resadmin) { player.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); return true; } if(args.length == 1) { rmanager.listResidences(player,1,true); return true; } else if (args.length == 2) { try { Integer.parseInt(args[1]); rmanager.listResidences(player, page, true); } catch (Exception ex) { rmanager.listResidences(player, args[1],1, true); } return true; } else if(args.length == 3) { rmanager.listResidences(player, args[1], page, true); return true; } return false; } if(cmd.equals("rename")) { if(args.length==3) { rmanager.renameResidence(player, args[1], args[2], resadmin); return true; } return false; } if(cmd.equals("renamearea")) { if(args.length==4) { ClaimedResidence res = rmanager.getByName(args[1]); if(res==null) { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); return true; } res.renameArea(player, args[2], args[3], resadmin); return true; } return false; } if (cmd.equals("unstuck")) { if (args.length != 1) { return false; } group = gmanager.getGroup(player); if(!group.hasUnstuckAccess()) { player.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); return true; } ClaimedResidence res = rmanager.getByLoc(player.getLocation()); if (res == null) { player.sendMessage(ChatColor.RED+language.getPhrase("NotInResidence")); } else { player.sendMessage(ChatColor.YELLOW+language.getPhrase("Moved")+"..."); player.teleport(res.getOutsideFreeLoc(player.getLocation())); } return true; } if (cmd.equals("mirror")) { if (args.length != 3) { return false; } rmanager.mirrorPerms(player, args[2], args[1], resadmin); return true; } if (cmd.equals("listall")) { if (args.length == 1) { rmanager.listAllResidences(player, 1); } else if (args.length == 2) { try { rmanager.listAllResidences(player, page); } catch (Exception ex) { } } else { return false; } return true; } if(cmd.equals("listallhidden")) { if(!resadmin) { player.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); return true; } if (args.length == 1) { rmanager.listAllResidences(player, 1, true); } else if (args.length == 2) { try { rmanager.listAllResidences(player, page, true); } catch (Exception ex) { } } else { return false; } return true; } if(cmd.equals("material")) { if(args.length!=2) { return false; } try { player.sendMessage(ChatColor.GREEN+language.getPhrase("MaterialGet",ChatColor.GOLD + args[1] + ChatColor.GREEN+"."+ChatColor.RED + Material.getMaterial(Integer.parseInt(args[1])).name()+ChatColor.GREEN)); } catch (Exception ex) { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidMaterial")); } return true; } if (cmd.equals("tpset")) { ClaimedResidence res = rmanager.getByLoc(player.getLocation()); if (res != null) { res.setTpLoc(player, resadmin); } else { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); } return true; } if (cmd.equals("tp")) { if (args.length != 2) { return false; } ClaimedResidence res = rmanager.getByName(args[1]); if (res == null) { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); return true; } res.tpToResidence(player, player, resadmin); return true; } if (cmd.equals("lease")) { return commandResLease(args, resadmin, player, page); } if(cmd.equals("bank")) { return commandResBank(args, resadmin, player, page); } if (cmd.equals("market")) { return commandResMarket(args, resadmin, player, page); } if (cmd.equals("message")) { return commandResMessage(args, resadmin, player, page); } if(cmd.equals("give") && args.length==3) { rmanager.giveResidence(player, args[2], args[1], resadmin); return true; } if(cmd.equals("server")) { if(!resadmin) { player.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); return true; } if(args.length==2) { ClaimedResidence res = rmanager.getByName(args[1]); if(res == null) { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); return true; } res.getPermissions().setOwner("Server Land", false); player.sendMessage(ChatColor.GREEN+language.getPhrase("ResidenceOwnerChange",ChatColor.YELLOW + args[1] + ChatColor.GREEN+"."+ChatColor.YELLOW+"Server Land"+ChatColor.GREEN)); return true; } else { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); return true; } } if(cmd.equals("clearflags")) { if(!resadmin) { player.sendMessage(ChatColor.RED+language.getPhrase("NoPermission")); return true; } ClaimedResidence area = rmanager.getByName(args[1]); if (area != null) { area.getPermissions().clearFlags(); player.sendMessage(ChatColor.GREEN+language.getPhrase("FlagsCleared")); } else { player.sendMessage(ChatColor.RED+language.getPhrase("InvalidResidence")); } return true; } if(cmd.equals("tool")) { player.sendMessage(ChatColor.YELLOW+language.getPhrase("SelectionTool")+":"+ChatColor.GREEN + Material.getMaterial(cmanager.getSelectionTooldID())); player.sendMessage(ChatColor.YELLOW+language.getPhrase("InfoTool")+": "+ChatColor.GREEN + Material.getMaterial(cmanager.getInfoToolID())); return true; } if(cmd.equals("donotrunmeonliveserver")) { if(sender instanceof ConsoleCommandSender) { <MASK>PerformanceTester.runHIGHLYDESTRUCTIVEToLiveServerPerformanceTest();</MASK> System.out.println("Started..."); return true; } } return false; }"
Inversion-Mutation
megadiff
"@Override protected void onCreate(Bundle savedInstanceState) { setTheme(UserPreferences.getTheme()); super.onCreate(savedInstanceState); getSupportActionBar().setDisplayHomeAsUpEnabled(true); setContentView(R.layout.gpodnetauth_activity); service = new GpodnetService(); viewFlipper = (ViewFlipper) findViewById(R.id.viewflipper); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); views = new View[]{ inflater.inflate(R.layout.gpodnetauth_credentials, null), inflater.inflate(R.layout.gpodnetauth_device, null), inflater.inflate(R.layout.gpodnetauth_finish, null) }; for (View view : views) { viewFlipper.addView(view); } advance(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate"
"@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().setDisplayHomeAsUpEnabled(true); <MASK>setTheme(UserPreferences.getTheme());</MASK> setContentView(R.layout.gpodnetauth_activity); service = new GpodnetService(); viewFlipper = (ViewFlipper) findViewById(R.id.viewflipper); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); views = new View[]{ inflater.inflate(R.layout.gpodnetauth_credentials, null), inflater.inflate(R.layout.gpodnetauth_device, null), inflater.inflate(R.layout.gpodnetauth_finish, null) }; for (View view : views) { viewFlipper.addView(view); } advance(); }"
Inversion-Mutation
megadiff
"public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest)req; final HttpServletResponse resp = (HttpServletResponse)response; long startTime = System.currentTimeMillis(); XsltGlobals glob = getXsltGlobals(hreq); glob.reason = null; if (debug) { getLogger().debug("XSLTFilter: Accessing filter for " + HttpServletUtils.getReqLine(hreq) + " " + hreq.getMethod() + " response class: " + resp.getClass().getName()); getLogger().debug("XSLTFilter: response: " + resp); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); WrappedResponse wrappedResp = new WrappedResponse(resp, hreq, getLogger(), debug); filterChain.doFilter(req, wrappedResp); /* We don't get a session till we've been through to the servlet. */ HttpSession sess = hreq.getSession(false); String sessId; if (sess == null) { sessId = "NONE"; } else { sessId = sess.getId(); } logTime("PRETRANSFORM", sessId, System.currentTimeMillis() - startTime); /** Ensure we're all set up to handle content */ doPreFilter(hreq); byte[] bytes = wrappedResp.toByteArray(); if (bytes == null || (bytes.length == 0)) { if (debug) { getLogger().debug("No content"); } // xformNeeded[0] = false; wrappedResp.setTransformNeeded(false); glob.reason = "No content"; } try { if ((!glob.dontFilter) && (wrappedResp.getTransformNeeded())) { if (debug) { getLogger().debug("+*+*+*+*+*+*+*+*+*+*+* about to transform: len=" + bytes.length); } //getLogger().debug(new String(bytes)); TransformerException te = null; Transformer xmlt = null; try { xmlt = getXmlTransformer(glob.url); } catch (TransformerException te1) { te = te1; } if (xmlt == null) { outputErrorMessage("No xml transformer", "Unable to obtain an XML transformer probably " + "due to a previous error. Server logs may " + "help determine the cause.", baos); glob.contentType = "text/html"; } else if (te != null) { /** We had an exception getting the transformer. Output error information instead of the transformed output */ outputInitErrorInfo(te, baos); glob.contentType = "text/html"; } else { /** We seem to be getting invalid bytes occassionally for (int i = 0; i < bytes.length; i++) { if ((bytes[i] & 0x0ff) > 128) { getLogger().warn("Found byte > 128 at " + i + " bytes = " + (bytes[i] & 0x0ff)); bytes[i] = (int)('?'); } } The above commented out. It breaks Unicode characters */ /** Managed to get a transformer. Do the thing. */ try { /* The choice is a pool of transformers per thread or to synchronize during the transform. Transforms appear to be fast, for a dynamic site they take a small proportiuon of the response time. Try synch for now. */ synchronized (xmlt) { xmlt.transform( new StreamSource( new InputStreamReader(new ByteArrayInputStream(bytes), "UTF-8")), new StreamResult(baos)); } } catch (TransformerException e) { outputTransformErrorInfo(e, baos); glob.contentType = "text/html"; } if (debug) { Properties pr = xmlt.getOutputProperties(); if (pr != null) { Enumeration en = pr.propertyNames(); while (en.hasMoreElements()) { String key = (String)en.nextElement(); getLogger().debug("--------- xslt-output property " + key + "=" + pr.getProperty(key)); } } } } if (glob.contentType != null) { /** Set explicitly by caller. */ resp.setContentType(glob.contentType); } else { /** The encoding and media type should be available from the * Transformer. Letting the stylesheet dictate the media-type * is the right thing to do as only the stylesheet knows what * it's producing. */ Properties pr = xmlt.getOutputProperties(); if (pr != null) { String encoding = pr.getProperty("encoding"); String mtype = pr.getProperty("media-type"); if (mtype != null) { if (debug) { getLogger().debug("Stylesheet set media-type to " + mtype); } if (encoding != null) { resp.setContentType(mtype + ";charset=" + encoding); } else { resp.setContentType(mtype); } } } } byte[] xformBytes = baos.toByteArray(); resp.setContentLength(xformBytes.length); resp.getOutputStream().write(xformBytes); if (debug) { getLogger().debug("XML -> HTML conversion completed"); } } else { if (debug) { if (glob.dontFilter) { glob.reason = "dontFilter"; } if (glob.reason == null) { glob.reason = "Unknown"; } getLogger().debug("+*+*+*+*+*+*+*+*+*+*+* transform suppressed" + " reason = " + glob.reason); } resp.setContentLength(bytes.length); resp.getOutputStream().write(bytes); if (glob.contentType != null) { /** Set explicitly by caller. */ resp.setContentType(glob.contentType); } } } catch (Throwable t) { /** We're seeing tomcat specific exceptions here when the client aborts. Try to detect these without making this code tomcat specific. */ if ("org.apache.catalina.connector.ClientAbortException".equals(t.getClass().getName())) { getLogger().warn("ClientAbortException: dropping response"); } else { getLogger().error("Unable to transform document", t); throw new ServletException("Unable to transform document", t); } } finally { if (wrappedResp != null) { wrappedResp.close(); } if (baos != null) { try { baos.close(); } catch (Exception bae) {} } bytes = null; } logTime("POSTTRANSFORM", sessId, System.currentTimeMillis() - startTime); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doFilter"
"public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest)req; final HttpServletResponse resp = (HttpServletResponse)response; long startTime = System.currentTimeMillis(); XsltGlobals glob = getXsltGlobals(hreq); glob.reason = null; if (debug) { getLogger().debug("XSLTFilter: Accessing filter for " + HttpServletUtils.getReqLine(hreq) + " " + hreq.getMethod() + " response class: " + resp.getClass().getName()); getLogger().debug("XSLTFilter: response: " + resp); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); WrappedResponse wrappedResp = new WrappedResponse(resp, hreq, getLogger(), debug); filterChain.doFilter(req, wrappedResp); /* We don't get a session till we've been through to the servlet. */ HttpSession sess = hreq.getSession(false); String sessId; if (sess == null) { sessId = "NONE"; } else { sessId = sess.getId(); } logTime("PRETRANSFORM", sessId, System.currentTimeMillis() - startTime); /** Ensure we're all set up to handle content */ doPreFilter(hreq); byte[] bytes = wrappedResp.toByteArray(); if (bytes == null || (bytes.length == 0)) { if (debug) { getLogger().debug("No content"); } // xformNeeded[0] = false; wrappedResp.setTransformNeeded(false); glob.reason = "No content"; } try { if ((!glob.dontFilter) && (wrappedResp.getTransformNeeded())) { if (debug) { getLogger().debug("+*+*+*+*+*+*+*+*+*+*+* about to transform: len=" + bytes.length); } //getLogger().debug(new String(bytes)); TransformerException te = null; Transformer xmlt = null; try { xmlt = getXmlTransformer(glob.url); } catch (TransformerException te1) { te = te1; } if (xmlt == null) { outputErrorMessage("No xml transformer", "Unable to obtain an XML transformer probably " + "due to a previous error. Server logs may " + "help determine the cause.", baos); glob.contentType = "text/html"; } else if (te != null) { /** We had an exception getting the transformer. Output error information instead of the transformed output */ outputInitErrorInfo(te, baos); glob.contentType = "text/html"; } else { /** We seem to be getting invalid bytes occassionally for (int i = 0; i < bytes.length; i++) { if ((bytes[i] & 0x0ff) > 128) { getLogger().warn("Found byte > 128 at " + i + " bytes = " + (bytes[i] & 0x0ff)); bytes[i] = (int)('?'); } } The above commented out. It breaks Unicode characters */ /** Managed to get a transformer. Do the thing. */ try { /* The choice is a pool of transformers per thread or to synchronize during the transform. Transforms appear to be fast, for a dynamic site they take a small proportiuon of the response time. Try synch for now. */ synchronized (xmlt) { xmlt.transform( new StreamSource( new InputStreamReader(new ByteArrayInputStream(bytes), "UTF-8")), new StreamResult(baos)); } } catch (TransformerException e) { outputTransformErrorInfo(e, baos); glob.contentType = "text/html"; } if (debug) { Properties pr = xmlt.getOutputProperties(); if (pr != null) { Enumeration en = pr.propertyNames(); while (en.hasMoreElements()) { String key = (String)en.nextElement(); getLogger().debug("--------- xslt-output property " + key + "=" + pr.getProperty(key)); } } } } if (glob.contentType != null) { /** Set explicitly by caller. */ resp.setContentType(glob.contentType); } else { /** The encoding and media type should be available from the * Transformer. Letting the stylesheet dictate the media-type * is the right thing to do as only the stylesheet knows what * it's producing. */ Properties pr = xmlt.getOutputProperties(); if (pr != null) { String encoding = pr.getProperty("encoding"); String mtype = pr.getProperty("media-type"); if (mtype != null) { if (debug) { getLogger().debug("Stylesheet set media-type to " + mtype); } if (encoding != null) { resp.setContentType(mtype + ";charset=" + encoding); } else { resp.setContentType(mtype); } } } } byte[] xformBytes = baos.toByteArray(); resp.setContentLength(xformBytes.length); resp.getOutputStream().write(xformBytes); if (debug) { getLogger().debug("XML -> HTML conversion completed"); } } else { if (debug) { if (glob.dontFilter) { glob.reason = "dontFilter"; } if (glob.reason == null) { glob.reason = "Unknown"; } getLogger().debug("+*+*+*+*+*+*+*+*+*+*+* transform suppressed" + " reason = " + glob.reason); } resp.setContentLength(bytes.length); resp.getOutputStream().write(bytes); if (glob.contentType != null) { /** Set explicitly by caller. */ resp.setContentType(glob.contentType); } } } catch (Throwable t) { /** We're seeing tomcat specific exceptions here when the client aborts. Try to detect these without making this code tomcat specific. */ <MASK>getLogger().error("Unable to transform document", t);</MASK> if ("org.apache.catalina.connector.ClientAbortException".equals(t.getClass().getName())) { getLogger().warn("ClientAbortException: dropping response"); } else { throw new ServletException("Unable to transform document", t); } } finally { if (wrappedResp != null) { wrappedResp.close(); } if (baos != null) { try { baos.close(); } catch (Exception bae) {} } bytes = null; } logTime("POSTTRANSFORM", sessId, System.currentTimeMillis() - startTime); }"
Inversion-Mutation
megadiff
"public static IDataset getSlice(final ILazyDataset ld, final SliceObject currentSlice, final IProgressMonitor monitor) throws Exception { final int[] dataShape = currentSlice.getFullShape(); if (monitor!=null&&monitor.isCanceled()) return null; // This is the bit that takes the time. // *DO NOT CANCEL MONITOR* if we get this far IDataset slice = (IDataset)ld.getSlice(currentSlice.getSliceStart(), currentSlice.getSliceStop(), currentSlice.getSliceStep()); slice.setName("Slice of "+currentSlice.getName()+" "+currentSlice.getShapeMessage()); final DimsDataList ddl = (DimsDataList)currentSlice.getDimensionalData(); final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class); if (currentSlice.isRange()) { // We sum the data in the dimensions that are not axes IDataset sum = slice; final int len = dataShape.length; for (int i = len-1; i >= 0; i--) { if (!currentSlice.isAxis(i) && dataShape[i]>1) sum = service.sum(sum, i); } if (currentSlice.getX() > currentSlice.getY()) sum = service.transpose(sum); sum = sum.squeeze(); sum.setName(slice.getName()); slice = sum; } else { if (ddl!=null && !ddl.isEmpty()) { final int len = dataShape.length; for (int i = len-1; i >= 0; i--) { final DimsData dd = ddl.getDimsData(i); if (dd.getPlotAxis().isAdvanced()) { slice = dd.getPlotAxis().process(slice,i); } } } slice = slice.squeeze(); if (currentSlice.getX() > currentSlice.getY() && slice.getShape().length==2) { // transpose clobbers name final String name = slice.getName(); slice = service.transpose(slice); if (name!=null) slice.setName(name); } } return slice; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getSlice"
"public static IDataset getSlice(final ILazyDataset ld, final SliceObject currentSlice, final IProgressMonitor monitor) throws Exception { final int[] dataShape = currentSlice.getFullShape(); if (monitor!=null&&monitor.isCanceled()) return null; // This is the bit that takes the time. // *DO NOT CANCEL MONITOR* if we get this far IDataset slice = (IDataset)ld.getSlice(currentSlice.getSliceStart(), currentSlice.getSliceStop(), currentSlice.getSliceStep()); slice.setName("Slice of "+currentSlice.getName()+" "+currentSlice.getShapeMessage()); final DimsDataList ddl = (DimsDataList)currentSlice.getDimensionalData(); final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class); if (currentSlice.isRange()) { // We sum the data in the dimensions that are not axes IDataset sum = slice; final int len = dataShape.length; for (int i = len-1; i >= 0; i--) { if (!currentSlice.isAxis(i) && dataShape[i]>1) sum = service.sum(sum, i); } if (currentSlice.getX() > currentSlice.getY()) sum = service.transpose(sum); <MASK>sum.setName(slice.getName());</MASK> sum = sum.squeeze(); slice = sum; } else { if (ddl!=null && !ddl.isEmpty()) { final int len = dataShape.length; for (int i = len-1; i >= 0; i--) { final DimsData dd = ddl.getDimsData(i); if (dd.getPlotAxis().isAdvanced()) { slice = dd.getPlotAxis().process(slice,i); } } } slice = slice.squeeze(); if (currentSlice.getX() > currentSlice.getY() && slice.getShape().length==2) { // transpose clobbers name final String name = slice.getName(); slice = service.transpose(slice); if (name!=null) slice.setName(name); } } return slice; }"
Inversion-Mutation
megadiff
"private void setDirection( int direction ) { currentDirection = direction; speed = SPEED; switch( currentDirection ) { case LEFT_DIRECTION: rightSprite.setVisible(false); leftSprite.setVisible(true); leftSprite.animate(ANIMATION_SPEED); break; case RIGHT_DIRECTION: leftSprite.setVisible(false); rightSprite.setVisible(true); rightSprite.animate(ANIMATION_SPEED); break; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setDirection"
"private void setDirection( int direction ) { currentDirection = direction; speed = SPEED; switch( currentDirection ) { case LEFT_DIRECTION: leftSprite.setVisible(true); <MASK>rightSprite.setVisible(false);</MASK> leftSprite.animate(ANIMATION_SPEED); break; case RIGHT_DIRECTION: leftSprite.setVisible(false); rightSprite.setVisible(true); rightSprite.animate(ANIMATION_SPEED); break; } }"
Inversion-Mutation
megadiff
"private synchronized KAuthFile getAuthFile() throws AuthenticationException { try { if (_kpwdFile != null && _kpwdFile.lastModified() >= _cacheTime) { _cacheAuthFile = new KAuthFile(_kpwdFile.getPath()); _cacheTime = System.currentTimeMillis(); } return _cacheAuthFile; } catch (IOException e) { throw new AuthenticationException(e.getMessage(), e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getAuthFile"
"private synchronized KAuthFile getAuthFile() throws AuthenticationException { try { if (_kpwdFile != null && _kpwdFile.lastModified() >= _cacheTime) { <MASK>_cacheTime = System.currentTimeMillis();</MASK> _cacheAuthFile = new KAuthFile(_kpwdFile.getPath()); } return _cacheAuthFile; } catch (IOException e) { throw new AuthenticationException(e.getMessage(), e); } }"
Inversion-Mutation
megadiff
"public HttpExchangeImpl( final HttpRequest request, final HttpRoute route, final Object state, final IOSessionManager<HttpRoute> sessmrg) { super(); this.request = request; this.responseFuture = new BasicFuture<HttpResponse>(null); this.sessionFuture = sessmrg.leaseSession(route, state, new InternalFutureCallback()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "HttpExchangeImpl"
"public HttpExchangeImpl( final HttpRequest request, final HttpRoute route, final Object state, final IOSessionManager<HttpRoute> sessmrg) { super(); this.request = request; <MASK>this.sessionFuture = sessmrg.leaseSession(route, state, new InternalFutureCallback());</MASK> this.responseFuture = new BasicFuture<HttpResponse>(null); }"
Inversion-Mutation
megadiff
"public void populateKryo(Kryo k) { k.setRegistrationOptional(getAcceptAll()); registerHierarchies(k, getHierarchyRegistrations(), getSkipMissing()); registerBasic(k, getSerializations(), getSkipMissing()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "populateKryo"
"public void populateKryo(Kryo k) { k.setRegistrationOptional(getAcceptAll()); <MASK>registerBasic(k, getSerializations(), getSkipMissing());</MASK> registerHierarchies(k, getHierarchyRegistrations(), getSkipMissing()); }"
Inversion-Mutation
megadiff
"public static Object getInstance(final Class<?> clazz, final Object[][] prioritizedParameters) { Object object = null; for (Object[] parameters : prioritizedParameters) { Constructor<?> constructor; Class<?>[] parameterClasses = getParameterClasses(parameters); try { if (object == null) { constructor = getMatchingConstructor(clazz, parameterClasses); if (constructor != null) { object = constructor.newInstance(parameters); break; } } } catch (SecurityException e) { logger.debug("Cannot instanciate object for class " + clazz + " with parameters (" + getReadableStringFromClassArray(parameterClasses) + ").", e); } catch (IllegalArgumentException e) { logger.debug("Cannot instanciate object for class " + clazz + " with parameters (" + getReadableStringFromClassArray(parameterClasses) + ").", e); } catch (InstantiationException e) { logger.debug("Cannot instanciate object for class " + clazz + " with parameters (" + getReadableStringFromClassArray(parameterClasses) + ").", e); } catch (IllegalAccessException e) { logger.debug("Cannot instanciate object for class " + clazz + " with parameters (" + getReadableStringFromClassArray(parameterClasses) + ").", e); } catch (InvocationTargetException e) { logger.debug("Cannot instanciate object for class " + clazz + " with parameters (" + getReadableStringFromClassArray(parameterClasses) + ").", e); } } return object; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getInstance"
"public static Object getInstance(final Class<?> clazz, final Object[][] prioritizedParameters) { Object object = null; for (Object[] parameters : prioritizedParameters) { Constructor<?> constructor; Class<?>[] parameterClasses = getParameterClasses(parameters); try { if (object == null) { constructor = getMatchingConstructor(clazz, parameterClasses); if (constructor != null) { object = constructor.newInstance(parameters); } <MASK>break;</MASK> } } catch (SecurityException e) { logger.debug("Cannot instanciate object for class " + clazz + " with parameters (" + getReadableStringFromClassArray(parameterClasses) + ").", e); } catch (IllegalArgumentException e) { logger.debug("Cannot instanciate object for class " + clazz + " with parameters (" + getReadableStringFromClassArray(parameterClasses) + ").", e); } catch (InstantiationException e) { logger.debug("Cannot instanciate object for class " + clazz + " with parameters (" + getReadableStringFromClassArray(parameterClasses) + ").", e); } catch (IllegalAccessException e) { logger.debug("Cannot instanciate object for class " + clazz + " with parameters (" + getReadableStringFromClassArray(parameterClasses) + ").", e); } catch (InvocationTargetException e) { logger.debug("Cannot instanciate object for class " + clazz + " with parameters (" + getReadableStringFromClassArray(parameterClasses) + ").", e); } } return object; }"
Inversion-Mutation
megadiff
"public String toXML() { StringBuffer buf = new StringBuffer(); buf.append("<iq "); if (getPacketID() != null) { buf.append("id=\"" + getPacketID() + "\" "); } if (getTo() != null) { buf.append("to=\"").append(getTo()).append("\" "); } if (getFrom() != null) { buf.append("from=\"").append(getFrom()).append("\" "); } if (type == null) { buf.append("type=\"get\">"); } else { buf.append("type=\"").append(getType()).append("\">"); } // Add the query section if there is one. String queryXML = getChildElementXML(); if (queryXML != null) { buf.append(queryXML); } // Add the error sub-packet, if there is one. XMPPError error = getError(); if (error != null) { buf.append(error.toXML()); } buf.append("</iq>"); return buf.toString(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "toXML"
"public String toXML() { StringBuffer buf = new StringBuffer(); buf.append("<iq "); if (getPacketID() != null) { buf.append("id=\"" + getPacketID() + "\" "); } if (getTo() != null) { buf.append("to=\"").append(getTo()).append("\" "); } if (getFrom() != null) { buf.append("from=\"").append(getFrom()).append("\" "); } if (type == null) { buf.append("type=\"get\">"); } else { buf.append("type=\"").append(getType()).append("\">"); } // Add the query section if there is one. String queryXML = getChildElementXML(); if (queryXML != null) { buf.append(queryXML); } <MASK>buf.append("</iq>");</MASK> // Add the error sub-packet, if there is one. XMPPError error = getError(); if (error != null) { buf.append(error.toXML()); } return buf.toString(); }"
Inversion-Mutation
megadiff
"private static void setupStatic(NoItem instance) { NoItem.instance = instance; NoItem.config = new Config(); NoItem.permsManager = new PermMan(); NoItem.lists = new Lists(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setupStatic"
"private static void setupStatic(NoItem instance) { NoItem.instance = instance; <MASK>NoItem.permsManager = new PermMan();</MASK> NoItem.config = new Config(); NoItem.lists = new Lists(); }"
Inversion-Mutation
megadiff
"private static Class makeClass(Class referent, Vector secondary, String name, ByteArrayOutputStream bytes) { Vector referents = null; if (secondary != null) { if (referent != null) { secondary.insertElementAt(referent,0); } referents = secondary; } else { if (referent != null) { referents = new Vector(); referents.addElement(referent); } } return BytecodeLoader.makeClass(name, referents, bytes.toByteArray()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "makeClass"
"private static Class makeClass(Class referent, Vector secondary, String name, ByteArrayOutputStream bytes) { Vector referents = null; if (secondary != null) { if (referent != null) { secondary.insertElementAt(referent,0); <MASK>referents = secondary;</MASK> } } else { if (referent != null) { referents = new Vector(); referents.addElement(referent); } } return BytecodeLoader.makeClass(name, referents, bytes.toByteArray()); }"
Inversion-Mutation
megadiff
"protected void createNormalLayout() { preLoadImages(); layout = new GridBagLayout(); gbConstraints = new GridBagConstraints(); setLayout(layout); // Create constraint for first component as standard constraint. parent.buildConstraints(gbConstraints, 0, 0, 1, 1, 0.25, 0.0); gbConstraints.insets = new Insets(5, 5, 5, 5); gbConstraints.anchor = GridBagConstraints.WEST; // Create the info label. createLabel( "PacksPanel.info", "preferences", layout, gbConstraints); // Create the snap label. parent.buildConstraints(gbConstraints, 1, 0, 1, 1, 0.50, 0.0); createLabel( "ImgPacksPanel.snap", "tip", layout, gbConstraints); // Create packs table with a scroller. tableScroller = new JScrollPane(); parent.buildConstraints(gbConstraints, 0, 1, 1, 2, 0.50, 0.0); gbConstraints.fill = GridBagConstraints.BOTH; packsTable = createPacksTable(250, tableScroller, layout, gbConstraints ); // Create the image label with a scroller. imgLabel = new JLabel((ImageIcon) images.get(0)); JScrollPane imgScroller = new JScrollPane(imgLabel); imgScroller.setPreferredSize(getPreferredSizeFromImages()); parent.buildConstraints(gbConstraints, 1, 1, 1, 1, 0.5, 1.0); layout.addLayoutComponent(imgScroller, gbConstraints); add(imgScroller); // Create a vertical strut. Component strut = Box.createVerticalStrut(20); parent.buildConstraints(gbConstraints, 1, 2, 1, 3, 0.0, 0.0); layout.addLayoutComponent(strut, gbConstraints); add(strut); // Create the dependency area with a scroller. if( dependenciesExist ) { JScrollPane depScroller = new JScrollPane(); depScroller.setPreferredSize(new Dimension(250, 40)); parent.buildConstraints(gbConstraints, 0, 3, 1, 1, 0.50, 0.50); dependencyArea = createTextArea("ImgPacksPanel.dependencyList", depScroller, layout, gbConstraints ); } // Create the description area with a scroller. descriptionScroller = new JScrollPane(); descriptionScroller.setPreferredSize(new Dimension(200, 60)); parent.buildConstraints(gbConstraints, 1, 3, 1, 1, 0.50, 0.50); descriptionArea = createTextArea("PacksPanel.description", descriptionScroller, layout, gbConstraints ); // Create the tip label. parent.buildConstraints(gbConstraints, 0, 4, 2, 1, 0.0, 0.0); createLabel( "PacksPanel.tip", "tip", layout, gbConstraints); // Create the space label. parent.buildConstraints(gbConstraints, 0, 5, 2, 1, 0.0, 0.0); spaceLabel = createPanelWithLabel( "PacksPanel.space", layout, gbConstraints ); if( IoHelper.supported("getFreeSpace")) { // Create the free space label only if free space is supported. parent.buildConstraints(gbConstraints, 0, 6, 2, 1, 0.0, 0.0); freeSpaceLabel = createPanelWithLabel( "PacksPanel.freespace", layout, gbConstraints ); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createNormalLayout"
"protected void createNormalLayout() { preLoadImages(); layout = new GridBagLayout(); gbConstraints = new GridBagConstraints(); setLayout(layout); // Create constraint for first component as standard constraint. parent.buildConstraints(gbConstraints, 0, 0, 1, 1, 0.25, 0.0); gbConstraints.insets = new Insets(5, 5, 5, 5); <MASK>gbConstraints.fill = GridBagConstraints.BOTH;</MASK> gbConstraints.anchor = GridBagConstraints.WEST; // Create the info label. createLabel( "PacksPanel.info", "preferences", layout, gbConstraints); // Create the snap label. parent.buildConstraints(gbConstraints, 1, 0, 1, 1, 0.50, 0.0); createLabel( "ImgPacksPanel.snap", "tip", layout, gbConstraints); // Create packs table with a scroller. tableScroller = new JScrollPane(); parent.buildConstraints(gbConstraints, 0, 1, 1, 2, 0.50, 0.0); packsTable = createPacksTable(250, tableScroller, layout, gbConstraints ); // Create the image label with a scroller. imgLabel = new JLabel((ImageIcon) images.get(0)); JScrollPane imgScroller = new JScrollPane(imgLabel); imgScroller.setPreferredSize(getPreferredSizeFromImages()); parent.buildConstraints(gbConstraints, 1, 1, 1, 1, 0.5, 1.0); layout.addLayoutComponent(imgScroller, gbConstraints); add(imgScroller); // Create a vertical strut. Component strut = Box.createVerticalStrut(20); parent.buildConstraints(gbConstraints, 1, 2, 1, 3, 0.0, 0.0); layout.addLayoutComponent(strut, gbConstraints); add(strut); // Create the dependency area with a scroller. if( dependenciesExist ) { JScrollPane depScroller = new JScrollPane(); depScroller.setPreferredSize(new Dimension(250, 40)); parent.buildConstraints(gbConstraints, 0, 3, 1, 1, 0.50, 0.50); dependencyArea = createTextArea("ImgPacksPanel.dependencyList", depScroller, layout, gbConstraints ); } // Create the description area with a scroller. descriptionScroller = new JScrollPane(); descriptionScroller.setPreferredSize(new Dimension(200, 60)); parent.buildConstraints(gbConstraints, 1, 3, 1, 1, 0.50, 0.50); descriptionArea = createTextArea("PacksPanel.description", descriptionScroller, layout, gbConstraints ); // Create the tip label. parent.buildConstraints(gbConstraints, 0, 4, 2, 1, 0.0, 0.0); createLabel( "PacksPanel.tip", "tip", layout, gbConstraints); // Create the space label. parent.buildConstraints(gbConstraints, 0, 5, 2, 1, 0.0, 0.0); spaceLabel = createPanelWithLabel( "PacksPanel.space", layout, gbConstraints ); if( IoHelper.supported("getFreeSpace")) { // Create the free space label only if free space is supported. parent.buildConstraints(gbConstraints, 0, 6, 2, 1, 0.0, 0.0); freeSpaceLabel = createPanelWithLabel( "PacksPanel.freespace", layout, gbConstraints ); } }"
Inversion-Mutation
megadiff
"private void addActionsToMenu() { Set<TaskRepository> includedRepositories = new HashSet<TaskRepository>(); TaskRepository localRepository = TasksUi.getRepositoryManager().getRepository( LocalRepositoryConnector.CONNECTOR_KIND, LocalRepositoryConnector.REPOSITORY_URL); addRepositoryAction(localRepository); IWorkingSet workingSet = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getActivePage() .getAggregateWorkingSet(); if (workingSet != null && !workingSet.isEmpty()) { // only add repositories in working set for (IAdaptable iterable_element : workingSet.getElements()) { if (iterable_element instanceof RepositoryQuery) { String repositoryUrl = ((RepositoryQuery) iterable_element).getRepositoryUrl(); String connectorKind = ((RepositoryQuery) iterable_element).getConnectorKind(); TaskRepository repository = TasksUi.getRepositoryManager().getRepository(connectorKind, repositoryUrl); if (repository != null && !repository.isOffline() && !repository.getConnectorKind().equals(LocalRepositoryConnector.CONNECTOR_KIND)) { includedRepositories.add(repository); } } } } else { // add all repositories for (TaskRepository repository : TasksUi.getRepositoryManager().getAllRepositories()) { if (repository != null && !repository.isOffline() && !repository.getConnectorKind().equals(LocalRepositoryConnector.CONNECTOR_KIND)) { includedRepositories.add(repository); } } } if (!includedRepositories.isEmpty()) { new Separator().fill(dropDownMenu, -1); ArrayList<TaskRepository> listOfRepositories = new ArrayList<TaskRepository>(includedRepositories); final TaskRepositoriesSorter comparator = new TaskRepositoriesSorter(); Collections.sort(listOfRepositories, new Comparator<TaskRepository>() { public int compare(TaskRepository arg0, TaskRepository arg1) { return comparator.compare(null, arg0, arg1); } }); for (TaskRepository taskRepository : listOfRepositories) { addRepositoryAction(taskRepository); } } new Separator().fill(dropDownMenu, -1); new ActionContributionItem(new NewQueryAction()).fill(dropDownMenu, -1); new ActionContributionItem(new NewCategoryAction()).fill(dropDownMenu, -1); new Separator().fill(dropDownMenu, -1); new ActionContributionItem(new AddRepositoryAction()).fill(dropDownMenu, -1); new Separator(IWorkbenchActionConstants.MB_ADDITIONS); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addActionsToMenu"
"private void addActionsToMenu() { Set<TaskRepository> includedRepositories = new HashSet<TaskRepository>(); TaskRepository localRepository = TasksUi.getRepositoryManager().getRepository( LocalRepositoryConnector.CONNECTOR_KIND, LocalRepositoryConnector.REPOSITORY_URL); addRepositoryAction(localRepository); IWorkingSet workingSet = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getActivePage() .getAggregateWorkingSet(); if (workingSet != null && !workingSet.isEmpty()) { // only add repositories in working set for (IAdaptable iterable_element : workingSet.getElements()) { if (iterable_element instanceof RepositoryQuery) { String repositoryUrl = ((RepositoryQuery) iterable_element).getRepositoryUrl(); String connectorKind = ((RepositoryQuery) iterable_element).getConnectorKind(); TaskRepository repository = TasksUi.getRepositoryManager().getRepository(connectorKind, repositoryUrl); if (repository != null && !repository.isOffline() && !repository.getConnectorKind().equals(LocalRepositoryConnector.CONNECTOR_KIND)) { includedRepositories.add(repository); } } } } else { // add all repositories for (TaskRepository repository : TasksUi.getRepositoryManager().getAllRepositories()) { if (repository != null && !repository.isOffline() && !repository.getConnectorKind().equals(LocalRepositoryConnector.CONNECTOR_KIND)) { includedRepositories.add(repository); } } } if (!includedRepositories.isEmpty()) { new Separator().fill(dropDownMenu, -1); ArrayList<TaskRepository> listOfRepositories = new ArrayList<TaskRepository>(includedRepositories); final TaskRepositoriesSorter comparator = new TaskRepositoriesSorter(); Collections.sort(listOfRepositories, new Comparator<TaskRepository>() { public int compare(TaskRepository arg0, TaskRepository arg1) { return comparator.compare(null, arg0, arg1); } }); for (TaskRepository taskRepository : listOfRepositories) { addRepositoryAction(taskRepository); } } new Separator().fill(dropDownMenu, -1); <MASK>new ActionContributionItem(new NewCategoryAction()).fill(dropDownMenu, -1);</MASK> new ActionContributionItem(new NewQueryAction()).fill(dropDownMenu, -1); new Separator().fill(dropDownMenu, -1); new ActionContributionItem(new AddRepositoryAction()).fill(dropDownMenu, -1); new Separator(IWorkbenchActionConstants.MB_ADDITIONS); }"
Inversion-Mutation
megadiff
"private void processBuffer() { try { while (!buffer.isEmpty()) { logger.debug("Executing "+buffer.size()+" database actions."); IDatabaseAction databaseAction = buffer.peek(); databaseAction.run(); buffer.poll(); } if (ModelUtility.hasImportedProjects(ResourcesPlugin.getWorkspace())) { StatusWidget.getInstance().setStatus(Status.OK_STATUS); buffer.offer(new FetchNewEventsAction()); } backoffMultiplier = 1; } catch (Exception ex) { backoffMultiplier = backoffMultiplier > MAX_MULTIPLIER ? 1 : backoffMultiplier*2; if (ex.getCause() != null && "org.hibernate.exception.JDBCConnectionException".equals(ex.getCause().getClass().getName())) { StatusWidget.getInstance().setStatus(Status.CANCEL_STATUS); } logger.error(ex, ex); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processBuffer"
"private void processBuffer() { try { <MASK>logger.debug("Executing "+buffer.size()+" database actions.");</MASK> while (!buffer.isEmpty()) { IDatabaseAction databaseAction = buffer.peek(); databaseAction.run(); buffer.poll(); } if (ModelUtility.hasImportedProjects(ResourcesPlugin.getWorkspace())) { StatusWidget.getInstance().setStatus(Status.OK_STATUS); buffer.offer(new FetchNewEventsAction()); } backoffMultiplier = 1; } catch (Exception ex) { backoffMultiplier = backoffMultiplier > MAX_MULTIPLIER ? 1 : backoffMultiplier*2; if (ex.getCause() != null && "org.hibernate.exception.JDBCConnectionException".equals(ex.getCause().getClass().getName())) { StatusWidget.getInstance().setStatus(Status.CANCEL_STATUS); } logger.error(ex, ex); } }"
Inversion-Mutation
megadiff
"void initGrabber(int w, int h, int _targetFps){ if(deviceID==-1) camera = Camera.open(); else{ try { int numCameras = (Integer) Camera.class.getMethod("getNumberOfCameras").invoke(null); Class<?> cameraInfoClass = Class.forName("android.hardware.Camera$CameraInfo"); Object cameraInfo = null; Field field = null; if ( cameraInfoClass != null ) { cameraInfo = cameraInfoClass.newInstance(); } if ( cameraInfo != null ) { field = cameraInfo.getClass().getField( "facing" ); } Method getCameraInfoMethod = Camera.class.getMethod( "getCameraInfo", Integer.TYPE, cameraInfoClass ); for(int i=0;i<numCameras;i++){ getCameraInfoMethod.invoke( null, i, cameraInfo ); int facing = field.getInt( cameraInfo ); Log.v("OF","Camera " + i + " facing: " + facing); } camera = (Camera) Camera.class.getMethod("open", Integer.TYPE).invoke(null, deviceID); } catch (Exception e) { // TODO Auto-generated catch block Log.e("OF","Error trying to open specific camera, trying default",e); camera = Camera.open(); } } Camera.Parameters config = camera.getParameters(); Log.i("OF","Grabber supported sizes"); for(Size s : config.getSupportedPreviewSizes()){ Log.i("OF",s.width + " " + s.height); } Log.i("OF","Grabber supported formats"); for(Integer i : config.getSupportedPreviewFormats()){ Log.i("OF",i.toString()); } Log.i("OF","Grabber supported fps"); for(Integer i : config.getSupportedPreviewFrameRates()){ Log.i("OF",i.toString()); } Log.i("OF", "Grabber default format: " + config.getPreviewFormat()); Log.i("OF", "Grabber default preview size: " + config.getPreviewSize().width + "," + config.getPreviewSize().height); config.setPreviewSize(w, h); config.setPreviewFormat(ImageFormat.NV21); try{ camera.setParameters(config); }catch(Exception e){ Log.e("OF","couldn init camera", e); } config = camera.getParameters(); width = config.getPreviewSize().width; height = config.getPreviewSize().height; if(width!=w || height!=h) Log.w("OF","camera size different than asked for, resizing (this can slow the app)"); if(_targetFps!=-1){ config = camera.getParameters(); config.setPreviewFrameRate(_targetFps); try{ camera.setParameters(config); }catch(Exception e){ Log.e("OF","couldn init camera", e); } } targetFps = _targetFps; Log.i("OF","camera settings: " + width + "x" + height); buffer = new byte[width*height*2]; orientationListener = new OrientationListener(OFAndroid.getContext()); orientationListener.enable(); thread = new Thread(this); thread.start(); initialized = true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initGrabber"
"void initGrabber(int w, int h, int _targetFps){ if(deviceID==-1) <MASK>camera = Camera.open();</MASK> else{ try { int numCameras = (Integer) Camera.class.getMethod("getNumberOfCameras").invoke(null); Class<?> cameraInfoClass = Class.forName("android.hardware.Camera$CameraInfo"); Object cameraInfo = null; Field field = null; if ( cameraInfoClass != null ) { cameraInfo = cameraInfoClass.newInstance(); } if ( cameraInfo != null ) { field = cameraInfo.getClass().getField( "facing" ); } Method getCameraInfoMethod = Camera.class.getMethod( "getCameraInfo", Integer.TYPE, cameraInfoClass ); for(int i=0;i<numCameras;i++){ getCameraInfoMethod.invoke( null, i, cameraInfo ); int facing = field.getInt( cameraInfo ); Log.v("OF","Camera " + i + " facing: " + facing); } camera = (Camera) Camera.class.getMethod("open", Integer.TYPE).invoke(null, deviceID); } catch (Exception e) { // TODO Auto-generated catch block Log.e("OF","Error trying to open specific camera, trying default",e); } <MASK>camera = Camera.open();</MASK> } Camera.Parameters config = camera.getParameters(); Log.i("OF","Grabber supported sizes"); for(Size s : config.getSupportedPreviewSizes()){ Log.i("OF",s.width + " " + s.height); } Log.i("OF","Grabber supported formats"); for(Integer i : config.getSupportedPreviewFormats()){ Log.i("OF",i.toString()); } Log.i("OF","Grabber supported fps"); for(Integer i : config.getSupportedPreviewFrameRates()){ Log.i("OF",i.toString()); } Log.i("OF", "Grabber default format: " + config.getPreviewFormat()); Log.i("OF", "Grabber default preview size: " + config.getPreviewSize().width + "," + config.getPreviewSize().height); config.setPreviewSize(w, h); config.setPreviewFormat(ImageFormat.NV21); try{ camera.setParameters(config); }catch(Exception e){ Log.e("OF","couldn init camera", e); } config = camera.getParameters(); width = config.getPreviewSize().width; height = config.getPreviewSize().height; if(width!=w || height!=h) Log.w("OF","camera size different than asked for, resizing (this can slow the app)"); if(_targetFps!=-1){ config = camera.getParameters(); config.setPreviewFrameRate(_targetFps); try{ camera.setParameters(config); }catch(Exception e){ Log.e("OF","couldn init camera", e); } } targetFps = _targetFps; Log.i("OF","camera settings: " + width + "x" + height); buffer = new byte[width*height*2]; orientationListener = new OrientationListener(OFAndroid.getContext()); orientationListener.enable(); thread = new Thread(this); thread.start(); initialized = true; }"
Inversion-Mutation
megadiff
"private void clear() { setRegisterKeys(false); body.clear(); patchSetPanels.clear(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "clear"
"private void clear() { body.clear(); patchSetPanels.clear(); <MASK>setRegisterKeys(false);</MASK> }"
Inversion-Mutation
megadiff
"public String render(Report report) { StringBuffer buf = new StringBuffer(quoteAndCommify("Problem")); buf.append(quoteAndCommify("Package")); buf.append(quoteAndCommify("File")); buf.append(quoteAndCommify("Priority")); buf.append(quoteAndCommify("Line")); buf.append(quoteAndCommify("Description")); buf.append(quoteAndCommify("Rule set")); buf.append(quote("Rule")); buf.append(PMD.EOL); int violationCount = 1; for (Iterator i = report.iterator(); i.hasNext();) { IRuleViolation rv = (IRuleViolation) i.next(); buf.append(quoteAndCommify(Integer.toString(violationCount))); buf.append(quoteAndCommify(rv.getPackageName())); buf.append(quoteAndCommify(rv.getFilename())); buf.append(quoteAndCommify(Integer.toString(rv.getRule().getPriority()))); buf.append(quoteAndCommify(Integer.toString(rv.getBeginLine()))); buf.append(quoteAndCommify(StringUtil.replaceString(rv.getDescription(), '\"', "'"))); buf.append(quoteAndCommify(rv.getRule().getRuleSetName())); buf.append(quote(rv.getRule().getName())); buf.append(PMD.EOL); violationCount++; } return buf.toString(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "render"
"public String render(Report report) { StringBuffer buf = new StringBuffer(quoteAndCommify("Problem")); buf.append(quoteAndCommify("Package")); buf.append(quoteAndCommify("File")); <MASK>buf.append(quoteAndCommify("Line"));</MASK> buf.append(quoteAndCommify("Priority")); buf.append(quoteAndCommify("Description")); buf.append(quoteAndCommify("Rule set")); buf.append(quote("Rule")); buf.append(PMD.EOL); int violationCount = 1; for (Iterator i = report.iterator(); i.hasNext();) { IRuleViolation rv = (IRuleViolation) i.next(); buf.append(quoteAndCommify(Integer.toString(violationCount))); buf.append(quoteAndCommify(rv.getPackageName())); buf.append(quoteAndCommify(rv.getFilename())); buf.append(quoteAndCommify(Integer.toString(rv.getRule().getPriority()))); buf.append(quoteAndCommify(Integer.toString(rv.getBeginLine()))); buf.append(quoteAndCommify(StringUtil.replaceString(rv.getDescription(), '\"', "'"))); buf.append(quoteAndCommify(rv.getRule().getRuleSetName())); buf.append(quote(rv.getRule().getName())); buf.append(PMD.EOL); violationCount++; } return buf.toString(); }"
Inversion-Mutation
megadiff
"void runLogic() { /* * Don't yet know the train/track implementation to * determine if a train is headed for the train yard. */ /* Switch tySwitch = (Switch) track.get(trackEnd()); Train train = tySwitch.getTrain(); if ((train != null) && train.needsToGoToTrainYard()) { tySwitch.setSwitchState(Switch.SwitchState.LEFT); spreadAuthority(1); } else { tySwitch.setSwitchState(Switch.SwitchState.RIGHT); if (nextRight().clearToReceiveFrom(this)) { spreadAuthority(0); } else { Switch s = (Switch) track.get(trackEnd()).getNext(direction); s.setSwitchState(Switch.SwitchState.RIGHT); spreadAuthority(1); } } */ }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "runLogic"
"void runLogic() { /* * Don't yet know the train/track implementation to * determine if a train is headed for the train yard. */ /* Switch tySwitch = (Switch) track.get(trackEnd()); Train train = tySwitch.getTrain(); if ((train != null) && train.needsToGoToTrainYard()) { tySwitch.setSwitchState(Switch.SwitchState.LEFT); spreadAuthority(1); <MASK>}</MASK> else { tySwitch.setSwitchState(Switch.SwitchState.RIGHT); if (nextRight().clearToReceiveFrom(this)) { spreadAuthority(0); <MASK>}</MASK> else { Switch s = (Switch) track.get(trackEnd()).getNext(direction); s.setSwitchState(Switch.SwitchState.RIGHT); spreadAuthority(1); <MASK>}</MASK> <MASK>}</MASK> <MASK>}</MASK> */ <MASK>}</MASK>"