auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START private static boolean monoNativeFailure(Either<Utils.CommandResult> result) { END if (result == null || !result.isSuccess()) { return true; } else { Utils.CommandResult commandResult = result.get(); return monoNativeFailure(commandResult.output) || monoNativeFailure(commandResult.error); } } maybe check for start of file or newline also?

Target:
static boolean monoNativeFailure(Either<Utils.CommandResult> result) { if (result == null || !result.isSuccess()) { return true; } else { Utils.CommandResult commandResult = result.get(); return monoNativeFailure(commandResult.output) || monoNativeFailure(commandResult.error); } }
Source:
private void removeAppBar() { DWORD dwABM = new DWORD(); APPBARDATA ABData = new APPBARDATA.ByReference(); ABData.cbSize.setValue( ABData.size() ); dwABM.setValue(ShellAPI.ABM_REMOVE); UINT_PTR result = Shell32.INSTANCE.SHAppBarMessage( dwABM, ABData); START assertNotNull(result ); END } Another extra space, can you plese cleanup all these similar things? There're a few others, some functions have spaces in parameters, some don't like `queryPos( APPBARDATA ABData )` vs. `dwABM.setValue(ShellAPI.ABM_QUERYPOS);`. Sorry to be a pest, just looks messy and inconsistent.

Target:
private void removeAppBar() { APPBARDATA data = new APPBARDATA.ByReference(); data.cbSize.setValue(data.size()); UINT_PTR result = Shell32.INSTANCE.SHAppBarMessage(new DWORD(ShellAPI.ABM_REMOVE), data); assertNotNull(result); }
Source:
public boolean couldMatch(ScriptPath path) { START return (path.eventLower.startsWith("mythicmob") && (path.eventArgLowerAt(2).equals("spawns"))); END } stray parens Also, use the standard couldMatch format used through Denizen, not this weird inline thing.

Target:
public boolean couldMatch(ScriptPath path) { if (!path.eventLower.startsWith("mythicmob")) { return false; } if (!path.eventArgLowerAt(2).equals("spawns")) { return false; } return true; }
Source:
void init() { START controllerHomeDir = resolveControllerHomeDir(); END this.initAccessOfDirectories(); this.initAccessOfHosts(); } Why does it resolve controller home? is it better to name it with HomeDir? It's because this class not only called from controller but agent.

Target:
void init() { this.initAccessOfDirectories(); this.initAccessOfHosts(); }
Source:
protected Sequence getServicesSequence(DsfSession session, ILaunch launch, IProgressMonitor rm) { if (launch instanceof GdbLaunch) { return new ServicesLaunchSequence(session, (GdbLaunch)launch, rm); } return null; START } END It is always expected that launch would be an instance of GdbLaunch, I don't think the check is required.

Target:
protected Sequence getServicesSequence(DsfSession session, ILaunch launch, IProgressMonitor rm) { return new ServicesLaunchSequence(session, (GdbLaunch)launch, rm); }
Source:
START public AdvanceResult advanceNursery(final AdvancingNursery advanceInfo, final Workbook workbook) throws RuleException, MiddlewareQueryException, FieldbookException { END return this.namingConventionService.advanceNursery(advanceInfo, workbook); } `MiddlewareQueryException` is now a run time exception so it is not required to be part of the method signature. Not invalid to have it in signature, but Sonar will report it as a _Major_ category violation.

Target:
public AdvanceResult advanceNursery(final AdvancingNursery advanceInfo, final Workbook workbook) throws RuleException, FieldbookException { return this.namingConventionService.advanceNursery(advanceInfo, workbook); }
Source:
public org.ovirt.engine.api.model.Cluster update(org.ovirt.engine.api.model.Cluster incoming) { //TODO MM: Dear code reviewer! I'm not sure if this is really cool. I'd assume mapping should happen in mappers, but their powers are limited. Please advise. MacPool macPool = incoming.getMacPool(); START macPool.setId(MacPoolIdByIdOrName.get(macPool.getId(), END macPool.getName(), this)); return performUpdate(incoming, new QueryIdResolver<>(VdcQueryType.GetClusterById, IdQueryParameters.class), VdcActionType.UpdateCluster, new UpdateParametersProvider()); } Please make it non-static, similar to what is done with ManagementNetworkFinder

Target:
public org.ovirt.engine.api.model.Cluster update(org.ovirt.engine.api.model.Cluster incoming) { return performUpdate(incoming, new QueryIdResolver<>(VdcQueryType.GetClusterById, IdQueryParameters.class), VdcActionType.UpdateCluster, new UpdateParametersProvider(this)); }
Source:
protected @NonNull TmfViewer createLeftChildViewer(@Nullable Composite parent) START { String analysisId = NonNullUtils.nullToEmptyString(getViewSite().getSecondaryId()); END return new AbstractSegmentStoreScatterChartTreeViewer(Objects.requireNonNull(parent)) { @Override protected @Nullable ISegmentStoreProvider getSegmentStoreProvider(ITmfTrace trace) { IAnalysisModule module = TmfTraceUtils.getAnalysisModuleOfClass(trace, IAnalysisModule.class, analysisId); if (module instanceof ISegmentStoreProvider) { return (ISegmentStoreProvider) module; } return null; } }; } handle this with an error log and returning null instead of a viewer? as the view won't work with an incorrect id?

Target:
protected @NonNull TmfViewer createLeftChildViewer(@Nullable Composite parent) { String analysisId = String.valueOf(getViewSite().getSecondaryId()); return new AbstractSegmentStoreScatterChartTreeViewer(Objects.requireNonNull(parent)) { @Override protected @Nullable ISegmentStoreProvider getSegmentStoreProvider(ITmfTrace trace) { IAnalysisModule module = TmfTraceUtils.getAnalysisModuleOfClass(trace, IAnalysisModule.class, analysisId); if (module instanceof ISegmentStoreProvider) { return (ISegmentStoreProvider) module; } return null; } }; }
Source:
public void testReservedSkippableBeforeStreamIdentifier() throws Exception { ByteBuf in = Unpooled.wrappedBuffer(new byte[] { -0x7f, 0x06, 0x00, 0x00, 's', 'n', 'e', 't', 't', 'y' }); START assertFalse(channel.writeInbound(in)); END } I think it makes more sense to omit this assert in the expected exception cases?

Target:
public void testReservedSkippableBeforeStreamIdentifier() throws Exception { ByteBuf in = Unpooled.wrappedBuffer(new byte[] { -0x7f, 0x06, 0x00, 0x00, 's', 'n', 'e', 't', 't', 'y' }); channel.writeInbound(in); }
Source:
public void set(String name, Property property) throws PropertyNotFoundException { Field field = getType().getField(name); if (field == null) { Property removedProperty = computeRemovedProperty(name); if (removedProperty != null) { removedProperty.set(name, property); } return; } START children.put(field.getName().getPrefixedName(), property); END setIsModified(); } In the `get` method which calls `getChild` we use `property.getName()` instead of `field.getName().getPrefixedName()` as the key in the `children` map. Can you make this consistent so that we're sure there's no discrepancy between prefixed/unprefixed?

Target:
public void set(String name, Property property) throws PropertyNotFoundException { Field field = getType().getField(name); if (field == null) { Property removedProperty = computeRemovedProperty(name); if (removedProperty != null) { removedProperty.set(name, property); } return; } children.put(property.getName(), property); setIsModified(); }
Source:
public int andCardinality(Container x) { if (this.getCardinality() == 0) return 0; else if (x.getCardinality() ==0) return 0; else { if (x instanceof ArrayContainer) START return and((ArrayContainer) x).getCardinality(); END else if (x instanceof BitmapContainer) return and((BitmapContainer) x).getCardinality(); return and((RunContainer) x).getCardinality(); } } `andCardinality(Container)` should be called here instead of `and(Container).getCardinality()`

Target:
public int andCardinality(Container x) { if (this.getCardinality() == 0) return 0; else if (x.getCardinality() == 0) return 0; else { if (x instanceof ArrayContainer) return andCardinality((ArrayContainer) x); else if (x instanceof BitmapContainer) return andCardinality((BitmapContainer) x); return andCardinality((RunContainer) x); } }
Source:
public Set<WorkerNetAddress> getWorkerAddresses() throws UnavailableException { if (mSafeModeManager.isInSafeMode()) { throw new UnavailableException(ExceptionMessage.MASTER_IN_SAFEMODE.getMessage()); } START Set<WorkerNetAddress> workerAddresses = new HashSet<>(); END for (MasterWorkerInfo worker : mWorkers) { // worker net address is unmodifiable after initialization, no locking is needed workerAddresses.add(worker.getWorkerAddress()); } return workerAddresses; } (nit) Initialize with initial capacity to be the number of workers.

Target:
public Set<WorkerNetAddress> getWorkerAddresses() throws UnavailableException { if (mSafeModeManager.isInSafeMode()) { throw new UnavailableException(ExceptionMessage.MASTER_IN_SAFEMODE.getMessage()); } Set<WorkerNetAddress> workerAddresses = new HashSet<>(mWorkers.size()); for (MasterWorkerInfo worker : mWorkers) { // worker net address is unmodifiable after initialization, no locking is needed workerAddresses.add(worker.getWorkerAddress()); } return workerAddresses; }
Source:
public void setUp() { params.put("CallSid", "CA1234567890ABCDE"); params.put("Caller", "+14158675309"); params.put("Digits", "1234"); params.put("From", "+14158675309"); params.put("To", "+18005551212"); START signature = "RSOYDt4T1cUTdK1PDd93/VVr8B8="; END } move this to where `signature` is declared, since it never changes?

Target:
public void setUp() { params.put("Digits", "1234"); params.put("CallSid", "CA1234567890ABCDE"); params.put("To", "+18005551212"); params.put("Caller", "+14158675309"); params.put("From", "+14158675309"); }
Source:
START public String getAttributeValue(@Nullable String name) { END return name; } public @Nullable String...

Target:
public @Nullable String getAttributeValue(@Nullable String name) { return name; }
Source:
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { for (Object cookie : cookiesToClear) { Cookie realCookie = null; START if (cookie instanceof String) { END realCookie = new Cookie((String) cookie, null); String cookiePath = request.getContextPath() + "/"; realCookie.setPath(cookiePath); realCookie.setMaxAge(0); }else if (cookie instanceof Cookie){ realCookie = (Cookie) cookie; } response.addCookie(realCookie); } } This logic will obviously need updated once we change `this.cookiesToClear`.

Target:
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { cookiesToClear.forEach( f -> response.addCookie(f.apply(request)) ); }
Source:
START private MethodHandles.Lookup getMethodHandleLookup(Class<?> endpointClass) throws InvalidWebSocketException END { return MethodHandles.publicLookup().in(endpointClass); } Can remove the throws `InvalidWebSocketException` now.

Target:
private MethodHandles.Lookup getMethodHandleLookup(Class<?> endpointClass) { return MethodHandles.publicLookup().in(endpointClass); }
Source:
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (maxConnections > 0) { if (numConnections.incrementAndGet() > maxConnections) { ctx.getChannel().close(); START numConnections.decrementAndGet(); END log.info("Accepted connection above limit ({}). Dropping.", maxConnections); } } super.channelOpen(ctx, e); } won't this be a double-decrement?

Target:
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (maxConnections > 0) { if (numConnections.incrementAndGet() > maxConnections) { ctx.getChannel().close(); // numConnections will be decremented in channelClosed log.info("Accepted connection above limit ({}). Dropping.", maxConnections); } } super.channelOpen(ctx, e); }
Source:
public Builder from(int ... nums) { START this.matchers.add((from, to, msg) -> Arrays.binarySearch(nums, from) >= 0); END return this; } this assumes the input is sorted, but the test case is what calls this; its very possible that the test defined them in non-sorted order

Target:
public Builder from(int... nums) { from = nums; return this; }
Source:
public B channel(Class<? extends C> channelClass) { ObjectUtil.checkNotNull(channelClass, "channelClass"); START return channelFactory(new ReflectiveChannelFactory<C>(channelClass)); END } @qeesung: nit you can merge the above 2 lines as `checkNotNull` returns `channelClass`.

Target:
public B channel(Class<? extends C> channelClass) { return channelFactory(new ReflectiveChannelFactory<C>( ObjectUtil.checkNotNull(channelClass, "channelClass") )); }
Source:
public void getActiveConditions_shouldGetActiveConditions() { List<Condition> activeConditions = conditionService.getActiveConditions(patientService.getPatient(2)); Condition firstActiveCondition = activeConditions.get(0); Condition secondActiveCondition = activeConditions.get(1); START String firstUUID = "2cc6880e-2c46-11e4-9138-a6c5e4d20fb7"; END String secondUUID = "2cc6880e-2c46-15e4-9038-a6c5e4d22fb7"; Assert.assertTrue(activeConditions.size() == 2); Assert.assertEquals(firstUUID,firstActiveCondition.getUuid()); Assert.assertEquals(secondUUID, secondActiveCondition.getUuid()); } For variables which you are using in one place, remove them and just use the actual value in that one place.

Target:
public void getActiveConditions_shouldGetActiveConditions() { List<Condition> activeConditions = conditionService.getActiveConditions(patientService.getPatient(2)); Assert.assertTrue(activeConditions.size() == 2); Assert.assertEquals("2cc6880e-2c46-11e4-9138-a6c5e4d20fb7",activeConditions.get(0).getUuid()); Assert.assertEquals("2cc6880e-2c46-15e4-9038-a6c5e4d22fb7", activeConditions.get(1).getUuid()); }
Source:
public synchronized Inode<?> getInodeOrNull() { if (!fullPathExists()) { return null; } START List<Inode<?>> inodeList = Lists.newArrayList(mLockList.getInodes()); END return inodeList.get(inodeList.size() - 1); } why is there a `newArrayList`?

Target:
public synchronized Inode<?> getInodeOrNull() { if (!fullPathExists()) { return null; } List<Inode<?>> inodeList = mLockList.getInodes(); return inodeList.get(inodeList.size() - 1); }
Source:
private static <T> Set<T> findDuplicates(Collection<T> list) { Set<T> duplicates = new HashSet<>(); Set<T> uniques = new HashSet<>(); START for(T t : list) { END if(!uniques.add(t)) { duplicates.add(t); } } return duplicates; } why not `list.stream().forEach`?

Target:
private static <T> Set<T> findDuplicates(Collection<T> list) { Set<T> duplicates = new HashSet<>(); Set<T> uniques = new HashSet<>(); list.stream().forEach(t -> { if (!uniques.add(t)) { duplicates.add(t); } }); return duplicates; }
Source:
public boolean next() throws IOException { for (;;) { LogQueueEntry t = queue.poll(); if (t == null) { return false; } refName = t.lc.getRefName(); updateIndex = t.lc.getUpdateIndex(); entry = t.lc.getReflogEntry(); boolean include = includeDeletes || entry != null; skipShadowed(refName, updateIndex); add(t); START if (include) { return true; } return true; END } } This isn't right.

Target:
public boolean next() throws IOException { for (;;) { LogQueueEntry t = queue.poll(); if (t == null) { return false; } refName = t.lc.getRefName(); updateIndex = t.lc.getUpdateIndex(); entry = t.lc.getReflogEntry(); boolean include = includeDeletes || entry != null; skipShadowed(refName, updateIndex); add(t); if (include) { return true; } } }
Source:
void remove(MessageGroup group) { Object correlationKey = group.getGroupId(); START if (this.groupIds.contains(correlationKey)) { END this.messageStore.removeMessageGroup(correlationKey); this.groupIds.remove(correlationKey); } } That's not logic for this method. If we are here, we have to be already sure that it is our own group. The real problem is definitely in the `ForceReleaseMessageGroupProcessor` implementation. We have to check for its presence there. All other logic should not be affected. Please, make this `remove()` method `protected`.

Target:
protected void remove(MessageGroup group) { Object correlationKey = group.getGroupId(); this.messageStore.removeMessageGroup(correlationKey); this.groupIds.remove(group.getGroupId()); }
Source:
public void sendOffsetsToTransaction(Map<TopicPartition, OffsetAndMetadata> offsets, String consumerGroupId) throws ProducerFencedException { START if (!cachedGroupMetadata.groupId().equals(consumerGroupId)) { END // Generally this logic should only be triggered once during first call. log.warn("Cached consumer groupId changed from to {}. If the old group id is not empty, this indicates an abuse of this API", cachedGroupMetadata.groupId(), consumerGroupId); cachedGroupMetadata = new ConsumerGroupMetadata(consumerGroupId, JoinGroupRequest.UNKNOWN_GENERATION_ID, JoinGroupRequest.UNKNOWN_MEMBER_ID, Optional.empty()); } sendOffsetsToTransactionInternal(offsets, cachedGroupMetadata, false); } Hmm, this feels like premature optimization. The offsets map is more likely to be a problem. Also, I'm not sure we should restrict the usage. It is possible today to send offsets for multiple groups. Is there a good reason to restrict this even if it doesn't make sense in streams?

Target:
public void sendOffsetsToTransaction(Map<TopicPartition, OffsetAndMetadata> offsets, String consumerGroupId) throws ProducerFencedException { sendOffsetsToTransaction(offsets, new ConsumerGroupMetadata(consumerGroupId)); }
Source:
public boolean cancel(final Exception rootReason) { if (transitionCancel(rootReason)) { final Exception reason = new CancellationException(rootReason); try { traceFailure(reason); } catch (Throwable ex) { START LOGGER.warn("Exception thrown in logging trace for failure!", ex); END } getSettableDelegate().fail(reason); return true; } return false; } The issue we found was when the original `reason` could not be logged due to an error in its `toString`. Do we have any concern that logging the _new_ error might have the same issue? Would it be better to have two stages to this? 1. Catch the logging error, then try to log that error. 2. Catch _that_ error if it happens, and log a generic, static message.

Target:
public boolean cancel(final Exception rootReason) { if (transitionCancel(rootReason)) { final Exception reason = new CancellationException(rootReason); try { traceFailure(reason); } catch (Throwable ex) { LOGGER.warn("Exception thrown in logging trace for failure!", ex); } finally { // guard any exception that may throw from catch block getSettableDelegate().fail(reason); } return true; } return false; }
Source:
START int allVersionsCombined() END { return formatIdentifier >>> SHIFT_FORMAT_IDENTIFIER | formatVersion >>> SHIFT_FORMAT_VERSION; } Can be private

Target:
private int allVersionsCombined() { return formatIdentifier >>> SHIFT_FORMAT_IDENTIFIER | formatVersion >>> SHIFT_FORMAT_VERSION; }
Source:
START protected void writeJDBCStoreConnection(XMLExtendedStreamWriter writer, SimpleConnectionFactoryConfiguration configuration) throws XMLStreamException { END writer.writeStartElement(Element.SIMPLE_CONNECTION); writeOptional(writer, Attribute.CONNECTION_URL, configuration.connectionUrl()); writeOptional(writer, Attribute.DRIVER_CLASS, configuration.driverClass()); writeOptional(writer, Attribute.USERNAME, configuration.username()); writeOptional(writer, Attribute.PASSWORD, configuration.password()); writer.writeEndElement(); } the connection configuration is never serialized.

Target:
private void writeJDBCStoreConnection(XMLExtendedStreamWriter writer, SimpleConnectionFactoryConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.SIMPLE_CONNECTION); writeOptional(writer, Attribute.CONNECTION_URL, configuration.connectionUrl()); writeOptional(writer, Attribute.DRIVER_CLASS, configuration.driverClass()); writeOptional(writer, Attribute.USERNAME, configuration.username()); writeOptional(writer, Attribute.PASSWORD, configuration.password()); writer.writeEndElement(); }
Source:
START static ByteBuf copyData(ByteBufList list) { END ByteBuf buf = Unpooled.buffer(list.readableBytes()); for (int i = 0; i < list.size(); i++) { buf.writeBytes(list.getBuffer(i).slice()); } return buf; } "public" or "private" ?

Target:
private static ByteBuf copyData(ByteBufList list) { ByteBuf buf = Unpooled.buffer(list.readableBytes()); for (int i = 0; i < list.size(); i++) { buf.writeBytes(list.getBuffer(i).slice()); } return buf; }
Source:
private String getXMI_ID(final EObject eobject) { if (eobject.eResource() instanceof XMIResource) { return ((XMIResource) eobject.eResource()).getID(eobject); } START ; END return null; } Useless

Target:
private String getXMI_ID(final EObject eobject) { if (eobject.eResource() instanceof XMIResource) { return ((XMIResource) eobject.eResource()).getID(eobject); } return null; }
Source:
START @Override public float getPressure () { END return 0; } Can you format these overrides?

Target:
public float getPressure () { return 0; }
Source:
private boolean checkForJournalFlush() { // System.err.printf("checkForJournalFlush: queue size=%d; journal size = %d\n", queue.size(), journal.size()) ; // System.err.printf("checkForJournalFlush: QueueBatchSize=%d; MaxQueueThreshold=%d; JournalThresholdSize=%d\n", // QueueBatchSize, MaxQueueThreshold, JournalThresholdSize) ; START if ( QueueBatchSize == 0 ) END return true ; if ( queue.size() >= QueueBatchSize ) // Based on number of queued commits // The MaxQueueThreshold is handled in processDelayedReplayQueue. return true ; boolean journalSizeFlush = (JournalThresholdSize > 0 && journal.size() > JournalThresholdSize ) ; if ( journalSizeFlush ) // JENA-1222 // Based on Journal file growing large in terms of bytes return true ; // No test for excessive queue length (MaxQueueThreshold). // That happens in notifyCommit (writer exit). return false ; } I'm probably missing something, but it seems like this is part of the next case (isn't `queue.size() >= 0` an invariant?). Is this called out just to emphasize that setting `0` => "no queuing"?

Target:
private boolean checkForJournalFlush() { if ( queue.size() >= QueueBatchSize ) return true ; boolean journalSizeFlush = (JournalThresholdSize > 0 && journal.size() > JournalThresholdSize ) ; if ( journalSizeFlush ) // JENA-1222 // Based on Journal file growing large in terms of bytes return true ; // No test here for excessive queue length (MaxQueueThreshold). return false ; }
Source:
private ProjectState newProjectState(ProjectConfig local) { START PrologEnvironment.Factory envFactory = null; GitRepositoryManager gitMgr = null; ProjectControl.AssistedFactory projectControlFactory = null; RulesCache rulesCache = null; SitePaths sitePaths = null; List<CommentLinkInfo> commentLinks = null; all.put(local.getProject().getNameKey(), new ProjectState(sitePaths, projectCache, allProjectsName, projectControlFactory, envFactory, gitMgr, rulesCache, commentLinks, local)); END return all.get(local.getProject().getNameKey()); } Use add(ProjectConfig) method here instead of repeating the same code?

Target:
private ProjectState newProjectState(ProjectConfig local) { add(local); return all.get(local.getProject().getNameKey()); }
Source:
public static Collection<PersonaAccount> getPersonaAccountsForAccount(long accountId) throws CentralRepoException { String queryClause = PERSONA_ACCOUNTS_QUERY_CALUSE + " WHERE persona_accounts.account_id = " + accountId START + "AND p.status_id != " + Persona.PersonaStatus.DELETED.getStatusId(); END CentralRepository cr = CentralRepository.getInstance(); if (cr != null) { String queryClause = PERSONA_ACCOUNTS_QUERY_CALUSE + " WHERE persona_accounts.account_id = " + accountId; PersonaAccountsQueryCallback queryCallback = new PersonaAccountsQueryCallback(); cr.executeSelectSQL(queryClause, queryCallback); return queryCallback.getPersonaAccountsList(); } return new ArrayList<>(); } There's a re-declaration error here, that got fixed on the parent branch. That needs to get merged in here.

Target:
public static Collection<PersonaAccount> getPersonaAccountsForAccount(long accountId) throws CentralRepoException { String queryClause = PERSONA_ACCOUNTS_QUERY_CALUSE + " WHERE persona_accounts.account_id = " + accountId + "AND p.status_id != " + Persona.PersonaStatus.DELETED.getStatusId(); CentralRepository cr = CentralRepository.getInstance(); if (cr != null) { PersonaAccountsQueryCallback queryCallback = new PersonaAccountsQueryCallback(); cr.executeSelectSQL(queryClause, queryCallback); return queryCallback.getPersonaAccountsList(); } return new ArrayList<>(); }
Source:
public boolean hasMultipleValues(final String dimension) { if (isVirtualColumn(dimension)) { return virtualColumns.getVirtualColumn(dimension).capabilities(dimension).hasMultipleValues(); } final Column column = index.getColumn(dimension); START if (column == null || !columnSupportsFiltering(column)) { END return false; } else { return column.getCapabilities().hasMultipleValues(); } } The same question, how "column supports filtering" relates to "has multiple values"?

Target:
public boolean hasMultipleValues(final String dimension) { if (isVirtualColumn(dimension)) { return virtualColumns.getVirtualColumn(dimension).capabilities(dimension).hasMultipleValues(); } final Column column = index.getColumn(dimension); return column != null && column.getCapabilities().hasMultipleValues(); }
Source:
public void resumeNode(String id) { START waitServerUntilAvailable.apply(getNode(id)); END api.serverApi().updateStatus(id, Server.UpdateStatus.create(Types.ServerAction.POWER_ON, Types.ServerActionMethod.HARDWARE)); } This won't work? You wait until the node is powered on when you want to resume it. This will take forever.

Target:
public void resumeNode(String id) { api.serverApi().updateStatus(id, Server.UpdateStatus.create(Types.ServerAction.POWER_ON, Types.ServerActionMethod.HARDWARE)); }
Source:
public IStyledLabelProvider[] getLabelProviders() { START if (fLabelProviders == null) { END fLabelProviders = CHEProviderSettings.getCCallHierarchyLabelProviders(); } return fLabelProviders; } either make this a get method that returns the result, or have it be a "load" method. Having it do both is unexpected (same for above method)

Target:
public IStyledLabelProvider[] getLabelProviders() { return fLabelProviders; }
Source:
public void registerOperations(ManagementResourceRegistration resourceRegistration) { if (showResources) { resourceRegistration.registerOperationHandler(ShowJaxrsResourcesHandler.DEFINITION, new ShowJaxrsResourcesHandler()); } else { resourceRegistration.registerOperationHandler(ADD_DEFINITION, JaxrsSubsystemAdd.INSTANCE); START resourceRegistration.registerOperationHandler(REMOVE_DEFINITION, ReloadRequiredRemoveStepHandler.INSTANCE); END } } Why are these registered at all? What invokes them?

Target:
public void registerOperations(ManagementResourceRegistration resourceRegistration) { super.registerOperations(resourceRegistration); resourceRegistration.registerOperationHandler(ShowJaxrsResourcesHandler.DEFINITION, new ShowJaxrsResourcesHandler()); }
Source:
public int hashCode() { START int result = processId.hashCode(); END result = 31 * result + taskId.hashCode(); result = 31 * result + taskName.hashCode(); result = 31 * result + formName.hashCode(); return result; } And one for luck ;-)

Target:
public int hashCode() { int result = processId.hashCode(); result = ~~result; result = 31 * result + taskId.hashCode(); result = ~~result; result = 31 * result + taskName.hashCode(); result = ~~result; result = 31 * result + formName.hashCode(); result = ~~result; return result; }
Source:
START public synchronized void stop(final String reason) END { new Thread( "Shutdown Thread" ) { @Override public void run() { independentThreadStop( reason, true ); } }.start(); } Can probably remove synchronized now?

Target:
public void stop(final String reason) { new Thread( "Shutdown Thread" ) { @Override public void run() { independentThreadStop( reason, true ); } }.start(); }
Source:
public boolean equals(Object o) { if (!(o instanceof Map.Entry)) START return END false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; return ((key == null ? e.getKey() == null : key.equals(e.getKey())) && (value == null ? e.getValue() == null : value.equals(e.getValue()))); } braces

Target:
public boolean equals(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry<?,?> e = (Map.Entry<?,?>)o; return ((key == null ? e.getKey() == null : key.equals(e.getKey())) && (value == null ? e.getValue() == null : value.equals(e.getValue()))); }
Source:
START public PostgreSqlEngine(final PdbProperties properties, final String driver) throws DatabaseEngineException { END super(driver, properties, Dialect.POSTGRESQL); } protected ?

Target:
protected PostgreSqlEngine(final PdbProperties properties, final String driver) throws DatabaseEngineException { super(driver, properties, Dialect.POSTGRESQL); }
Source:
START public void dispose() { END clearCachedSwingEditor(); } make dispose synchronized, then we could remove the volatile keyword in the class member.

Target:
public synchronized void dispose() { clearCachedSwingEditor(); }
Source:
public void run() { if(thread == null || !Thread.currentThread().equals(thread)) { START thread = new Thread(this); END thread.start(); } else { try { if (logger.isInfoEnabled()) logger.info("Start reconnecting " + provider); provider.register( getUIService().getDefaultSecurityAuthority(provider)); } catch (OperationFailedException ex) { logger.error("cannot re-register provider will keep going", ex); } } } I'm thinking that new thread is not needed for the reconnect task. This thread should be dead already by the time a new reconnect is needed and I see `Timer` instance serving the purpose of this thread. What do you think?

Target:
public void run() { try { if (logger.isInfoEnabled()) logger.info("Start reconnecting " + provider); provider.register( getUIService().getDefaultSecurityAuthority(provider)); } catch (OperationFailedException ex) { logger.error("cannot re-register provider will keep going", ex); } }
Source:
public void checkProperties(Properties properties) { START properties.setProperty("log4j.shutdownCallbackRegistry", "io.druid.common.config.Log4jShutdown"); END properties.setProperty("log4j.shutdownHookEnabled", "true"); } Couldn't this actually depend on the class and generate the name from that?

Target:
public void checkProperties(Properties properties) { if (!properties.contains("log4j.shutdownCallbackRegistry")) { properties.setProperty("log4j.shutdownCallbackRegistry", "io.druid.common.config.Log4jShutdown"); } if (!properties.contains("log4j.shutdownHookEnabled")) { properties.setProperty("log4j.shutdownHookEnabled", "true"); } }
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartTimerEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartTimerEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); START assertTimerEventEmpty(emptyTop.getExecutionSet(), NON_INTERRUPTING, ""); END // Know issue. Should be uncommented after https://issues.jboss.org/browse/JBPM-7038 will be fixed //assertDataIOSet(emptySubprocess.getDataIOSet(), EMPTY_VALUE); } ```suggestion assertTimerEventEmpty(emptyTop.getExecutionSet(), NON_INTERRUPTING, EMPTY_VALUE); ```

Target:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartTimerEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartTimerEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertTimerEventEmpty(emptyTop.getExecutionSet(), NON_INTERRUPTING, EMPTY_VALUE); // Know issue. Should be uncommented after https://issues.jboss.org/browse/JBPM-7038 will be fixed //assertDataIOSet(emptySubprocess.getDataIOSet(), EMPTY_VALUE); }
Source:
private EmbeddedExpirableMetadata( long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit, EntryVersion version) { super(version); this.lifespan = lifespan < 0 ? lifespan : lifespanUnit.toMillis(lifespan); START this.maxIdle = maxIdleUnit.toMillis(maxIdle); END } We should handle maxIdle as well

Target:
private EmbeddedExpirableMetadata( long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit, EntryVersion version) { super(version); this.lifespan = lifespan < 0 ? -1 : lifespanUnit.toMillis(lifespan); this.maxIdle = maxIdle < 0 ? -1 : maxIdleUnit.toMillis(maxIdle); }
Source:
protected void setMatcherString(String pattern) { if (pattern.length() == 0) { searchPattern = null; } else { SearchPattern patternMatcher = new SearchPattern(); if (pattern.indexOf('*') != 0 && pattern.indexOf('?') != 0 && pattern.indexOf('.') != 0) { START pattern = "*" + pattern; //$NON-NLS-1$ END } patternMatcher.setPattern(pattern); searchPattern = patternMatcher; } } @Lars Do you think that for consistency (and maybe another slight performance enhancement) this line should be changed as well?

Target:
protected void setMatcherString(String pattern) { if (pattern.length() == 0) { searchPattern = null; } else { SearchPattern patternMatcher = new SearchPattern(); if (pattern.indexOf('*') != 0 && pattern.indexOf('?') != 0 && pattern.indexOf('.') != 0) { pattern = '*' + pattern; } patternMatcher.setPattern(pattern); searchPattern = patternMatcher; } }
Source:
public DefaultEditorSession(final ManagedSession session, final CanvasCommandManager<AbstractCanvasHandler> canvasCommandManager, final @Session SessionCommandManager<AbstractCanvasHandler> sessionCommandManager, final @Request SessionCommandManager<AbstractCanvasHandler> requestCommandManager, final ClientCommandRegistry<org.kie.workbench.common.stunner.core.command.Command<AbstractCanvasHandler, CanvasViolation>> clientCommandRegistry) { this.session = session; START this.commandRegistry = clientCommandRegistry.setSession(session); END this.sessionCommandManager = sessionCommandManager; this.requestCommandManager = requestCommandManager; this.canvasCommandManager = canvasCommandManager; } yeah let's remove this :)

Target:
public DefaultEditorSession(final ManagedSession session, final CanvasCommandManager<AbstractCanvasHandler> canvasCommandManager, final @Session SessionCommandManager<AbstractCanvasHandler> sessionCommandManager, final @Request SessionCommandManager<AbstractCanvasHandler> requestCommandManager, final ClientCommandRegistry<org.kie.workbench.common.stunner.core.command.Command<AbstractCanvasHandler, CanvasViolation>> clientCommandRegistry) { this.session = session; this.commandRegistry = clientCommandRegistry; this.sessionCommandManager = sessionCommandManager; this.requestCommandManager = requestCommandManager; this.canvasCommandManager = canvasCommandManager; }
Source:
private String transformToHeaderValue(Directive... directives) { START final StringBuilder sb = new StringBuilder(); END for (int i = 0; i < directives.length - 1; i++) { sb.append(directives[i].headerValue).append(", "); } sb.append(directives[directives.length - 1].headerValue); return sb.toString(); } For consistency across the project, please remove the `final` keyword here.

Target:
private String transformToHeaderValue(Directive... directives) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < directives.length - 1; i++) { sb.append(directives[i].headerValue).append(", "); } sb.append(directives[directives.length - 1].headerValue); return sb.toString(); }
Source:
private static void fireOnFailure(final NodeProvisioner.PlannedNode plannedNode, final Throwable cause) { for (CloudProvisioningListener cl : CloudProvisioningListener.all()) { try { cl.onFailure(plannedNode, cause); } catch (Throwable e) { LOGGER.log(Level.SEVERE, "Unexpected uncaught exception encountered while " + "processing onFailure() listener call in " + cl + " for agent " + plannedNode.displayName, e); START if (e instanceof Error) { END throw e; } } } } 🐜 De-facto we process errors in the logging handler. E.g. logging constructs the string, and it may cause OutOfMemoryError, which suppresses the original one. I'd rather vote that Errors are being rethrown without any processing

Target:
private static void fireOnFailure(final NodeProvisioner.PlannedNode plannedNode, final Throwable cause) { for (CloudProvisioningListener cl : CloudProvisioningListener.all()) { try { cl.onFailure(plannedNode, cause); } catch (Error e) { throw e; } catch (Throwable e) { LOGGER.log(Level.SEVERE, "Unexpected uncaught exception encountered while " + "processing onFailure() listener call in " + cl + " for agent " + plannedNode.displayName, e); } } }
Source:
public synchronized boolean isLastMQNotifLongAgo() { long delay = 18 * 3600; // 24h - 3h = 18h long threshold = sharedPreferences.getLong(getCurrentModeName() + LAST_MORNING_Q_TIMESTAMP, - delay) + delay; if (threshold < Calendar.getInstance().getTimeInMillis()) { Logger.d(TAG, "{} - Last MQ notif was yesterday", getCurrentModeName()); return true; } else { START Logger.d(TAG, "{} - Last MQ notif was recent, do not notify", getCurrentModeName()); END return false; } } These two logs could be `Logger.v()`. That's all, good to go!

Target:
public synchronized boolean isLastMQNotifLongAgo() { long delay = 18 * 3600; // 24h - 3h = 18h long threshold = sharedPreferences.getLong(getCurrentModeName() + LAST_MORNING_Q_TIMESTAMP, - delay) + delay; if (threshold < Calendar.getInstance().getTimeInMillis()) { Logger.v(TAG, "{} - Last MQ notif was yesterday", getCurrentModeName()); return true; } else { Logger.v(TAG, "{} - Last MQ notif was recent, do not notify", getCurrentModeName()); return false; } }
Source:
public CrewMember apply(org.atlasapi.media.entity.CrewMember input) { if (input instanceof org.atlasapi.media.entity.Actor) { return translateLegacyActor((org.atlasapi.media.entity.Actor) input); START } else if(Objects.nonNull(input)) { END return translateLegacyCrewMember(input); } else { return null; } } Ditto `input != null`

Target:
public CrewMember apply(org.atlasapi.media.entity.CrewMember input) { // we carry IDs through from Owl to Deer, reject anything without one if (null == input.getId()) { return null; } if (input instanceof org.atlasapi.media.entity.Actor) { return translateLegacyActor((org.atlasapi.media.entity.Actor) input); } else if(null != input) { return translateLegacyCrewMember(input); } else { return null; } }
Source:
public void testSocket() throws Exception { Socket s = new Socket(); s.connect(server.getLocalAddress()); s.close(); assertEquals(Collections.EMPTY_MAP, START tagger.getLiveDescriptors()); END } Did you want to assert something before close in all these cases? i.e. it's not empty.

Target:
public void testSocket() throws Exception { Socket s = new Socket(); s.connect(server.getLocalAddress()); assertEquals(1, tagger.getLiveDescriptors().size()); s.close(); assertEquals(Collections.EMPTY_MAP, tagger.getLiveDescriptors()); }
Source:
public ValuesMatcher( Map<String, Integer> outputSymbolAliases, Optional<Integer> expectedOutputSymbolCount, Optional<List<List<Expression>>> expectedRows) { START this.outputSymbolAliases = ImmutableMap.copyOf(requireNonNull(outputSymbolAliases, "outputSymbolAliases is null")); END this.expectedOutputSymbolCount = requireNonNull(expectedOutputSymbolCount, "expectedOutputSymbolCount is null"); this.expectedRows = requireNonNull(expectedRows, "expectedRows is null"); } `requireNonNull` is not needed given `copyOf` checks for nullability.

Target:
public ValuesMatcher( Map<String, Integer> outputSymbolAliases, Optional<Integer> expectedOutputSymbolCount, Optional<List<List<Expression>>> expectedRows) { this.outputSymbolAliases = ImmutableMap.copyOf(outputSymbolAliases); this.expectedOutputSymbolCount = requireNonNull(expectedOutputSymbolCount, "expectedOutputSymbolCount is null"); this.expectedRows = requireNonNull(expectedRows, "expectedRows is null"); }
Source:
protected Button getButton(int id) { START return buttons.get(new Integer(id)); END } Can just pass id and let Java autoboxing take care of it.

Target:
protected Button getButton(int id) { return buttons.get(id); }
Source:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { if (data instanceof START Hashtable) { END Hashtable<?, ?> table = (Hashtable<?, ?>) data; color = (String) table.get("color"); //$NON-NLS-1$ } } Better: Map

Target:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { if (data instanceof Hashtable<?, ?>) { Hashtable<?, ?> map = (Hashtable<?, ?>) data; color = (String) map.get("color"); //$NON-NLS-1$ } }
Source:
public void addRequestCleanupHandler(HttpServletRequest request) { RequestContext.getActiveContext(request).addRequestCleanupHandler(new RequestCleanupHandler() { @Override public void cleanup(HttpServletRequest req) { try { close(); } catch (OperationException cause) { START throw new NuxeoException(cause); END } } }); } `cause` —> `e` please

Target:
public void addRequestCleanupHandler(HttpServletRequest request) { RequestContext.getActiveContext(request).addRequestCleanupHandler(new RequestCleanupHandler() { @Override public void cleanup(HttpServletRequest req) { try { close(); } catch (OperationException e) { throw new NuxeoException(e); } } }); }
Source:
public void visitStatementList(PyStatementListTree pyStatementListTree) { START if (isStmtListIncrementsNestingLevel(pyStatementListTree) && !pyStatementListTree.parent().is(Kind.FILE_INPUT)) { END nestingLevelStack.peek().increment(); super.visitStatementList(pyStatementListTree); nestingLevelStack.peek().decrement(); } else { super.visitStatementList(pyStatementListTree); } } Why not move the logic about `Kind.FILE_INPUT` inside `isStmtListIncrementsNestingLevel`?

Target:
public void visitStatementList(PyStatementListTree pyStatementListTree) { if (isStmtListIncrementsNestingLevel(pyStatementListTree)) { nestingLevelStack.peek().increment(); super.visitStatementList(pyStatementListTree); nestingLevelStack.peek().decrement(); } else { super.visitStatementList(pyStatementListTree); } }
Source:
private static void checkLxmlParseCall(SubscriptionContext ctx) { CallExpression callExpression = (CallExpression) ctx.syntaxNode(); if (checkCallExpressionFqn(callExpression, LXML_PARSE)) { CallExpression parserCall = getParserCall( getArgValueAsCallExpression( TreeUtils.nthArgumentOrKeyword(1, "parser", callExpression.arguments()))); if (parserCall != null && isUnsafeParserUsage(parserCall)) { START ctx.addIssue(parserCall, MESSAGE).secondary(callExpression, MESSAGE); END } } } no need to add the same message to the secondary location

Target:
private static void checkLxmlParseCall(SubscriptionContext ctx) { CallExpression callExpression = (CallExpression) ctx.syntaxNode(); if (checkCallExpressionFqn(callExpression, LXML_PARSE)) { CallExpression parserCall = getParserCall( getArgValueAsCallExpression( TreeUtils.nthArgumentOrKeyword(1, "parser", callExpression.arguments()))); if (parserCall != null && isUnsafeParserUsage(parserCall)) { ctx.addIssue(parserCall, MESSAGE).secondary(callExpression, null); } } }
Source:
public int getVisibility(IBinding member) { try { PDOMCPPMemberBlock members = new PDOMCPPMemberBlock(getLinkage(), record + MEMBERLIST); return members.getAccessibility(member); } catch (CoreException e) { CCorePlugin.log(e); START throw new IllegalArgumentException(member.getName() + " is not a member of " + getName()); //$NON-NLS-1$ END } } The same error is reported twice.

Target:
public int getVisibility(IBinding member) { try { PDOMCPPMemberBlock members = new PDOMCPPMemberBlock(getLinkage(), record + MEMBERLIST); return members.getVisibility(member); } catch (CoreException e) { CCorePlugin.log(e); throw new IllegalArgumentException(member.getName() + " is not a member of " + getName()); //$NON-NLS-1$ } }
Source:
public Map<String,Object> getDynamicTemplateData() { if(dynamicTemplateData == null) START return Collections.<String,Object>emptyMap(); END return dynamicTemplateData; } Nitpick: It's generally safer to include curly brackets for _all_ if statements. It can help protect against a future developer accidentally introducing a bug if another line is added to the if statement. Alternatively, a more succinct way of writing this method would be: ``` return (dynamicTemplateData == null) ? Collections.<String, Object>emptyMap() : dynamicTemplateData; ```

Target:
public Map<String,Object> getDynamicTemplateData() { return dynamicTemplateData == null ? Collections.<String,Object>emptyMap() : dynamicTemplateData; }
Source:
START public String getVersion() { END return version; } I'm not sure about public modifier here as version field represents reference's implementation details. I doubt consumers would be really interested in it. I would leave it private (or even remove it) unless there is a real usecase that requires access to its value. Making it private later would be hard (due to API breakage), we can make it public later without any problems.

Target:
String getVersion() { return version; }
Source:
public List<User> getUsers(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); // Authorization if(!AuthzResolver.isAuthorized(sess, Role.PERUNADMIN) && START !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) { END throw new PrivilegeException(sess, "getUsers"); } return getUsersManagerBl().getUsers(sess); } You can drop PERUNADMIN check here. And also in all other such methods in this file please.

Target:
public List<User> getUsers(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); // Authorization if(!AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) { throw new PrivilegeException(sess, "getUsers"); } return getUsersManagerBl().getUsers(sess); }
Source:
protected void setDefaultSwitchTypeIfNeeded() { Cluster cluster = getCluster(); START if (cluster.isSetRequiredSwitchType()) { END SwitchType defaultSwitchType = DefaultSwitchType.getDefaultSwitchType(cluster.getCompatibilityVersion()); cluster.setRequiredSwitchTypeForCluster(defaultSwitchType); } } Negation missing? if (!cluster.isSetRequiredSwitchType()) {

Target:
protected void setDefaultSwitchTypeIfNeeded() { Cluster cluster = getCluster(); if (!cluster.isSetRequiredSwitchType()) { SwitchType defaultSwitchType = DefaultSwitchType.getDefaultSwitchType(cluster.getCompatibilityVersion()); cluster.setRequiredSwitchTypeForCluster(defaultSwitchType); } }
Source:
public List<BlockLocationInfo> getBlockLocations(AlluxioURI alluxioURI) START throws IOException END { throw new UnsupportedOperationException("GetBlockLocations is not supported."); } Removed.

Target:
public List<BlockLocationInfo> getBlockLocations(AlluxioURI alluxioURI) { throw new UnsupportedOperationException("GetBlockLocations is not supported."); }
Source:
public CustomTxtParserWizard() { super(); START setWindowTitle(Messages.CustomTxtParserInputWizardPage_windowTitle); END } can this be in the second ctor and call this(null) here?

Target:
public CustomTxtParserWizard() { this(null); }
Source:
START protected Provider<AdditionalProperties> createProvider(String name) { END Provider<AdditionalProperties> p = mock(Provider.class); when(p.getName()).thenReturn(name); return p; } Don't see how this change is necessary

Target:
private Provider<AdditionalProperties> createProvider(String name) { Provider<AdditionalProperties> p = mock(Provider.class); when(p.getName()).thenReturn(name); return p; }
Source:
public static int mapApiToArtVersion(int api) { if (api < 19) { return NO_VERSION; } switch (api) { case 19: case 20: return 7; case 21: return 39; case 22: return 45; case 23: return 64; case 24: case 25: return 79; case 26: return 124; case 27: return 131; case 28: // 144 is the current version in the master branch of AOSP as of 2018-05-22 return 144; } START return 143; END } You can change the 28 case to a default case, and remove this.

Target:
public static int mapApiToArtVersion(int api) { if (api < 19) { return NO_VERSION; } switch (api) { case 19: case 20: return 7; case 21: return 39; case 22: return 45; case 23: return 64; case 24: case 25: return 79; case 26: return 124; case 27: return 131; default: // 144 is the current version in the master branch of AOSP as of 2018-05-22 return 144; } }