auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Function<Throwable, Throwable> getThrowableFunction(CoreEvent event) { return throwable -> { Throwable cause = getMessagingExceptionCause(throwable); CoreEvent exceptionEvent = event; if (throwable instanceof MessagingException) { exceptionEvent = ((MessagingException) throwable).getEvent(); } // MessagingException cause is set to null in order to avoid RETRY:EXHAUSTED ErrorType replacement // during ErrorType resolution (see ChainErrorHandlingUtils and MessagingExceptionResolver) return new MessagingException(exceptionEvent, new RetryPolicyExhaustedException(createStaticMessage(UNTIL_SUCCESSFUL_MSG_PREFIX, cause.getMessage()), START null, owner), END owner); }; } should this be done internally by `RetryPolicyExhaustedException`? What other uses are there for it?

Target:
private Function<Throwable, Throwable> getThrowableFunction(CoreEvent event) { return throwable -> { Throwable cause = getMessagingExceptionCause(throwable); CoreEvent exceptionEvent = event; if (throwable instanceof MessagingException) { exceptionEvent = ((MessagingException) throwable).getEvent(); } // RetryPolicyExhaustedException cause is not set in order to avoid RETRY:EXHAUSTED ErrorType replacement // during ErrorType resolution (see ChainErrorHandlingUtils and MessagingExceptionResolver) return new MessagingException(exceptionEvent, new RetryPolicyExhaustedException(createStaticMessage(UNTIL_SUCCESSFUL_MSG_PREFIX, cause.getMessage()), owner), owner); }; }
Source:
private void checkIfCrashRecoveryAndFinishActivity(final Activity context) { if (isRecoveredFromCrash()) { if (!(context instanceof MainMenuActivity)) { context.finish(); } else { PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(RECOVERED_FROM_CRASH, false).commit(); } } START CrashReporter.sendUnhandledCaughtException(); END } Please move the line in the if isRecoveredFromCrash block. ```java if (isRecoveredFromCrash()) { CrashReporter.sendUnhandledCaughtException(); … ``` This way we don't change the behavior in any kind. We will discuss where to put it later on.

Target:
private void checkIfCrashRecoveryAndFinishActivity(final Activity context) { if (isRecoveredFromCrash()) { CrashReporter.sendUnhandledCaughtException(); if (!(context instanceof MainMenuActivity)) { context.finish(); } else { PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(RECOVERED_FROM_CRASH, false).commit(); } } }
Source:
START public boolean evaluate(String uriHost, String uriPath, String uriQuery, String httpStatus, String contentType, String userAgent) { END return Pageview.isPageview(uriHost.toString(), uriPath.toString(), uriQuery.toString(), httpStatus.toString(), contentType.toString(), userAgent.toString()); } Loooooong line

Target:
public boolean evaluate( String uriHost, String uriPath, String uriQuery, String httpStatus, String contentType, String userAgent ) { return Pageview.isPageview( uriHost, uriPath, uriQuery, httpStatus, contentType, userAgent ); }
Source:
public Integer replayObserverFromIndex(Integer idx, SubjectObserver<? super T> observer) { int i = idx; START while (i < index.get()) { END accept(observer, i); i++; } return i; } The `index` field should be read into a local variable outside the loop.

Target:
public Integer replayObserverFromIndex(Integer idx, SubjectObserver<? super T> observer) { int i = idx; while (i < get()) { accept(observer, i); i++; } return i; }
Source:
public String getUnmodifiedInstance() { START return m_ipAddress + "[" + m_serviceName + "]"; END } ```suggestion return getInstance(); ```

Target:
public String getUnmodifiedInstance() { return getInstance(); }
Source:
START public LogEntry save(LogEntry delegate) throws ResourceDoesNotSupportOperationException { END return null; } Try to fill more of these methods bodies by copying ideas from that pull request or even the classes i pointed you to in the ticket description.

Target:
public LogEntry save(LogEntry delegate) throws ResourceDoesNotSupportOperationException { throw new ResourceDoesNotSupportOperationException(); }
Source:
protected int indexOfChild(String localName) { AbstractDataTreeNode[] nodes = this.children; NoDataDeltaNode localNameNode = new NoDataDeltaNode(localName); START return Arrays.binarySearch(nodes, localNameNode, (n1, n2) -> n1.name.compareTo(n2.name)); END } Two things: * Arrays.binarySearch() returns a negative if not found, but not necessarily -1 like the original code. And that will make line 453 above fail. You'd also have to check other callers. * IIRC this operation is called *very* frequently. I think you absolutely want to avoid allocating a dummy object here; it'll just put additional pressure on GC.

Target:
protected int indexOfChild(String localName) { AbstractDataTreeNode[] nodes = this.children; if (nodes.length == 0) { return -1; } else if (nodes.length == 1) { return nodes[0].name.equals(localName) ? 0 : -1; } NoDataDeltaNode localNameNode = new NoDataDeltaNode(localName); return Arrays.binarySearch(nodes, localNameNode, (n1, n2) -> n1.name.compareTo(n2.name)); }
Source:
public void test() { connect(); jq(".z-listbox-body").scrollTop(10000); START waitResponse(); END Assert.assertTrue(jq("@listcell:contains(199)").exists()); } need to wait before doing scrollTop

Target:
public void test() { connect(); waitResponse(); jq(".z-listbox-body").scrollTop(10000); waitResponse(); Assert.assertTrue(jq("@listcell:contains(199)").exists()); }
Source:
@Override public void initialize(Context context, ValueMap settings, LogLevel logLevel) throws IllegalStateException { START if (!hasPermission(context, Manifest.permission.INTERNET)) { END throw new IllegalStateException("Apptimize requires INTERNET permission"); } Apptimize.setup(context, settings.getString("appkey")); } Our SDK can't be initialized without the internet permission either, so you don't need to check for this.

Target:
@Override public void initialize(Context context, ValueMap settings, LogLevel logLevel) throws IllegalStateException { Apptimize.setup(context, settings.getString("appkey")); }
Source:
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { START ViewGroup rootView = createMainView(inflater, container, savedInstanceState); return rootView; END } Nitpick: AS is complaining about the unnecessary `rootView` variable. 😿

Target:
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return createMainView(inflater, container, savedInstanceState); }
Source:
START public static Set<FieldDeclaration> mergeFDs( DirectCompilerResult... sets ) { END Set<FieldDeclaration> result = new HashSet<>(); for ( DirectCompilerResult fs : sets ) { result.addAll(fs.getFieldDeclarations()); } return result; } Formatting of `( DirectCompilerResult... sets )`, should be `(DirectCompilerResult... sets)`.

Target:
public static Set<FieldDeclaration> mergeFDs( DirectCompilerResult... sets ) { return mergeFDs(Arrays.asList(sets)); }
Source:
private Long getHostsByCapability(List<Long> hostList, String hostCapability) { int totalHostswithCapability = 0; for (Long host : hostList) { //TODO: Fix this in single query instead of polling request for each Host Map<String, String> details = hostDetailsDao.findDetails(host); if (details.containsKey(Host.HOST_UEFI_ENABLE)) { if (details.get(Host.HOST_UEFI_ENABLE).equalsIgnoreCase("Yes")) { START totalHostswithCapability++; END } } } return totalHostswithCapability > 0 ? new Long(1) : new Long(0); } Better return here when a host found with UEFI capability as that satisfies the return cond.

Target:
private Long getHostsByCapability(List<Long> hostList, String hostCapability) { for (Long host : hostList) { //TODO: Fix this in single query instead of polling request for each Host Map<String, String> details = hostDetailsDao.findDetails(host); if (details.containsKey(Host.HOST_UEFI_ENABLE)) { if (details.get(Host.HOST_UEFI_ENABLE).equalsIgnoreCase("Yes")) { return new Long(1); } } } return new Long(0); }
Source:
START void setUniverseWrapper(UniverseWrapper wrapper) { END this.universeWrapper = wrapper; } Probably another access modification we don't need (probably the same for `isLoadingAsServer()` ?)

Target:
public void setUniverseWrapper(UniverseWrapper wrapper) { this.universeWrapper = wrapper; }
Source:
public Double getAggregate(AverageAccumulator<Double> result) { START return (result.value)/result.count; END } I suggest to check whether count is 0, and return null (so that the aggregate constraint simply will not match) in that case.

Target:
public Double getAggregate(AverageAccumulator<Double> result) { return (result.count == 0) ? null : ((double)result.value)/result.count; }
Source:
public static void openClassLoader() throws IOException { ClassLoader myClassLoader = RetentionPolicyTest.class.getClassLoader(); START assert myClassLoader END != null; // Load the annotated class (and annotation classes) from the annotations-test.jar. See // http://b/132100102. File jarFile = new File(temporaryFolder.getRoot(), "annotations-test.jar"); try (InputStream in = myClassLoader.getResourceAsStream("annotations-test.jar"); OutputStream out = new FileOutputStream(jarFile)) { Streams.copy(in, out); } classLoader = new PathClassLoader(jarFile.getAbsolutePath(), myClassLoader); } Did you mean to use the assert keyword here? Is it functional? Suggest either remove or switch to assertNotNull()

Target:
public static void openClassLoader() throws IOException { ClassLoader myClassLoader = RetentionPolicyTest.class.getClassLoader(); assertNotNull(myClassLoader); // Load the annotated class (and annotation classes) from the annotations-test.jar. File jarFile = new File(temporaryFolder.getRoot(), "annotations-test.jar"); try (InputStream in = myClassLoader.getResourceAsStream("annotations-test.jar"); OutputStream out = new FileOutputStream(jarFile)) { Streams.copy(in, out); } classLoader = new PathClassLoader(jarFile.getAbsolutePath(), myClassLoader); }
Source:
private boolean isWithoutRoot(Parameter[] parameters, JsonObject root, ControllerMethod method) { START if(method.containsAnnotation(Consumes.class) && method.getMethod().getAnnotation(Consumes.class).withoutRoot()) { END return true; } for (Parameter parameter : parameters) { if (root.get(parameter.getName()) != null) return false; } return true; } I think that the 1st check is not needed, because if method doesn't contains `Consumes`, observer will not called.

Target:
private boolean isWithoutRoot(Parameter[] parameters, JsonObject root, ControllerMethod method) { if(method.getMethod().getAnnotation(Consumes.class).withoutRoot()) { return true; } for (Parameter parameter : parameters) { if (root.get(parameter.getName()) != null) return false; } return true; }
Source:
public String getValue(ITask task) { AbstractRepositoryConnector connector = TasksUi.getRepositoryConnector(task.getConnectorKind()); TaskRepository repository = TasksUiInternal.getRepository(task); START URL url = connector.getBrowserUrl(repository, task); END if (url == null) { return task.getUrl(); } return url.toString(); } This should check that repository is not null.

Target:
public String getValue(ITask task) { AbstractRepositoryConnector connector = TasksUi.getRepositoryConnector(task.getConnectorKind()); TaskRepository repository = TasksUiInternal.getRepository(task); if (repository != null) { URL url = connector.getBrowserUrl(repository, task); if (url != null) { return url.toString(); } } return task.getUrl(); }
Source:
protected void onInit() { START this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(this.getBeanFactory()); END if (this.mongoTemplate == null) { this.mongoTemplate = new ReactiveMongoTemplate(this.mongoDbFactory, this.mongoConverter); } this.initialized = true; } No, `this.` when you call methods.

Target:
protected void onInit() { this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory()); if (this.mongoTemplate == null) { this.mongoTemplate = new ReactiveMongoTemplate(this.mongoDbFactory, this.mongoConverter); } this.initialized = true; }
Source:
public String read(String key) { String data = dataManager.read(key); START return (data == null) ? null : encode(cryptoBox.decrypt(iv, decode(data)); END } Missing a close bracket (`)`) before the `;`.

Target:
public String read(String key) { String data = dataManager.read(key); return (data == null) ? null : encode(cryptoBox.decrypt(iv, decode(data))); }
Source:
protected void executeVdsBrokerCommand() { try { DeviceInfoReturn deviceInfoReturn = START getBroker().attachManagedBlockStorageVolume(getParameters().getVolumeId(), JsonHelper.mapToJson(getParameters().getConnectionInfo())); END setReturnValue(deviceInfoReturn.getDeviceInfo()); } catch (IOException e) { log.error("attachment of managed block storage device failed {}", e); return; } } please break the line

Target:
protected void executeVdsBrokerCommand() { DeviceInfoReturn deviceInfoReturn = getBroker().attachManagedBlockStorageVolume(getParameters().getVolumeId(), getParameters().getConnectionInfo()); setReturnValue(deviceInfoReturn.getDeviceInfo()); }
Source:
public IndexedInts getRow() { // Treat any non-single-valued row as a row containing a single null value, to ensure consistency with // other expression selectors. See also ExpressionSelectors.supplierFromDimensionSelector for similar behavior. final IndexedInts row = selector.getRow(); if (row.size() == 1) { if (nullAdjustment == 0) { return row; } else { return new SingleIndexedInt(row.get(0) + nullAdjustment); } } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. START return new SingleIndexedInt(0); END } } Could be cached, `SingleIndexedInt.of()` and cache 0-127 :)

Target:
public IndexedInts getRow() { final IndexedInts row = selector.getRow(); if (row.size() == 1) { if (nullAdjustment == 0) { return row; } else { return SingleIndexedInt.of(row.get(0) + nullAdjustment); } } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return SingleIndexedInt.of(0); } }
Source:
public void channelRegistered(ChannelHandlerContext ctx) throws Exception { super.channelRegistered(ctx); LOG.info("channelRegistered {}", ctx); START } END These look like they are for debugging. could we make them debug logs instead?

Target:
public void channelRegistered(ChannelHandlerContext ctx) throws Exception { super.channelRegistered(ctx); LOG.debug("channelRegistered {}", ctx); }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } START if (!(obj instanceof Member)) { END return false; } if (!getClass().equals(obj.getClass())) { return false; } Member other = (Member) obj; return getId() == other.getId(); } Shouldn't this be at line 134 ? Replacing ``.getClass()`` check instead of ``obj == null`` check ? Like in ``User`` object ? I know it will return ``false`` for ``null`` anyway, but this will also return false if you compare ``Member`` and ``RichMember`` which we wanted to be comparable. In ``User`` object you just continue with params comparison when you compare ``User`` and ``Candidate`` or ``RichUser``. I believe implementation should be at least equivalent in both ``Member`` and ``User`` objects.

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Member)) { return false; } Member other = (Member) obj; return getId() == other.getId(); }
Source:
public List<RefRight> getAllRights(final ApprovalCategory.Id id) { List<RefRight> l = new ArrayList<RefRight>(); l.addAll(getLocalRights(id)); l.addAll(getInheritedRights(id)); Collections.sort(l, RefRight.REF_PATTERN_ORDER); START l = Collections.unmodifiableList(RefControl.filterMostSpecific(l)); END return l; } Style-nit: You can just return Collections.unmodifiableList ... here and avoid assignment back to l.

Target:
public List<RefRight> getAllRights(final ApprovalCategory.Id id) { List<RefRight> l = new ArrayList<RefRight>(); l.addAll(getLocalRights(id)); l.addAll(getInheritedRights(id)); Collections.sort(l, RefRight.REF_PATTERN_ORDER); return Collections.unmodifiableList(RefControl.filterMostSpecific(l)); }
Source:
public void checkSelectFilter(final String label, final String value) { selectInputs.computeIfPresent(label, (key, values) -> { values.forEach(i -> { START if ((i.getValue().equals(value)) && i.getChecked() == false) { END i.setChecked(true); } }); return values; }); } is this needed?

Target:
public void checkSelectFilter(final String label, final String value) { selectInputs.computeIfPresent(label, (key, values) -> { values.forEach(i -> { if (i.getValue().equals(value) && i.getChecked() == false) { i.setChecked(true); } }); return values; }); }
Source:
START public synchronized Marshaller<Key> getKeyMarshaller() { END return keyMarshaller; } Instead remove synchronized from the setter, and make the variable volatile

Target:
public Marshaller<Key> getKeyMarshaller() { return keyMarshaller; }
Source:
public void loadMyStep(int id) { try { START if (!Objects.equals(id, null)) { END setMySchritt(this.serviceManager.getTaskService().getById(id)); } } catch (DAOException e) { Helper.setFehlerMeldung("Error retrieving task with ID '" + id + "'; ", e.getMessage()); } } An `int` type can or should never be null, maybe you want to use an `Integer` type which can be null. On other places you are comparing this with value `0`, so maybe only a wrong written condition?

Target:
public void loadMyStep(int id) { try { setMySchritt(this.serviceManager.getTaskService().getById(id)); } catch (DAOException e) { Helper.setFehlerMeldung("Error retrieving task with ID '" + id + "'; ", e.getMessage()); } }
Source:
private void addBootstrap3And4Style( START String bootstrap3FileName, InputStream bootstrap3Data, Resource bootstrap4resource) { END try (InputStream bootstrap4Data = bootstrap4resource.getInputStream()) { String bootstrap4FileName = bootstrap4resource.getFilename(); LOG.debug("Adding matching bootstrap 4 theme with name {}", bootstrap4FileName); styleService.addStyle( bootstrap3FileName, bootstrap3FileName, bootstrap3Data, bootstrap4FileName, bootstrap4Data); } catch (IOException e) { LOG.error("error adding new bootstrap 4 theme", e); } } Is a bit surprising that it gets one InputStream and one Resource.

Target:
private void addBootstrap3And4Style( String bootstrap3FileName, InputStream bootstrap3Data, Resource bootstrap4resource) { try (InputStream bootstrap4Data = bootstrap4resource.getInputStream()) { String bootstrap4FileName = bootstrap4resource.getFilename(); LOG.debug("Adding matching bootstrap 4 theme with name {}", bootstrap4FileName); styleService.addStyle( bootstrap3FileName, bootstrap3FileName, bootstrap3Data, bootstrap4FileName, bootstrap4Data); } catch (Exception e) { LOG.error("error adding new bootstrap 4 theme", e); } }
Source:
public void init() throws DBException { synchronized(RocksDBClient.class) { if(rocksDb == null) { rocksDbDir = Paths.get(getProperties().getProperty(PROPERTY_ROCKSDB_DIR)); START System.out.println("RocksDB data dir: " + rocksDbDir); END try { rocksDb = initRocksDB(); } catch (final IOException | RocksDBException e) { throw new DBException(e); } } references++; } } please use a logging framework instead of System.out for messages. preferably slf4j.

Target:
public void init() throws DBException { synchronized(RocksDBClient.class) { if(rocksDb == null) { rocksDbDir = Paths.get(getProperties().getProperty(PROPERTY_ROCKSDB_DIR)); LOGGER.info("RocksDB data dir: " + rocksDbDir); try { rocksDb = initRocksDB(); } catch (final IOException | RocksDBException e) { throw new DBException(e); } } references++; } }
Source:
protected void registerExtraDatabaseTypes( Properties configuration ) throws KettlePluginException { /*String hiveSimbaDriverName = configuration.getProperty( "hive2.simba.driver", "com.simba.hive.jdbc41.HS2Driver" ); JDBC_POSSIBLE_DRIVER_MAP.put( "hive2Simba", hiveSimbaDriverName );*/ START String impalaSimbaDriverName = END configuration.getProperty( "impala.simba.driver", "com.cloudera.impala.jdbc41.Driver" ); JDBC_POSSIBLE_DRIVER_MAP.put( "ImpalaSimba", impalaSimbaDriverName ); } We don't need impala for hdi35, it's Cloudera only.

Target:
protected void registerExtraDatabaseTypes( Properties configuration ) throws KettlePluginException { /*String hiveSimbaDriverName = configuration.getProperty( "hive2.simba.driver", "com.simba.hive.jdbc41.HS2Driver" ); JDBC_POSSIBLE_DRIVER_MAP.put( "hive2Simba", hiveSimbaDriverName );*/ /*String impalaSimbaDriverName = configuration.getProperty( "impala.simba.driver", "com.cloudera.impala.jdbc41.Driver" ); JDBC_POSSIBLE_DRIVER_MAP.put( "ImpalaSimba", impalaSimbaDriverName );*/ }
Source:
START void addEntriesAndRotateLogs(EntryLogger entryLogger, int numOfRotations) END throws IOException { EntryLogManagerBase entryLogManager = (EntryLogManagerBase) entryLogger.getEntryLogManager(); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); Random rand = new Random(); for (int i = 0; i < numOfRotations; i++) { addEntries(entryLogger, 10); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); } addEntries(entryLogger, 10); } nit: make this static

Target:
void addEntriesAndRotateLogs(EntryLogger entryLogger, int numOfRotations) throws IOException { EntryLogManagerBase entryLogManager = (EntryLogManagerBase) entryLogger.getEntryLogManager(); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); for (int i = 0; i < numOfRotations; i++) { addEntries(entryLogger, 10); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); } addEntries(entryLogger, 10); }
Source:
public static ArrayList<Guid> getGuidListFromString(String str) { START if (StringHelper.isNullOrEmpty(str)) { END return new ArrayList<Guid>(); } return getGuidListFromStringArray(Arrays.asList(str.split(SEPARATOR))); } We're trying to kill off the entire compat package - please don't add new dependencies to it. You can use common-lang's StringUtils.isEmpty(str)

Target:
public static ArrayList<Guid> getGuidListFromString(String str) { if (StringUtils.isEmpty(str)) { return new ArrayList<Guid>(); } return getGuidListFromStringArray(Arrays.asList(str.split(SEPARATOR))); }
Source:
public FileMockContext(Context context) { mContext = context; // default START requestedPermissionName = "android.permission.INTERNET"; END responsePermissionFlag = PackageManager.PERMISSION_GRANTED; permissionMap.put(requestedPermissionName,responsePermissionFlag); } do you still need the requestePermissionName and responsePermissionFlag?

Target:
public FileMockContext(Context context) { mContext = context; // default String requestedPermissionName = "android.permission.INTERNET"; int responsePermissionFlag = PackageManager.PERMISSION_GRANTED; permissionMap.put(requestedPermissionName,responsePermissionFlag); }
Source:
public static MultipartInput buildMultipartInput(Object input, String content) throws IOException { MultipartInput mpinput = new MultipartInput(); mpinput.setRequest(content); if (input instanceof Blob) { Blob blob = (Blob) input; START mpinput.setBlob(blob); END } else if (input instanceof Blobs) { mpinput.setBlobs((Blobs) input); } else { throw new IllegalArgumentException("Unsupported binary input object: " + input); } return mpinput; } No need for intermediate `blob` variable

Target:
public static MultipartInput buildMultipartInput(Object input, String content) throws IOException { MultipartInput mpinput = new MultipartInput(); mpinput.setRequest(content); if (input instanceof Blob) { mpinput.setBlob((Blob) input); } else if (input instanceof Blobs) { mpinput.setBlobs((Blobs) input); } else { throw new IllegalArgumentException("Unsupported binary input object: " + input); } return mpinput; }
Source:
private ImmutableListMultimap<String, Availability> getAvailabilities(List<Episode> episodes) { ImmutableListMultimap<String, Availability> availabilities; try { START availabilities = availabilities(episodes); END } catch (GlycerinException e) { throw Throwables.propagate(e); } return availabilities; } Just do `return availabilities(episodes)` here. Same for the rest of them.

Target:
private ImmutableListMultimap<String, Availability> getAvailabilities(List<Episode> episodes) { ImmutableListMultimap<String, Availability> availabilities; try { return availabilities(episodes); } catch (GlycerinException e) { throw Throwables.propagate(e); } }
Source:
public static boolean isWhitespaceOrComment(int kind) { START switch (getCategory(kind)) { END case WHITESPACE: case COMMENT: return true; default: return false; } } nice. Maybe we can have a `isWhitespaceOrComment` method on the category and change this to: `return getCategory(kind).isWhitespaceOrComment()`

Target:
public static boolean isWhitespaceOrComment(int kind) { return getCategory(kind).isWhitespaceOrComment(); }
Source:
public List<String> getRuleChainVisits() { if (xPathRuleQueryNeedsInitialization()) { initXPathRuleQuery(); START for (final String nodeName : xpathRuleQuery.getRuleChainVisits()) { END super.addRuleChainVisit(nodeName); } } return super.getRuleChainVisits(); } Unwanted final?

Target:
public List<String> getRuleChainVisits() { if (xPathRuleQueryNeedsInitialization()) { initXPathRuleQuery(); for (String nodeName : xpathRuleQuery.getRuleChainVisits()) { super.addRuleChainVisit(nodeName); } } return super.getRuleChainVisits(); }
Source:
private boolean appliesToEvent(ITmfEvent event) { String eventName = event.getType().getName(); String eventHandlerName = fName; // test for correct name if (eventName.equals(eventHandlerName)) { return true; } // test for the wildcard at the end START if ((eventHandlerName.endsWith(TmfXmlStrings.WILDCARD) && eventName.startsWith(eventHandlerName.replace(TmfXmlStrings.WILDCARD, TmfXmlStrings.NULL)))) { END return true; } return false; } cut at &&

Target:
private boolean appliesToEvent(ITmfEvent event) { String eventName = event.getType().getName(); /* test for full name */ if (eventName.equals(fName)) { return true; } /* test for the wildcard at the end */ if ((fName.endsWith(TmfXmlStrings.WILDCARD) && eventName.startsWith(fName.replace(TmfXmlStrings.WILDCARD, TmfXmlStrings.NULL)))) { return true; } return false; }
Source:
@NonNull public String server() { // A protocol-relative URL can be returned from the API. // Protocol-relative URLs need to guarantee to be accessible via https, so we assume // https in this case. if (server.startsWith("//")) { server = START "https:" + END server; } return server; } Maybe we should derive this from Prefs.getMediaWikiBaseUri() or require the client to pass in a default protocol. I think I prefer the latter to avoid complicating this nice and simple model type.

Target:
@NonNull public String server() { return server; }
Source:
public void init(OrganizationalUnitsScreen presenter) { this.presenter = presenter; if (!presenter.canCreateOrganizationalUnit()) { createOrganizationalUnit.setHidden(true); } else { createOrganizationalUnit.setTextContent(ts.format(LibraryConstants.CreateOrganizationalUnit, translationUtils.getOrganizationalUnitAliasInSingular())); } title.setTextContent(translationUtils.getOrganizationalUnitAliasInPlural()); filterName.setAttribute("placeholder", ts.getTranslation(LibraryConstants.FilterByName)); START cardByOrganizationalUnitIdentifier = new HashMap<>(); END } Here I would make this view, or any view, as "stupid" as possible. The `if` here could be in presenter and as could this variable `cardByOrganizationalUnitIdentifier`. This way you see what the component does by looking at the presenter and the functionality can be tested with the unit test.

Target:
public void init(OrganizationalUnitsScreen presenter) { this.presenter = presenter; createOrganizationalUnit.setTextContent(ts.format(LibraryConstants.CreateOrganizationalUnit, translationUtils.getOrganizationalUnitAliasInSingular())); title.setTextContent(translationUtils.getOrganizationalUnitAliasInPlural()); filterName.setAttribute("placeholder", ts.getTranslation(LibraryConstants.FilterByName)); }
Source:
private CertificateDTO addCertByAlias(List<CertificateDTO> toList, List<CertificateDTO> fromList, String alias){ for(CertificateDTO cert : fromList){ START if(StringUtils.isNotEmpty(cert.getAlias()) && StringUtils.isNotEmpty(alias) && cert.getAlias().compareTo(alias)==0){ END toList.add(cert); fromList.remove(cert); return cert; } } return null; } Can we use .equals() instead of .compareTo?

Target:
private CertificateDTO addCertByAlias(List<CertificateDTO> toList, List<CertificateDTO> fromList, String alias){ for(CertificateDTO cert : fromList){ if (StringUtils.isNotEmpty(cert.getAlias()) && StringUtils.isNotEmpty(alias) && cert.getAlias().equals(alias)) { toList.add(0, cert); fromList.remove(cert); return cert; } } return null; }
Source:
public static ArrayList<Guid> getGuidListFromStringArray(List<String> strings) { ArrayList<Guid> guidList = new ArrayList<Guid>(); START if (CollectionUtils.isEmpty(strings)) { END for (String guidString : strings) { guidList.add(Guid.createGuidFromString(guidString)); } } return guidList; } pls replace with strings != null && strings.isEmpty()

Target:
public static ArrayList<Guid> getGuidListFromStringArray(List<String> strings) { ArrayList<Guid> guidList = new ArrayList<Guid>(); if (strings != null && !strings.isEmpty()) { for (String guidString : strings) { guidList.add(Guid.createGuidFromString(guidString)); } } return guidList; }
Source:
public void withAssertions_assertThat_iterator_Test() { START assertThat(Arrays.asList(ITEMS).iterator()).toIterable().contains(ITEMS[0]); END } Should be an iterator assertion, e.g: ``` assertThat(Arrays.asList(ITEMS).iterator()).hasNext(); ```

Target:
public void withAssertions_assertThat_iterator_Test() { assertThat(Arrays.asList(ITEMS).iterator()).hasNext(); }
Source:
public LogEntry deserializeLogData(ILogData logData) throws Exception{ LogEntry logEntry; try { logEntry = logData.getLogEntry(runtime); } catch (Exception e) { log.error("Cannot deserialize log entry" + logData.getGlobalAddress(), e); START throw e; END } return logEntry; } I dont think this try/catch is necessary to just log this message. Why don't you move the message to processLogData

Target:
public LogEntry deserializeLogData(ILogData logData) throws Exception{ return logData.getLogEntry(runtime); }
Source:
public QueryMetrics<Query<?>> makeMetrics(SegmentMetadataQuery query) { START query.withAnalysisTypes(getFinalAnalysisTypes(query)); END return queryMetricsFactory.makeMetrics(query); } The result of this call is unused. I don't think it should be here.

Target:
public QueryMetrics<Query<?>> makeMetrics(SegmentMetadataQuery query) { return queryMetricsFactory.makeMetrics(query); }
Source:
private static void checkAssertion(SamlAssertionWrapper assertion, String confirmMethod) throws WSSecurityException { if (OpenSAMLUtil.isMethodHolderOfKey(confirmMethod)) { if (assertion.getSubjectKeyInfo() == null) { START LOG.debug("There is no Subject KeyInfo to match the holder-of-key subject conf method"); END throw new WSSecurityException(ErrorCode.FAILED_CHECK, "noKeyInSAMLToken"); } // The assertion must have been signed for HOK if (!assertion.isSigned()) { LOG.debug("A holder-of-key assertion must be signed"); throw new WSSecurityException(ErrorCode.FAILED_CHECK, "invalidSAMLsecurity"); } } } This isn't really a debug statement, more of an info or trace.

Target:
private static void checkAssertion(SamlAssertionWrapper assertion, String confirmMethod) throws WSSecurityException { if (OpenSAMLUtil.isMethodHolderOfKey(confirmMethod)) { if (assertion.getSubjectKeyInfo() == null) { LOG.info("There is no Subject KeyInfo to match the holder-of-key subject conf method"); throw new WSSecurityException(ErrorCode.FAILED_CHECK, "noKeyInSAMLToken"); } // The assertion must have been signed for HOK if (!assertion.isSigned()) { LOG.info("A holder-of-key assertion must be signed"); throw new WSSecurityException(ErrorCode.FAILED_CHECK, "invalidSAMLsecurity"); } } }
Source:
public void checkChangedColumn() throws Exception { START test(String.format("ALTER session SET `%s` = %d;", SLICE_TARGET, END ExecConstants.SLICE_TARGET_DEFAULT)); testBuilder() .sqlQuery("SELECT status FROM sys.options WHERE name = '%s' AND type = 'SESSION'", SLICE_TARGET) .unOrdered() .baselineColumns("status") .baselineValues("DEFAULT") .build() .run(); } you can remove `String.format` here too

Target:
public void checkChangedColumn() throws Exception { test("ALTER session SET `%s` = %d;", SLICE_TARGET, ExecConstants.SLICE_TARGET_DEFAULT); testBuilder() .sqlQuery("SELECT status FROM sys.options WHERE name = '%s' AND type = 'SESSION'", SLICE_TARGET) .unOrdered() .baselineColumns("status") .baselineValues("DEFAULT") .build() .run(); }
Source:
public void tearDown() throws Exception { START this.mTranslateSpecialChar = null; END this.mTestStr.clear(); this.mVerifyStr.clear(); } remove "this."

Target:
public void tearDown() throws Exception { mTranslateSpecialChar = null; mTestStr.clear(); mVerifyStr.clear(); }
Source:
private String search(SearchRequest searchRequest, Model model, HttpServletRequest request) { SearchResultResponse resultResponse = doSearch(searchRequest, model, request); String queryText = formatQueryText(request); model.addAttribute("resultType", "searchResults"); START model.addAttribute("pageSubtitle", "Search results for <span class=\"query-request\">\"" END + queryText + "\"</span>"); return "searchResults"; } I'd like to keep formatting/mark up out of our controllers. Maybe we could put the `queryText` into its model attribute and use it in `searchResults.jsp`

Target:
private String search(SearchRequest searchRequest, Model model, HttpServletRequest request) { SearchResultResponse resultResponse = doSearch(searchRequest, model, request); String queryText = formatQueryText(request); model.addAttribute("resultType", "searchResults"); model.addAttribute("pageSubtitle", queryText); return "searchResults"; }
Source:
START private FetchV0Request(@NonNull Set<ObjectId> wantIds, int depth, END @NonNull Set<ObjectId> clientShallowCommits, long filterBlobLimit, @NonNull Set<String> clientCapabilities) { super(wantIds, depth, clientShallowCommits, filterBlobLimit, clientCapabilities); } I prefer to leave this as package-private to avoid a synthetic accessor.

Target:
FetchV0Request(@NonNull Set<ObjectId> wantIds, int depth, @NonNull Set<ObjectId> clientShallowCommits, long filterBlobLimit, @NonNull Set<String> clientCapabilities) { super(wantIds, depth, clientShallowCommits, filterBlobLimit, clientCapabilities); }
Source:
public static WeightedReservoirSampleStateStrategy deserialize(SliceInput input) { START WeightedDoubleReservoirSample reservoir = WeightedDoubleReservoirSample.deserialize(input); END return new WeightedReservoirSampleStateStrategy(reservoir); } I'd inline this variable: `return new WeightedReservoirSampleStateStrategy(WeightedDoubleReservoirSample.deserialize(input));`

Target:
public static WeightedReservoirSampleStateStrategy deserialize(SliceInput input) { return new WeightedReservoirSampleStateStrategy(WeightedDoubleReservoirSample.deserialize(input)); }
Source:
private void cleanup(File execDir) { if (execDir != null) { try { FileUtils.deleteDirectory(execDir); } catch (IOException e) { START Throwables.propagate(e); END } } } Isn't this an anti-pattern described by https://github.com/google/guava/wiki/Why-we-deprecated-Throwables.propagate Shall we move away from using a deprecated method in general?

Target:
private void cleanup(File execDir) { if (execDir != null) { try { FileUtils.deleteDirectory(execDir); } catch (IOException e) { throw new RuntimeException(e); } } }
Source:
public SELF isEqualTo(String stringTemplate, Object ... args){ String expected = String.format(stringTemplate, args); START this.comparables.assertEqual(info, actual, expected); END return super.isEqualTo(expected); } delete this line as the call to `super.isEqualTo(expected);` should be the only required assertion

Target:
public SELF isEqualTo(String stringTemplate, Object ... args){ String expected = String.format(stringTemplate, args); return super.isEqualTo(expected); }
Source:
public String getText() { if ("textarea".equals(getWrappedElement().getTagName())) { return getWrappedElement().getText(); } START Optional<String> enteredText = Optional.of(getWrappedElement().getAttribute("value")); END return enteredText.orElse(""); } can be inlined i think

Target:
public String getText() { if ("textarea".equals(getWrappedElement().getTagName())) { return getWrappedElement().getText(); } return Optional.of(getWrappedElement().getAttribute("value")).orElse(""); }
Source:
public double getTotalPopulationWeight() { START return (double) reservoir.getTotalPopulationCount(); END } you shouldn't need to cast to double here

Target:
public double getTotalPopulationWeight() { return reservoir.getTotalPopulationCount(); }
Source:
START public void draw(Batch batch, float parentAlpha) { END batch.setShader(shader); if (alpha == 0.0f) { super.setVisible(false); } else { super.setVisible(true); } if (lookData instanceof DroneVideoLookData) { lookData.draw(batch, alpha); } if (isLookVisible() && this.getDrawable() != null) { super.draw(batch, this.alpha); } batch.setShader(null); } Please synchronize it.

Target:
public synchronized void draw(Batch batch, float parentAlpha) { batch.setShader(shader); if (alpha == 0.0f) { super.setVisible(false); } else { super.setVisible(true); } if (lookData instanceof DroneVideoLookData) { lookData.draw(batch, alpha); } if (isLookVisible() && this.getDrawable() != null) { super.draw(batch, this.alpha); } batch.setShader(null); }
Source:
protected boolean canSearchUsersAndGroups(NuxeoPrincipal principal) { if (principal.isAdministrator() || principal.isMemberOf(POWER_USERS_GROUP)) { return true; } UserManager um = Framework.getService(UserManager.class); List<String> adminGroups = um.getAdministratorsGroups(); START return adminGroups.stream().anyMatch(principal::isMemberOf); END } Isn't this redundant with `principal.isAdministrator()`, knowing that `UserManager#makePrincipal` goes through `NuxeoPrincipalImpl#setVirtualGroups` and `NuxeoPrincipalImpl#updateAllGroups`? See https://github.com/nuxeo/nuxeo/blob/master/nuxeo-services/nuxeo-platform-usermanager-api/src/main/java/org/nuxeo/ecm/platform/usermanager/NuxeoPrincipalImpl.java#L367.

Target:
protected boolean canSearchUsersAndGroups(NuxeoPrincipal principal) { return principal.isAdministrator() || principal.isMemberOf(POWER_USERS_GROUP); }
Source:
void setSucceeded() { START this.succeeded = true; END this.done = true; } minor: `this` not required anywhere.

Target:
void setSucceeded() { succeeded = true; done = true; }
Source:
public void addPapyrusTable(Table tableInstance) { START getResource().getContents().add(tableInstance); END } Might not work with controlled models

Target:
public void addPapyrusTable(Table tableInstance) { if (getResource() != null) { getResource().getContents().add(tableInstance); } }
Source:
public <T> ReportedConfigurations add(ReportedConfigurationType type, T actual, T expected, boolean inSync) { String actualValue = actual != null ? actual.toString() : "null"; START String expectedValue = expected != null ? expected.toString() : "null"; END reportedConfigurationList.add(new ReportedConfiguration(type, actualValue, expectedValue, inSync)); return this; } Done

Target:
public <T> ReportedConfigurations add(ReportedConfigurationType type, T actual, T expected, boolean inSync) { String actualValue = actual == null ? null : actual.toString(); String expectedValue = expected == null ? null : expected.toString(); reportedConfigurationList.add(new ReportedConfiguration(type, actualValue, expectedValue, inSync)); return this; }
Source:
public String toString() { StringBuilder sb = new StringBuilder("MaprDBJsonRecordReader[Table="); START if (table != null) { END sb.append(table.getPath()); } if (reader != null) { sb.append(", Document ID=") .append(IdCodec.asString(reader.getId())); } sb.append(", reader=") .append(reader) .append(']'); return sb.toString(); } For the case when `table` is null, the string will be formed incorrectly - `Table=` should be appended only if `table != null`

Target:
public String toString() { StringBuilder sb = new StringBuilder("MaprDBJsonRecordReader[Table=") .append(table != null ? table.getPath() : null); if (reader != null) { sb.append(", Document ID=") .append(IdCodec.asString(reader.getId())); } sb.append(", reader=") .append(reader) .append(']'); return sb.toString(); }
Source:
private static Statistics stringColumnStats(String minimum, String maximum) { START Statistics.Builder builder = Statistics.getBuilderForReading(new PrimitiveType(Type.Repetition.OPTIONAL, PrimitiveType.PrimitiveTypeName.BINARY, "testFile", OriginalType.UTF8)); END builder.withMin(minimum.getBytes()) .withMax(maximum.getBytes()) .withNumNulls(0); return builder.build(); } You can import `OPTIONAL`, `BINARY`, `UTF8`.

Target:
private static Statistics stringColumnStats(String minimum, String maximum) { Statistics.Builder builder = Statistics.getBuilderForReading(new PrimitiveType(OPTIONAL, BINARY, "testFile", UTF8)); builder.withMin(minimum.getBytes()) .withMax(maximum.getBytes()) .withNumNulls(0); return builder.build(); }
Source:
START private static Dsn resolveDsn(Lookup lookup, @Nullable String dsn) { END try { if (Util.isNullOrEmpty(dsn)) { dsn = Dsn.dsnFrom(lookup); } return new Dsn(dsn); } catch (Exception e) { logger.error("Error creating valid DSN from: '{}'.", dsn, e); throw e; } } Does this belong in `SentryOptions`? In other SDKs we have it more as a POJO type of class. Perhaps these methods could be pulled out into an internal helper class.

Target:
private static String resolveDsn(Lookup lookup, @Nullable String dsn) { try { if (Util.isNullOrEmpty(dsn)) { dsn = Dsn.dsnFrom(lookup); } return dsn; } catch (Exception e) { logger.error("Error creating valid DSN from: '{}'.", dsn, e); throw e; } }
Source:
public void reset(WritableByteChannel channel) throws IOException { START this.channel = channel; END } This code should be: ``` this.channel.close(); ```

Target:
public void reset(WritableByteChannel channel) throws IOException { this.channel.close(); this.channel = channel; }
Source:
public void stop(ComponentContext context) throws InterruptedException { START super.stop(context); END providers.values().forEach(KeyValueStoreProvider::close); } You should do the close before calling `super.stop`

Target:
public void stop(ComponentContext context) throws InterruptedException { providers.values().forEach(KeyValueStoreProvider::close); super.stop(context); }
Source:
void foo1() START throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, END BadPaddingException { byte[] bytes = "111".getBytes("UTF-8"); random.nextBytes(bytes); IvParameterSpec iv = new IvParameterSpec(bytes); // Compliant } What does this list of exceptions bring to the test? Can't we replace it with `throws Exception`?

Target:
void foo1() throws Exception { byte[] bytes = "111".getBytes("UTF-8"); random.nextBytes(bytes); IvParameterSpec iv = new IvParameterSpec(bytes); // Compliant }
Source:
private static PathAddress createDeploymentAddressPrefix(DeploymentUnit deploymentUnit) { if (deploymentUnit.getParent() == null) { return PathAddress.pathAddress(DEPLOYMENT, deploymentUnit.getAttachment(Attachments.MANAGEMENT_NAME)); } else { START return createDeploymentAddressPrefix(deploymentUnit.getParent()).append(SUBDEPLOYMENT, deploymentUnit.getAttachment(Attachments.MANAGEMENT_NAME)); END } } I'm pretty sure removing the change to this line will help fix the test failure problem. I don't think a subdeployment has this attachment, and in any case a subdeployment never has a management name that is different from deploymentUnit.getName(). A user can't assign a management name to a subdeployment as it's an internal part of the top level deployment, not something independently added to the server config.

Target:
private static PathAddress createDeploymentAddressPrefix(DeploymentUnit deploymentUnit) { if (deploymentUnit.getParent() == null) { return PathAddress.pathAddress(DEPLOYMENT, deploymentUnit.getAttachment(Attachments.MANAGEMENT_NAME)); } else { return createDeploymentAddressPrefix(deploymentUnit.getParent()).append(SUBDEPLOYMENT, deploymentUnit.getName()); } }
Source:
START void addUnloadedPlayer(String id, EntityData.PlayerStore unloadedPlayer) { END unloadedPlayers.put(id, unloadedPlayer); } More likely meaningless access changes

Target:
public void addUnloadedPlayer(String id, EntityData.PlayerStore unloadedPlayer) { unloadedPlayers.put(id, unloadedPlayer); }
Source:
public void stop() { if (isStarted.compareAndSet(true, false)) { stopQueue(); dispatcher.stop(); } START if (config.getPersistentQueueMode() == PersistentQueueMode.STICKY_POLLING) { END reaper.stop(); } } I would always call `stop` regardless of the mode (and make sure that `stop` is a no-op if it wasn't started). That way, as we implement other modes, we don't have to update that piece of code.

Target:
public void stop() { if (isStarted.compareAndSet(true, false)) { stopQueue(); dispatcher.stop(); } reaper.stop(); }
Source:
public static synchronized void setupRetentionPolicyMgr(int numThreads) { if (s_retentionPolicyMgr == null) { s_retentionPolicyMgr = new RetentionPolicyMgr(numThreads); } else if (s_retentionPolicyMgr.getRetentionThreadPoolSize() != numThreads) { START s_retentionPolicyMgr.updateThreadPoolSize(numThreads); END } } Why not just always call the update and have the update either apply the change if it is different or ignore it

Target:
public static synchronized void setupRetentionPolicyMgr(int numThreads) { if (s_retentionPolicyMgr == null) { s_retentionPolicyMgr = new RetentionPolicyMgr(numThreads); } else { s_retentionPolicyMgr.updateThreadPoolSize(numThreads); } }
Source:
public String toString() { START return String.valueOf(value); END } Why can't you just return value here?

Target:
public String toString() { return value; }
Source:
public List<Concept> getPossibleValues() { try { return Context.getConceptService().getConceptsByName(""); } catch (Exception e) { START logger.error("Error", e); END } //pass return Collections.emptyList(); } Change this to `log`

Target:
public List<Concept> getPossibleValues() { try { return Context.getConceptService().getConceptsByName(""); } catch (Exception e) { log.error("Error", e); } //pass return Collections.emptyList(); }
Source:
public String getIssuerName() { START issuerName = StringUtils.isEmpty(x509Cert.getIssuerDN().getName()) ? EMPTY_FIELD END : x509Cert.getIssuerDN().getName(); return issuerName; } Do everything in the CertificateManagerServiceImpl . Use the certificate class just for sending to/from information on the View.

Target:
public String getIssuerName() { return issuerName; }
Source:
START TestShardConsumerSubscriber(RecordsPublisher recordsPublisher, ExecutorService executorService, int bufferSize, END ShardConsumer shardConsumer, int readTimeoutsToIgnoreBeforeWarning) { super(recordsPublisher, executorService, bufferSize, shardConsumer, readTimeoutsToIgnoreBeforeWarning); this.recordsPublisher = recordsPublisher; this.executorService = executorService; this.bufferSize = bufferSize; this.shardConsumer = shardConsumer; } I am not able to see this constructor being used? There is no need to chain the constructors.

Target:
TestShardConsumerSubscriber(RecordsPublisher recordsPublisher, ExecutorService executorService, int bufferSize, ShardConsumer shardConsumer, // Setup test expectations int readTimeoutsToIgnoreBeforeWarning) { super(recordsPublisher, executorService, bufferSize, shardConsumer, readTimeoutsToIgnoreBeforeWarning); }
Source:
public String getText(final Object element) { Item item = (Item) element; START String label = item.getLabel(); if (label == null || label.trim().length() == 0) { label = item.getViewpoint().getName(); } END return label; } This should be handled in item.getLabel()

Target:
public String getText(final Object element) { Item item = (Item) element; return item.getLabel(); }