auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean layerGroupContainmentCheckRequired() { // first, is it WMS? Request request = Dispatcher.REQUEST.get(); if(request == null) { return false; } // layer groups are used only in WMS final String service = request.getService(); boolean isMapService = "WMS".equalsIgnoreCase(service) || "gwc".equalsIgnoreCase(service); if(!isMapService) { return false; } return true; }

Target:
private boolean layerGroupContainmentCheckRequired() { // first, is it WMS? Request request = Dispatcher.REQUEST.get(); if(request == null) { return false; } // layer groups are used only in WMS final String service = request.getService(); return "WMS".equalsIgnoreCase(service) || "gwc".equalsIgnoreCase(service); }
Source:
public boolean canStreamToNextPipe() { return super.canStreamToNextPipe() && !isCollectResults(); // when collectResults is false, streaming is not necessary or useful }

Target:
public boolean canStreamToNextPipe() { return !isCollectResults() && super.canStreamToNextPipe(); // when collectResults is false, streaming is not necessary or useful }
Source:
public void tearDown() { try { queryRunner.close(); } finally { queryRunner = null; } }

Target:
public void tearDown() { queryRunner.close(); }
Source:
public List<OutputLine> getLog() { return this.log; }

Target:
public List<OutputLine> getLog() { return new ArrayList<>(this.log); }
Source:
public void executeBatch(OperationsQueue operationsQueue) { log.tracef( "Executing batch" ); try { if ( GridDialects.hasFacet( getGridDialect(), BatchableGridDialect.class ) || GridDialects.hasFacet( getGridDialect(), GroupingByEntityDialect.class ) ) { super.executeBatch( operationsQueue ); } } catch ( TupleAlreadyExistsException taee ) { // TODO: Ideally, we should log the entity name + id here; For now we trust the datastore to provide this // information via the original exception; It'd require a fair bit of changes to obtain the entity name here // (we'd have to obtain the persister matching the given entity key metadata which in turn would require // access to the session factory which is not easily available here) throw log.mustNotInsertSameEntityTwice( taee.getMessage(), taee ); } }

Target:
public void executeBatch(OperationsQueue operationsQueue) { try { if ( GridDialects.hasFacet( getGridDialect(), BatchableGridDialect.class ) || GridDialects.hasFacet( getGridDialect(), GroupingByEntityDialect.class ) ) { log.tracef( "Executing batch" ); super.executeBatch( operationsQueue ); } } catch ( TupleAlreadyExistsException taee ) { // TODO: Ideally, we should log the entity name + id here; For now we trust the datastore to provide this // information via the original exception; It'd require a fair bit of changes to obtain the entity name here // (we'd have to obtain the persister matching the given entity key metadata which in turn would require // access to the session factory which is not easily available here) throw log.mustNotInsertSameEntityTwice( taee.getMessage(), taee ); } }
Source:
public void testWrongFormatNumber() throws Exception { NumberCellEditor editor; editor = new NumberCellEditor(shell, Integer.class); //empty string editor.setValue(" "); editor.getValue(); assertNull(editor.getValue() ); //not parsable number editor.setValue("aa"); editor.getValue(); assertNull(editor.getValue() ); }

Target:
public void testWrongFormatNumber() throws Exception { NumberCellEditor editor; editor = new NumberCellEditor(shell, Integer.class); // empty string editor.getValue(); assertNull(editor.getValue()); // not parsable number editor.setValue("aa"); editor.getValue(); assertNull(editor.getValue()); }
Source:
public DescriptorImpl() { super(ThrottleJobProperty.class); synchronized(propertiesByCategoryLock) { load(); // Explictly drop queue items loaded from 1.8.1 version if (!propertiesByCategory.isEmpty()) { propertiesByCategory = new HashMap<String,Map<ThrottleJobProperty,Void>>(); save(); // Save the configuration to remove obsolete data } } }

Target:
public DescriptorImpl() { super(ThrottleJobProperty.class); synchronized(propertiesByCategoryLock) { load(); // Explictly handle the persisted data from the version 1.8.1 if (propertiesByCategory == null) { propertiesByCategory = new HashMap<String,Map<ThrottleJobProperty,Void>>(); } if (!propertiesByCategory.isEmpty()) { propertiesByCategory.clear(); save(); // Save the configuration to remove obsolete data } } }
Source:
public String toString() { // Since the static data arrives from external source it's not guarenteed not to be null so a null check is // mandatory in order to avoid NPE when invoking toString by the logger String domainName = staticData.getName() == null ? "null" : staticData.getName(); String domainId = staticData.getId() == null ? "null" : staticData.getId().toString(); return "StorageDomain[" + domainName + ", " + domainId + "]"; }

Target:
public String toString() { // Since the static data arrives from external source it's not guarenteed not to be null so a null check is // mandatory in order to avoid NPE when invoking toString by the logger String domainName = staticData == null ? "null" : staticData.getName(); Guid domainId = staticData == null ? null : staticData.getId(); return "StorageDomain[" + domainName + ", " + domainId + "]"; }
Source:
private void sendToSocket(Socket socket, String cmdString) throws IOException { // remove spaces at beginning and end and replace double spaces in // string with single space byte[] sendBytes = ("A" + cmdString.trim().replaceAll("\\s+", " ") + "\n").getBytes(); socket.getInputStream().skip(tcpSocket.getInputStream().available()); socket.getOutputStream().write(sendBytes); socket.getOutputStream().flush(); AstericsErrorHandling.instance.reportInfo(this, "IRTrans sent data: " + cmdString); }

Target:
private void sendToSocket(Socket socket, String cmdString) throws IOException { // remove spaces at beginning and end and replace double spaces in // string with single space byte[] sendBytes = ("A" + cmdString.trim().replaceAll("\\s+", " ") + "\n").getBytes(); socket.getInputStream().skip(socket.getInputStream().available()); socket.getOutputStream().write(sendBytes); socket.getOutputStream().flush(); AstericsErrorHandling.instance.reportInfo(this, "IRTrans sent data: " + cmdString); }
Source:
public boolean hasMatchingOpSig(String name, JavaOperationSigMask mask) { // Indexing on signatures optimises this type of request for (Entry<JavaOperationSignature, Set<String>> entry : operations.entrySet()) { if (mask.covers(entry.getKey())) { if (operations.get(entry.getKey()).contains(name)) { return true; } } } return false; }

Target:
public boolean hasMatchingOpSig(String name, JavaOperationSigMask mask) { // Indexing on signatures optimises this type of request for (Entry<JavaOperationSignature, Set<String>> entry : operations.entrySet()) { if (mask.covers(entry.getKey())) { if (entry.getValue().contains(name)) { return true; } } } return false; }
Source:
protected OperationController getOperationController() { return ocList.get(ThreadLocalRandom.current().nextInt(ocList.size())); }

Target:
private OperationController getOperationController() { return ocList.get(ThreadLocalRandom.current().nextInt(ocList.size())); }
Source:
private JsonObject toJson(Timer timer, TimeUnit rateUnit, TimeUnit durationUnit) { Snapshot snapshot = timer.getSnapshot(); JsonObject json = new JsonObject(); // Meter populateMetered(json, timer, rateUnit); // Snapshot double factor = 1.0 / durationUnit.toNanos(1); populateSnapshot(json, snapshot, factor); // Duration rate String duration = durationUnit.toString().toLowerCase(Locale.US); json.putString("durationRate", duration); return json; }

Target:
private JsonObject toJson(Timer timer, TimeUnit rateUnit, TimeUnit durationUnit) { Snapshot snapshot = timer.getSnapshot(); JsonObject json = new JsonObject(); // Meter populateMetered(json, timer, rateUnit); // Snapshot double factor = 1.0 / durationUnit.toNanos(1); populateSnapshot(json, snapshot, factor); // Duration rate String duration = durationUnit.toString().toLowerCase(); json.putString("durationRate", duration); return json; }
Source:
public String getExtendedLabelForVSM(String providedShapeURI) { for (IConfigurationElement configurationElement : extensions) { String identifier = ((ExtensionHandle) configurationElement.getParent()).getSimpleIdentifier(); if (identifier != null && identifier.equals(providedShapeURI)) { return configurationElement.getAttribute(LABEL_ATTRIBUTE) + " - " + configurationElement.getNamespaceIdentifier(); //$NON-NLS-1$ } } return "Unknown URI"; //$NON-NLS-1$ }

Target:
public String getExtendedLabelForVSM(String providedShapeURI) { for (IConfigurationElement configurationElement : extensions) { String identifier = ((ExtensionHandle) configurationElement.getParent()).getSimpleIdentifier(); if (identifier != null && identifier.equals(providedShapeURI)) { return getExtendedLabelForVSM(configurationElement); } } return "Unknown URI"; //$NON-NLS-1$ }
Source:
public <C extends CtTypedElement> C setType(CtTypeReference<T> type) { if (type != null) { type.setParent(this); } // even if the setter delegates to getExecutable, it makes sense to create an event getFactory().getEnvironment().getModelChangeListener().onObjectUpdate(this, TYPE, type, getExecutable().getType()); if (getExecutable() != null) { getExecutable().setType(type); } return (C) this; }

Target:
public <C extends CtTypedElement> C setType(CtTypeReference<T> type) { if (type != null) { type.setParent(this); } if (getExecutable() != null) { getExecutable().setType(type); } return (C) this; }
Source:
private void importLdif(InMemoryDirectoryServer directoryServer) throws LDAPException { if (StringUtils.hasText(this.ldif)) { try { Resource resource = locateResource(); try (InputStream inputStream = resource.getInputStream()) { directoryServer.importFromLDIF(false, new LDIFReader(inputStream)); } } catch (Exception ex) { throw new IllegalStateException("Unable to load LDIF " + this.ldif, ex); } } }

Target:
private void importLdif(InMemoryDirectoryServer directoryServer) { if (StringUtils.hasText(this.ldif)) { try { Resource resource = locateResource(); try (InputStream inputStream = resource.getInputStream()) { directoryServer.importFromLDIF(false, new LDIFReader(inputStream)); } } catch (Exception ex) { throw new IllegalStateException("Unable to load LDIF " + this.ldif, ex); } } }
Source:
protected void setUpGetUnregisteredVmTemplateExpectations(boolean notFound) { setUpEntityQueryExpectations( QueryType.GetUnregisteredVmTemplate, GetUnregisteredEntityQueryParameters.class, new String[] { "StorageDomainId", "EntityId" }, new Object[] { STORAGE_DOMAIN_ID, TEMPLATE_ID }, notFound ? null : getEntity(1)); }

Target:
private void setUpGetUnregisteredVmTemplateExpectations(boolean notFound) { setUpEntityQueryExpectations( QueryType.GetUnregisteredVmTemplate, GetUnregisteredEntityQueryParameters.class, new String[] { "StorageDomainId", "EntityId" }, new Object[] { STORAGE_DOMAIN_ID, TEMPLATE_ID }, notFound ? null : getEntity(1)); }
Source:
public Map<String, MetricPlotDTOs> createTaskPlots() { sessionId = getSessionIdProvider().getSessionId(); // check new model List<MetricPointEntity> metricDetails = getHibernateTemplate().find( "select m from MetricPointEntity m where m.metricDescription.taskData.sessionId=?", sessionId); if (metricDetails == null || metricDetails.isEmpty()) { return oldWay(); } else { return newWay(metricDetails); } }

Target:
private Map<String, MetricPlotDTOs> createTaskPlots() { // check new model List<MetricPointEntity> metricDetails = getHibernateTemplate().find( "select m from MetricPointEntity m where m.metricDescription.taskData.sessionId=?", sessionId); if (metricDetails == null || metricDetails.isEmpty()) { return oldWay(); } else { return newWay(metricDetails); } }
Source:
public void testDeadlock() throws Exception { doTest(1000 * 30); // 30 secs almost always locks boolean interrupted = Thread.interrupted(); if (interrupted) { fail("Thread was interrupted at end of test"); } }

Target:
public void testDeadlock() throws Exception { doTest(1000 * 30); // 30 secs almost always locks if (Thread.interrupted()) { fail("Thread was interrupted at end of test"); } }
Source:
private void readInternal(long position, byte[] buffer, int bufferOffset, int bufferLength) { try { long readStart = System.nanoTime(); inputStream.readFully(position, buffer, bufferOffset, bufferLength); stats.readDataBytesPerSecond(bufferLength, System.nanoTime() - readStart); } catch (PrestoException e) { // just in case there is a Presto wrapper or hook throw e; } catch (Exception e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Error reading from %s at position %s", id.toString(), position), e); } }

Target:
private void readInternal(long position, byte[] buffer, int bufferOffset, int bufferLength) { try { long readStart = System.nanoTime(); inputStream.readFully(position, buffer, bufferOffset, bufferLength); stats.readDataBytesPerSecond(bufferLength, System.nanoTime() - readStart); } catch (PrestoException e) { // just in case there is a Presto wrapper or hook throw e; } catch (Exception e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Error reading from %s at position %s", id, position), e); } }
Source:
private DeltaVisit next() { // If our parent has no more children, discard it. if (parent != null && parent.nextChild == null) { parent.data = null; parent = parent.parent; } if (nextChild != null) return new DeltaVisit(this); // If we have no child ourselves, our parent must (if it exists), // due to the discard rule above. With no parent, we are done. if (parent != null) return new DeltaVisit(parent); return null; }

Target:
DeltaVisit next() { // If our parent has no more children, discard it. if (parent != null && parent.nextChild == null) { parent.data = null; parent = parent.parent; } if (nextChild != null) return new DeltaVisit(this); // If we have no child ourselves, our parent must (if it exists), // due to the discard rule above. With no parent, we are done. if (parent != null) return new DeltaVisit(parent); return null; }
Source:
protected boolean isTransientException(Throwable e) { if(e instanceof SQLException) { final String sqlState = ((SQLException) e).getSQLState(); // retry on connection errors and insufficient resources // (see http://www.postgresql.org/docs/current/static/errcodes-appendix.html) return sqlState.startsWith("08") || sqlState.startsWith("53"); } return false; }

Target:
protected boolean isTransientException(Throwable e) { if(e instanceof SQLException) { final String sqlState = ((SQLException) e).getSQLState(); // limited to errors that are likely to be resolved within a few retries // retry on connection errors and insufficient resources // see http://www.postgresql.org/docs/current/static/errcodes-appendix.html for details return sqlState != null && (sqlState.startsWith("08") || sqlState.startsWith("53")); } return false; }
Source:
public JupiterActivity generateJupiterActivity(Operation op, User source, SPath editor) { // send(op, myMsgs, otherMsgs); JupiterActivity jupiterActivity = new JupiterActivity(this.vectorTime, op, source, editor); // add(op, myMsgs) to outgoing; if (!(op instanceof TimestampOperation)) { this.ackJupiterActivityList.add( new OperationWrapper(op, this.vectorTime.getLocalOperationCount())); } // myMsgs = myMsgs + 1; this.vectorTime = this.vectorTime.incrementLocalOperationCount(); return jupiterActivity; }

Target:
public JupiterActivity generateJupiterActivity(Operation op, User source, SPath editor) { // send(op, myMsgs, otherMsgs); JupiterActivity jupiterActivity = new JupiterActivity(this.vectorTime, op, source, editor); // add(op, myMsgs) to outgoing; this.ackJupiterActivityList.add( new OperationWrapper(op, this.vectorTime.getLocalOperationCount())); // myMsgs = myMsgs + 1; this.vectorTime = this.vectorTime.incrementLocalOperationCount(); return jupiterActivity; }
Source:
public void testAssignExecutorInvalidExecutor() throws Exception { final ExecutableFlow flow = TestUtils.createExecutableFlow("exectest1", "exec1"); this.executionFlowDao.uploadExecutableFlow(flow); assertThatThrownBy( () -> this.assignExecutor.assignExecutor(flow.getExecutionId(), 1)) .isInstanceOf(ExecutorManagerException.class) .hasMessageContaining("non-existent executor"); }

Target:
public void testAssignExecutorInvalidExecutor() throws Exception { final ExecutableFlow flow = TestUtils.createExecutableFlow("exectest1", "exec1"); this.executionFlowDao.uploadExecutableFlow(flow); // Since we haven't inserted any executors, 1 should be non-existent executor id. assertThatThrownBy( () -> this.assignExecutor.assignExecutor(1, flow.getExecutionId())) .isInstanceOf(ExecutorManagerException.class) .hasMessageContaining("non-existent executor"); }
Source:
public String toString() { return methodPrefix.toString(); }

Target:
public String toString() { return methodPrefix; }
Source:
Object loadServiceCapabilities(String serviceUrl) throws IOException { HttpGet request = new HttpGet(serviceUrl); request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES)); CloseableHttpResponse httpResponse = execute(request, serviceUrl, "retrieve help"); validateResponse(httpResponse, serviceUrl); HttpEntity httpEntity = httpResponse.getEntity(); ContentType contentType = ContentType.getOrDefault(httpEntity); if ("text/plain".equals(contentType.getMimeType())) { return getContent(httpEntity); } return parseJsonMetadata(httpEntity); }

Target:
Object loadServiceCapabilities(String serviceUrl) throws IOException { HttpGet request = new HttpGet(serviceUrl); request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES)); CloseableHttpResponse httpResponse = execute(request, serviceUrl, "retrieve help"); validateResponse(httpResponse, serviceUrl); HttpEntity httpEntity = httpResponse.getEntity(); ContentType contentType = ContentType.getOrDefault(httpEntity); if (contentType.getMimeType().equals("text/plain")) { return getContent(httpEntity); } return parseJsonMetadata(httpEntity); }
Source:
private boolean shouldBeDistributed(PlanNode planNode) { return planNode instanceof AggregationNode || planNode instanceof JoinNode || (planNode instanceof TopNNode && ((TopNNode) planNode).getStep().equals(TopNNode.Step.PARTIAL)); }

Target:
private boolean shouldBeDistributed(PlanNode planNode) { if (planNode instanceof JoinNode) { return true; } if (planNode instanceof AggregationNode) { // TODO: differentiate aggregation with empty grouping set return true; } if (planNode instanceof TopNNode) { return ((TopNNode) planNode).getStep() == TopNNode.Step.PARTIAL; } return false; }
Source:
public QueryWrapper(@JsonProperty("query") String query, @JsonProperty("queryType") String queryType) { this(query, queryType, ""); }

Target:
public QueryWrapper(@JsonProperty("query") String query, @JsonProperty("queryType") String queryType) { this(query, queryType, null); }
Source:
protected VariableReferenceExpression getVariableReference(RowExpression expression) { if (expression instanceof VariableReferenceExpression) { return ((VariableReferenceExpression) expression); } else { throw new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), "Expected a variable reference but got " + expression); } }

Target:
protected VariableReferenceExpression getVariableReference(RowExpression expression) { if (expression instanceof VariableReferenceExpression) { return ((VariableReferenceExpression) expression); } throw new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), "Expected a variable reference but got " + expression); }
Source:
protected void findUsers(String searchString, AsyncQuery query) { Frontend.getInstance() .runQuery(VdcQueryType.Search, new DirectorySearchParameters("ADUSER@" + ((ProfileEntry) getProfile().getSelectedItem()).getAuthz() + ": " + searchString, SearchType.DirectoryUser, (String) getNamespace().getSelectedItem()), query); //$NON-NLS-1$ //$NON-NLS-2$ }

Target:
protected void findUsers(String searchString, AsyncQuery query) { Frontend.getInstance() .runQuery(VdcQueryType.Search, new DirectorySearchParameters("ADUSER@" + ((ProfileEntry) getProfile().getSelectedItem()).getAuthz() + ": " + searchString, SearchType.DirectoryUser, getNamespace().getSelectedItem()), query); //$NON-NLS-1$ //$NON-NLS-2$ }
Source:
public final String consoleClientResourcesUrl() { String url = getString(DynamicMessageKey.CONSOLE_CLIENT_RESOURCES_URL); boolean isAbsolute = url.contains("://"); return isAbsolute ? url : Window.Location.getProtocol() + "//" + Window.Location.getHost() + //$NON-NLS-1$ "/" + BaseContextPathData.getInstance().getRelativePath() + url; //$NON-NLS-1$ }

Target:
public final String consoleClientResourcesUrl() { String url = getString(DynamicMessageKey.CONSOLE_CLIENT_RESOURCES_URL); boolean isAbsolute = url.contains("://"); return isAbsolute ? url : "/" + BaseContextPathData.getInstance().getRelativePath() + url; //$NON-NLS-1$ }
Source:
void addLayer(String id, StyleLayer layer) { layersById.put(id, layer); }

Target:
public void addLayer(String id, StyleLayer layer) { layersById.put(id, layer); }
Source:
public void setSelection(ITimeGraphEntry trace) { /* if there is a pending selection, ignore this one */ synchronized (fListenerNotifierLock) { if (fListenerNotifier != null && fListenerNotifier.hasSelectionChanged()) { return; } } fSelectedEntry = trace; fTimeGraphCtrl.selectItem(trace, false); adjustVerticalScrollBar(); }

Target:
public void setSelection(ITimeGraphEntry trace) { /* if there is a pending selection, ignore this one */ if (fListenerNotifier != null && fListenerNotifier.hasSelectionChanged()) { return; } fSelectedEntry = trace; fTimeGraphCtrl.selectItem(trace, false); adjustVerticalScrollBar(); }
Source:
private void init() { // get the localhost. try { hostname = InetAddress.getLocalHost().getHostName(); hostname = "localhost"; } catch (UnknownHostException e) { logger.warn("Error getting the value of localhost. " + "Proceeding with 'localhost'.", e); } }

Target:
private void init() { // get the localhost. try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { logger.warn("Error getting the value of localhost. " + "Proceeding with 'localhost'.", e); } }
Source:
protected OSImageToImage(JustProvider provider) { this.provider = provider; }

Target:
OSImageToImage(JustProvider provider) { this.provider = provider; }
Source:
public void destroy() { // clients must be destroyed before the pools or // you will create a several second busy wait loop for (JettyHttpClient client : clients) { client.close(); } if (pool != null) { pool.close(); pool = null; if(injector.getExistingBinding(Key.get(MBeanExporter.class)) != null) { injector.getInstance(MBeanExporter.class) .unexport(generatedNameOf(QueuedThreadPoolMBean.class) + "_" + name); } } destroyed.set(true); }

Target:
public void destroy() { // clients must be destroyed before the pools or // you will create a several second busy wait loop for (JettyHttpClient client : clients) { client.close(); } if (pool != null) { pool.close(); pool = null; } destroyed.set(true); }
Source:
public void testMultipleBatchesLateral_WithStreamingAgg() throws Exception { String sql = "SELECT t2.maxprice FROM (SELECT customer.c_orders AS c_orders FROM " + "dfs.`lateraljoin/multipleFiles/` customer) t1, LATERAL (SELECT CAST(MAX(t.ord.o_totalprice)" + " AS int) AS maxprice FROM UNNEST(t1.c_orders) t(ord) GROUP BY t.ord.o_orderstatus) t2"; testBuilder() .optionSettingQueriesForTestQuery("alter session set `%s` = true", PlannerSettings.STREAMAGG.getOptionName()) .sqlQuery(sql) .unOrdered() .baselineColumns("maxprice") .baselineValues(367190) .baselineValues(316347) .baselineValues(146610) .baselineValues(306996) .baselineValues(235695) .baselineValues(177819) .build().run(); }

Target:
public void testMultipleBatchesLateral_WithStreamingAgg() throws Exception { String sql = "SELECT t2.maxprice FROM (SELECT customer.c_orders AS c_orders FROM " + "dfs.`lateraljoin/multipleFiles/` customer) t1, LATERAL (SELECT CAST(MAX(t.ord.o_totalprice)" + " AS int) AS maxprice FROM UNNEST(t1.c_orders) t(ord) GROUP BY t.ord.o_orderstatus) t2"; testBuilder() .sqlQuery(sql) .unOrdered() .baselineColumns("maxprice") .baselineValues(367190) .baselineValues(316347) .baselineValues(146610) .baselineValues(306996) .baselineValues(235695) .baselineValues(177819) .build().run(); }
Source:
private boolean needProjectionNode (AbstractPlanNode root) { if ( false == root.planNodeClassNeedsProjectionNode()) { return false; } // If there is a complexGroupby at his point, it means that // display columns contain all the order by columns and // does not require another projection node on top of sort node. // If there is a complex aggregation case, the projection plan node is already added // right above the group by plan node. In future, we may inline that projection node. if (m_parsedSelect.hasComplexGroupby() || m_parsedSelect.hasComplexAgg()) { return false; } if (root instanceof AbstractReceivePlanNode && m_parsedSelect.hasPartitionColumnInGroupby()) { // Top aggregate has been removed, its schema is exactly the same to // its local aggregate node. return false; } return true; }

Target:
private boolean needProjectionNode (AbstractPlanNode root) { if (!root.planNodeClassNeedsProjectionNode()) { return false; } // If there is a complexGroupby at his point, it means that // display columns contain all the order by columns and // does not require another projection node on top of sort node. // If there is a complex aggregation case, the projection plan node is already added // right above the group by plan node. In future, we may inline that projection node. if (m_parsedSelect.hasComplexGroupby() || m_parsedSelect.hasComplexAgg()) { return false; } if (root instanceof AbstractReceivePlanNode && m_parsedSelect.hasPartitionColumnInGroupby()) { // Top aggregate has been removed, its schema is exactly the same to // its local aggregate node. return false; } return true; }
Source:
public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof XarSecurityRule)) { return false; } XarSecurityRule rhs = (XarSecurityRule) object; return new EqualsBuilder() .append(this.right, rhs.right) .append(this.simple, rhs.simple) .append(this.securityTool, rhs.securityTool) .isEquals(); }

Target:
public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof XarSecurityRule)) { return false; } XarSecurityRule rhs = (XarSecurityRule) object; return new EqualsBuilder() .append(this.right, rhs.right) .append(this.simple, rhs.simple) .isEquals(); }
Source:
private static int computeNewVectorCapacity(int usedCapacity, int newPayload, int currentCapacity) { int newUsedCapacity = BaseAllocator.nextPowerOfTwo(usedCapacity + newPayload); assert newUsedCapacity >= 0; return newUsedCapacity <= currentCapacity ? currentCapacity : newUsedCapacity; }

Target:
private static int computeNewVectorCapacity(int usedCapacity, int newPayload, int currentCapacity) { int newUsedCapacity = BaseAllocator.nextPowerOfTwo(usedCapacity + newPayload); assert newUsedCapacity >= 0; return Math.max(currentCapacity, newUsedCapacity); }
Source:
private static void cleanShutdown() { log.info("CleanShutdown: Starting Cleanup."); shutdownServer = true; try { CorfuServerNode current = activeServer; if (current != null) { activeServer.close(); } } catch (Throwable th) { log.error("cleanShutdown: failed during shutdown", th); } // Flush the async appender before exiting to prevent the loss of logs LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.stop(); }

Target:
private static void cleanShutdown() { log.info("CleanShutdown: Starting Cleanup."); shutdownServer = true; try { CorfuServerNode current = activeServer; if (current != null) { current.close(); } } catch (Throwable th) { log.error("cleanShutdown: failed during shutdown", th); } // Flush the async appender before exiting to prevent the loss of logs LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.stop(); }
Source:
public void preInit(FMLPreInitializationEvent event) { Log.setModLog(event.getModLog()); configDir = new File(event.getModConfigurationDirectory(), "antiqueatlas"); configDir.mkdir(); extTileIdMap = ExtTileIdMap.instance(); extTileConfig = new ExtTileConfig(new File(configDir, "tileids.json")); extTileConfig.load(extTileIdMap); // Assign default values AFTER the config file loads, so that the old saved values are kept: registerVanillaCustomTiles(); checkSaveConfig(); }

Target:
public void preInit(FMLPreInitializationEvent event) { configDir = new File(event.getModConfigurationDirectory(), "antiqueatlas"); configDir.mkdir(); extTileIdMap = ExtTileIdMap.instance(); extTileConfig = new ExtTileConfig(new File(configDir, "tileids.json")); extTileConfig.load(extTileIdMap); // Assign default values AFTER the config file loads, so that the old saved values are kept: registerVanillaCustomTiles(); checkSaveConfig(); }
Source:
public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.apache.jasper.compiler.JspConfig", classLoader)) { try { String resourceName = getResourceName(view, environment); if (resourceLoader.getResource(resourceName).exists()) { return true; } return new File("src/main/webapp", resourceName).exists(); } catch (AccessControlException ex) { return false; } } return false; }

Target:
public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.apache.jasper.compiler.JspConfig", classLoader)) { String resourceName = getResourceName(view, environment); if (resourceLoader.getResource(resourceName).exists()) { return true; } try { return new File("src/main/webapp", resourceName).exists(); } catch (AccessControlException ex) { } } return false; }
Source:
private static Throwable getConfigFailureException(ITestContext context) { Throwable t = null; for (IInvokedMethod method : context.getSuite().getAllInvokedMethods()) { ITestNGMethod m = method.getTestMethod(); if (m.isBeforeSuiteConfiguration() && (!method.getTestResult().isSuccess())) { t = method.getTestResult().getThrowable(); break; } } return t; }

Target:
private static Throwable getConfigFailureException(ITestContext context) { for (IInvokedMethod method : context.getSuite().getAllInvokedMethods()) { ITestNGMethod m = method.getTestMethod(); if (m.isBeforeSuiteConfiguration() && (!method.getTestResult().isSuccess())) { return method.getTestResult().getThrowable(); } } return null; }
Source:
@Override protected Pair<Recipients, Boolean> doInBackground(Recipients... recipients) { Capability textCapability = DirectoryHelper.getUserCapabilities(context, recipients[0]).getTextCapability(); return new Pair<>(recipients[0], textCapability == Capability.SUPPORTED); }

Target:
protected Pair<Recipients, Boolean> doInBackground(Recipients... recipients) { Capability textCapability = DirectoryHelper.getUserCapabilities(context, recipients[0]).getTextCapability(); return new Pair<>(recipients[0], textCapability == Capability.SUPPORTED); }
Source:
public static DateTime setBeginValidTime(DateTime beginValidTimeArg, DateTime issueInstant) { DateTime beginValidTime = beginValidTimeArg; final DateTime now = new DateTime(); if (beginValidTime == null || beginValidTime.isAfter(now)) { beginValidTime = now; } // If provided time is after the given issue instant, // modify it to include the issue instant if (beginValidTime.isAfter(issueInstant)) { if (issueInstant.isAfter(now)) { beginValidTime = now; } } else { beginValidTime = issueInstant; } return beginValidTime; }

Target:
private static DateTime setBeginValidTime(DateTime beginValidTimeArg, DateTime issueInstant) { DateTime beginValidTime = beginValidTimeArg; final DateTime now = new DateTime(); if (beginValidTime == null || beginValidTime.isAfter(now)) { beginValidTime = now; } // If provided time is after the given issue instant, // modify it to include the issue instant if (beginValidTime.isAfter(issueInstant)) { if (issueInstant.isAfter(now)) { beginValidTime = now; } } else { beginValidTime = issueInstant; } return beginValidTime; }
Source:
public static void setupSystemProperties() { int freePort = TestUtilGit.findFreePort(); System.setProperty("org.uberfire.nio.git.daemon.port", String.valueOf(freePort)); logger.info("Git port used:{}", freePort); //These are not needed for the tests System.setProperty("org.uberfire.nio.git.daemon.enabled", "false"); System.setProperty("org.uberfire.nio.git.ssh.enabled", "false"); System.setProperty("org.uberfire.sys.repo.monitor.disabled", "true"); }

Target:
public static void setupSystemProperties() { //These are not needed for the tests System.setProperty("org.uberfire.nio.git.daemon.enabled", "false"); System.setProperty("org.uberfire.nio.git.ssh.enabled", "false"); System.setProperty("org.uberfire.sys.repo.monitor.disabled", "true"); }
Source:
private void buildErrataDetailPanel() { errataDetailPanel.clear(); errataDetailFormPanel = new GeneralFormPanel(); errataTitle = new Span(); errataTitle.setStyleName(style.errataTitleLabel()); FlowPanel errataTitlePanel = new FlowPanel(); errataTitlePanel.setStyleName(style.errataTitlePanel()); errataTitlePanel.add(errataTitle); errataDetailPanel.add(errataTitlePanel); errataDetailPanel.setStyleName("testtest"); //$NON-NLS-1$ errataDetailPanel.add(errataDetailFormPanel); }

Target:
private void buildErrataDetailPanel() { errataDetailPanel.clear(); errataDetailFormPanel = new GeneralFormPanel(); errataTitle = new Span(); errataTitle.setStyleName(style.errataTitleLabel()); FlowPanel errataTitlePanel = new FlowPanel(); errataTitlePanel.setStyleName(style.errataTitlePanel()); errataTitlePanel.add(errataTitle); errataDetailPanel.add(errataTitlePanel); errataDetailPanel.add(errataDetailFormPanel); }
Source:
public static void setup() throws Exception { assumeTrue("Skipping tests since Hive supports only JDK 8.", HiveTestUtilities.supportedJavaVersion()); startMiniDfsCluster(TestSqlStdBasedAuthorization.class.getSimpleName()); prepHiveConfAndData(); setSqlStdBasedAuthorizationInHiveConf(); startHiveMetaStore(); startDrillCluster(true); addHiveStoragePlugin(getHivePluginConfig()); addMiniDfsBasedStorage(new HashMap<>()); generateTestData(); }

Target:
public static void setup() throws Exception { startMiniDfsCluster(TestSqlStdBasedAuthorization.class.getSimpleName()); prepHiveConfAndData(); setSqlStdBasedAuthorizationInHiveConf(); startHiveMetaStore(); startDrillCluster(true); addHiveStoragePlugin(getHivePluginConfig()); addMiniDfsBasedStorage(new HashMap<>()); generateTestData(); }
Source:
public FeatureTypeStyle transform(MBStyle styleContext, Double minScaleDenominator, Double maxScaleDenominator) { // Would prefer to accept zoom levels here (less concepts in our API) // If we accept zoom levels we may be able to reduce, and return a list of FeatureTypeStyles // (with the understanding that the list may be empty if the MBLayer does not contribute any content // at a specific zoom level range) FeatureTypeStyle style = transform(styleContext); for (Rule rule : style.rules()) { if (minScaleDenominator != null) { rule.setMinScaleDenominator(minScaleDenominator); } if (maxScaleDenominator != null) { rule.setMaxScaleDenominator(maxScaleDenominator); } } return style; }

Target:
public FeatureTypeStyle transform(MBStyle styleContext, Double minScaleDenominator, Double maxScaleDenominator) { // Would prefer to accept zoom levels here (less concepts in our API) // If we accept zoom levels we may be able to reduce, and return a list of FeatureTypeStyles // (with the understanding that the list may be empty if the MBLayer does not contribute any content // at a specific zoom level range) FeatureTypeStyle style = transform(styleContext); if (style == null) { return null; } for (Rule rule : style.rules()) { if (minScaleDenominator != null) { rule.setMinScaleDenominator(minScaleDenominator); } if (maxScaleDenominator != null) { rule.setMaxScaleDenominator(maxScaleDenominator); } } return style; }
Source:
public Optional<SessionStore<J2EContext>> buildFromTrackableSession(final J2EContext context, final Object trackableSession) { return trackableSession == null ? Optional.empty() : Optional.of(new J2EProvidedSessionStore((HttpSession) trackableSession)); }

Target:
public Optional<SessionStore<J2EContext>> buildFromTrackableSession(final J2EContext context, final Object trackableSession) { return trackableSession != null ? Optional.of(new J2EProvidedSessionStore((HttpSession) trackableSession)) : Optional.empty(); }
Source:
public static void assertValidSubmodulePath(String path) throws SubmoduleValidationException { if (path.startsWith("-")) { //$NON-NLS-1$ throw new SubmoduleValidationException( MessageFormat.format( JGitText.get().submodulePathInvalid, path), ObjectChecker.ErrorType.GITMODULES_PATH); } }

Target:
public static void assertValidSubmodulePath(String path) throws SubmoduleValidationException { if (path.startsWith("-")) { //$NON-NLS-1$ throw new SubmoduleValidationException( MessageFormat.format( JGitText.get().submodulePathInvalid, path), GITMODULES_PATH); } }
Source:
public String getMessage() { String ret = super.getMessage(); if (pql.isPresent()) { ret += " with pql \"" + pql.get() + "\""; } return ret; }

Target:
public String getMessage() { String message = super.getMessage(); if (pql.isPresent()) { message += " with pql \"" + pql.get() + "\""; } return message; }
Source:
protected Cause createUpstreamCause(Run<?, ?> build) { if(Jenkins.getInstance().getPlugin("promoted-builds") != null) { // Test only when promoted-builds is installed. if(build instanceof Promotion) { Promotion promotion = (Promotion)build; // This cannot be done for PromotionCause#PromotionCause is in a package scope. // return new PromotionCause(build, promotion.getTarget()); return new UpstreamCause((Run<?,?>)promotion.getTarget()); } } return new UpstreamCause((Run) build); }

Target:
protected Cause createUpstreamCause(Run<?, ?> build) { if(Jenkins.getInstance().getPlugin("promoted-builds") != null) { // Test only when promoted-builds is installed. if(build instanceof Promotion) { Promotion promotion = (Promotion)build; // This cannot be done for PromotionCause#PromotionCause is in a package scope. // return new PromotionCause(build, promotion.getTarget()); return new UpstreamCause((Run<?,?>)promotion.getTarget()); } } return new UpstreamCause(build); }
Source:
private Set<SupportedAdditionalClusterFeature> getAdditionalClusterFeaturesAdded() { // Lets not modify the existing collection. Hence creating a new hashset. Set<SupportedAdditionalClusterFeature> featuresSupported = new HashSet<SupportedAdditionalClusterFeature>(getVdsGroup().getAddtionalFeaturesSupported()); featuresSupported.removeAll(clusterFeatureDao.getSupportedFeaturesByClusterId(getVdsGroup().getId())); return featuresSupported; }

Target:
private Set<SupportedAdditionalClusterFeature> getAdditionalClusterFeaturesAdded() { // Lets not modify the existing collection. Hence creating a new hashset. Set<SupportedAdditionalClusterFeature> featuresSupported = new HashSet<>(getVdsGroup().getAddtionalFeaturesSupported()); featuresSupported.removeAll(clusterFeatureDao.getSupportedFeaturesByClusterId(getVdsGroup().getId())); return featuresSupported; }
Source:
public boolean hasNext() { // If we do not have the next element pipelined, go ahead and fetch it. if (next == null) { // If the iterator is valid, this means that the next entry exists. checkInvariants(); if (iterator.isValid()) { // Go ahead and cache that entry. next = new AbstractMap.SimpleEntry( serializer.deserialize(Unpooled.wrappedBuffer(iterator.key()), corfuRuntime), serializer.deserialize(Unpooled.wrappedBuffer(iterator.value()), corfuRuntime)); // Advance the underlying iterator. iterator.next(); } else { // If there is no more elements to consume, we should release the resources. iterator.close(); } } return next != null; }

Target:
public boolean hasNext() { // If we have the next element pipelined, go ahead and return true. if (next != null) { return true; } // If the iterator is valid, this means that the next entry exists. checkInvariants(); if (iterator.isValid()) { // Go ahead and cache that entry. next = new AbstractMap.SimpleEntry( serializer.deserialize(Unpooled.wrappedBuffer(iterator.key()), corfuRuntime), serializer.deserialize(Unpooled.wrappedBuffer(iterator.value()), corfuRuntime)); // Advance the underlying iterator. iterator.next(); } else { // If there is no more elements to consume, we should release the resources. iterator.close(); } return next != null; }
Source:
public ItemAshenMask(ArmorMaterial material, int renderIndex, EntityEquipmentSlot slot, AshenMasks maskType) { super(material, renderIndex, slot); setHasSubtypes(true); this.maxStackSize = 64; this.maskType = maskType; ItemRegistry.maskMap.put(maskType, this); }

Target:
public ItemAshenMask(ArmorMaterial material, int renderIndex, EntityEquipmentSlot slot, AshenMasks maskType) { super(material, renderIndex, slot); this.maskType = maskType; ItemRegistry.maskMap.put(maskType, this); }
Source:
public void dispose() { //Remove all messages from the queue this.mHandler.removeCallbacksAndMessages(null); this.mHandler = null; this.mPhone = null; }

Target:
public void dispose() { }
Source:
public void onPageScrolled(int i, float v, int i2) { if (pager.getCurrentItem() != 0) { speakerbox.stop(); } if (pager.getCurrentItem() == pagerPositionWhenPaused) { resume.setVisibility(View.GONE); getView().findViewById(R.id.routes).setBackgroundColor(act.getBaseContext() .getResources().getColor(R.color.transparent_white)); } }

Target:
public void onPageScrolled(int i, float v, int i2) { if (pager.getCurrentItem() != 0) { speakerbox.stop(); } if (pager.getCurrentItem() == pagerPositionWhenPaused) { resume.setVisibility(View.GONE); } }
Source:
public XWikiAttachment set(XWikiAttachment attachment) { XWikiAttachment put = map.put(attachment.getFilename(), attachment); if (put == null || !put.equals(attachment)) { added(attachment); updatedMap(); } return put; }

Target:
public XWikiAttachment set(XWikiAttachment attachment) { XWikiAttachment put = map.put(attachment.getFilename(), attachment); if (put != attachment) { added(attachment); updatedMap(); } return put; }
Source:
private void printInfo(String sizeMessage, String inAlluxioMessage, String inMemMessage, String path) { System.out.println(inMemMessage.equals("") ? String.format(SHORT_INFO_FORMAT, sizeMessage, inAlluxioMessage, path) : String.format(LONG_INFO_FORMAT, sizeMessage, inAlluxioMessage, inMemMessage, path)); }

Target:
private void printInfo(String sizeMessage, String inAlluxioMessage, String inMemMessage, String path) { System.out.println(inMemMessage.isEmpty() ? String.format(SHORT_INFO_FORMAT, sizeMessage, inAlluxioMessage, path) : String.format(LONG_INFO_FORMAT, sizeMessage, inAlluxioMessage, inMemMessage, path)); }
Source:
public void tearDown() { // Destroy JMX beans created during testing. MetricsService metricsService = new MetricsService(nodeEngineMock, () -> metricsRegistry); metricsService.init(nodeEngineMock, new Properties()); metricsService.shutdown(true); JmxLeakHelper.checkJmxBeans(); // Stop executor service. if (executionService != null) { executionService.shutdown(); } }

Target:
public void tearDown() { // Destroy JMX beans created during testing. if (metricsService != null) { metricsService.shutdown(true); metricsService = null; } JmxLeakHelper.checkJmxBeans(); // Stop executor service. if (executionService != null) { executionService.shutdown(); } }
Source:
public void scanForRepoChanges() throws IOException { refs.refresh(); getAllRefs(); // This will look for changes to refs if (!isBare()) getIndex(); // This will detect changes in the index }

Target:
public void scanForRepoChanges() throws IOException { getAllRefs(); // This will look for changes to refs if (!isBare()) getIndex(); // This will detect changes in the index }
Source:
public Iterator<ImageTypeSpecifier> getImageTypes(int pImageIndex) throws IOException { checkBounds(pImageIndex); // TODO: Better implementation, include INT_RGB types for 3BYTE_BGR and 4BYTE_ABGR for INT_ARGB return Collections.singletonList(getRawImageType(pImageIndex)).iterator(); }

Target:
public Iterator<ImageTypeSpecifier> getImageTypes(int pImageIndex) throws IOException { checkBounds(pImageIndex); // TODO: Better implementation, include INT_RGB types for 3BYTE_BGR and 4BYTE_ABGR for INT_ARGB return Arrays.asList(getRawImageType(pImageIndex)).iterator(); }
Source:
public static SelectorHandler getHandler(final String selectorStr) { if (!selectorStr.isEmpty()) for (final Entry<String, SelectorHandler> handler : selectorHandlers.subMap(selectorStr, true, selectorStr.substring(0, 1), true).entrySet()) if (selectorStr.startsWith(handler.getKey())) return handler.getValue(); return vanillaHandler; }

Target:
public static SelectorHandler getHandler(final String selectorStr) { if (!selectorStr.isEmpty()) { for (final Entry<String, SelectorHandler> handler : selectorHandlers.subMap(selectorStr, true, selectorStr.substring(0, 1), true).entrySet()) { if (selectorStr.startsWith(handler.getKey())) { return handler.getValue(); } } } return vanillaHandler; }
Source:
public void testDefaultConfig() throws Exception { Files.write(springTestFile.toPath(), "modification".getBytes(), StandardOpenOption.SYNC); // Adding few millis to avoid fleaky tests // The file hasher could sometimes evaluate these two changes as duplicate, as the second modification of file could be done before hashing is done Thread.sleep(50); Files.write(springTestFile.toPath(), "modification 2".getBytes(), StandardOpenOption.SYNC); MockEndpoint mock = getMockEndpoint("mock:springTest"); mock.setExpectedCount(1); // The same with testCustomHasher, that second MODIFY event is discarded mock.setResultWaitTime(1000); mock.assertIsSatisfied(); }

Target:
public void testDefaultConfig() throws Exception { Files.write(springTestFile.toPath(), "modification".getBytes(), StandardOpenOption.SYNC); // Adding few millis to avoid fleaky tests // The file hasher could sometimes evaluate these two changes as duplicate, as the second modification of file could be done before hashing is done Thread.sleep(50); Files.write(springTestFile.toPath(), "modification 2".getBytes(), StandardOpenOption.SYNC); MockEndpoint mock = getMockEndpoint("mock:springTest"); mock.setExpectedCount(2); // two MODIFY events mock.setResultWaitTime(1000); mock.assertIsSatisfied(); }
Source:
private boolean startsOrEndsWithWhitespace(String value) { boolean startsOrEndsWithWhitespace = false; if (value != null && StringUtils.isNotBlank(value)) { int lastIndex = value.length() - 1; if (Character.isSpaceChar(value.charAt(0))) { startsOrEndsWithWhitespace = true; } else if (Character.isSpaceChar(value.charAt(lastIndex))) { startsOrEndsWithWhitespace = true; } } else { startsOrEndsWithWhitespace = false; } return startsOrEndsWithWhitespace; }

Target:
private boolean startsOrEndsWithWhitespace(String value) { return (StringUtils.isNotBlank(value) && (Character.isSpaceChar(value.charAt(0)) || Character.isSpaceChar(value.charAt(value.length() -1)))); }
Source:
private void updateData(OCShare share) { // Update DB with the response share.setPath(mPath); if (mPath.endsWith(FileUtils.PATH_SEPARATOR)) { share.setIsFolder(true); } else { share.setIsFolder(false); } share.setPermissions(READ_ONLY); getStorageManager().saveShare(share); // Update OCFile with data from share: ShareByLink and publicLink OCFile file = getStorageManager().getFileByPath(mPath); if (file!=null) { file.setShareWithSharee(true); // TODO - this should be done by the FileContentProvider, as part of getStorageManager().saveShare(share) getStorageManager().saveFile(file); } }

Target:
private void updateData(OCShare share) { // Update DB with the response share.setPath(mPath); share.setIsFolder(mPath.endsWith(FileUtils.PATH_SEPARATOR)); share.setPermissions(READ_ONLY); getStorageManager().saveShare(share); // Update OCFile with data from share: ShareByLink and publicLink OCFile file = getStorageManager().getFileByPath(mPath); if (file!=null) { file.setShareWithSharee(true); // TODO - this should be done by the FileContentProvider, as part of getStorageManager().saveShare(share) getStorageManager().saveFile(file); } }