auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public MetadataHashAggPOP(@JsonProperty("child") PhysicalOperator child, @JsonProperty("context") MetadataAggregateContext context, @JsonProperty("phase") OperatorPhase phase) { super(child, phase, context.groupByExpressions(), Collections.emptyList(), 1.0F); START this.context = context; END this.phase = phase; Preconditions.checkArgument(context.createNewAggregations(), "Hash aggregate for metadata collecting should be used only for creating new aggregations."); } Please move this check before assigning the variables.

Target:
public MetadataHashAggPOP(@JsonProperty("child") PhysicalOperator child, @JsonProperty("context") MetadataAggregateContext context, @JsonProperty("phase") OperatorPhase phase) { super(child, phase, context.groupByExpressions(), Collections.emptyList(), 1.0F); Preconditions.checkArgument(context.createNewAggregations(), "Hash aggregate for metadata collecting should be used only for creating new aggregations."); this.context = context; this.phase = phase; }
Source:
private void saveProcess(Process process) { try { serviceManager.getProcessService().save(process); } catch (DataException e) { START Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "Error while saving process: " + process.getTitle(), e); END logger.error(KITODO_SCRIPT_FIELD + "Error while saving process: " + process.getTitle(), e); } } Please first log the error and then inform the user.

Target:
private void saveProcess(Process process) { try { serviceManager.getProcessService().save(process); } catch (DataException e) { logger.error(KITODO_SCRIPT_FIELD + "Error while saving process: " + process.getTitle(), e); Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "Error while saving process: " + process.getTitle(), e); } }
Source:
START private String toHexString(QuantileDigest qdigest) END { return new SqlVarbinary(qdigest.serialize().getBytes()).toString().replaceAll("\\s+", " "); } private static

Target:
private static String toHexString(QuantileDigest qdigest) { return new SqlVarbinary(qdigest.serialize().getBytes()).toString().replaceAll("\\s+", " "); }
Source:
START public String getHeader(){ END return selectedPageHeader.getText(); } this should be private method

Target:
private String getHeader(){ return selectedPageHeader.getText(); }
Source:
public void onImportUserFromLDAP(LDAPObject ldapUser, UserModel user, RealmModel realm, boolean isCreate) { String userModelAttrName = getUserModelAttribute(); String attributeValue = getAttributeValue(); Property<Object> userModelProperty = userModelProperties.get(userModelAttrName.toLowerCase()); if (userModelProperty != null) { START checkDuplicateEmail(userModelAttrName, attributeValue, realm, ldapProvider.getSession(), user); END setPropertyOnUserModel(userModelProperty, user, attributeValue); } else { user.setAttribute(userModelAttrName, Arrays.asList(attributeValue)); } } Does it have any sense to check for duplicated email here? IMO I am not seeing much sense to have hardcoded username or email same for all users? So I would just delete this line and also completely delete the methods "checkDuplicateEmail" and "checkDuplicateUsername" . And you can instead implement method on the HardcodedAttributeMapperFactory "validateConfiguration" and throw an error in case that "username" or "email" was configured as user model attribute.

Target:
public void onImportUserFromLDAP(LDAPObject ldapUser, UserModel user, RealmModel realm, boolean isCreate) { String userModelAttrName = getUserModelAttribute(); String attributeValue = getAttributeValue(); Property<Object> userModelProperty = userModelProperties.get(userModelAttrName.toLowerCase()); if (userModelProperty != null) { setPropertyOnUserModel(userModelProperty, user, attributeValue); } else { user.setAttribute(userModelAttrName, Arrays.asList(attributeValue)); } }
Source:
START public Boolean delete( ProjectName projectName ) END { return callWithContext( () -> { final Boolean result = doDelete( projectName ); LOG.info( "Project deleted: " + projectName ); return result; } ); } boolean instead of Boolean

Target:
public boolean delete( ProjectName projectName ) { return callWithContext( () -> { final boolean result = doDelete( projectName ); LOG.info( "Project deleted: " + projectName ); return result; } ); }
Source:
public static void startServerInstance(File dataDir, ServerCnxnFactory factory, String hostPort) throws IOException, START InterruptedException, KeeperException.NoNodeException { END final int port = getPort(hostPort); LOG.info("STARTING server instance 127.0.0.1:{}", port); ZooKeeperServer zks = new ZooKeeperServer(dataDir, dataDir, 3000); factory.startup(zks); Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp( "127.0.0.1:" + port, CONNECTION_TIMEOUT, factory.isSecure())); } this isn't needed anymore right?

Target:
public static void startServerInstance(File dataDir, ServerCnxnFactory factory, String hostPort) throws IOException, InterruptedException { final int port = getPort(hostPort); LOG.info("STARTING server instance 127.0.0.1:{}", port); ZooKeeperServer zks = new ZooKeeperServer(dataDir, dataDir, 3000); factory.startup(zks); Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp( "127.0.0.1:" + port, CONNECTION_TIMEOUT, factory.isSecure())); }
Source:
public void shouldShowAllMusicsAsHTTP() { MockHttpResult mockHttpResult = new MockHttpResult(); controller = new MusicController(dao, userInfo, mockHttpResult, validator, musics); when(dao.listAll()).thenReturn(Arrays.asList(music)); controller.showAllMusicsAsHTTP(); assertEquals("<p class=\"content\">"+ Arrays.asList(music).toString()+"</p>", mockHttpResult.getBody()); START } END If you want, you can change to use hamcrest here too. The method `Matchers.is` compare if two objects are equals.

Target:
public void shouldShowAllMusicsAsHTTP() { MockHttpResult mockHttpResult = new MockHttpResult(); controller = new MusicController(dao, userInfo, mockHttpResult, validator, musics); when(dao.listAll()).thenReturn(Arrays.asList(music)); controller.showAllMusicsAsHTTP(); assertThat(mockHttpResult.getBody(), is("<p class=\"content\">"+ Arrays.asList(music).toString()+"</p>")); }
Source:
public AttributeValueSearch(IAttributeType attributeType, String attributeValue) { this.attributeType = attributeType; this.attributeValue = attributeValue; START Conditions.checkNotNull(attributeType, "attributeType"); Conditions.checkNotNullOrEmpty(attributeValue, "attributeValue"); END } wouldn't you want the conditions check prior to assignments?

Target:
public AttributeValueSearch(IAttributeType attributeType, String attributeValue) { Conditions.checkNotNull(attributeType, "attributeType"); Conditions.checkNotNullOrEmpty(attributeValue, "attributeValue"); this.attributeType = attributeType; this.attributeValue = attributeValue; }
Source:
public ListenerContainerIdleEvent(Object source, long idleTime, @Nullable String id, String... queueNames) { super(source); START this.idleTime = Duration.ofMillis(idleTime); END this.listenerId = id; this.queueNames = Arrays.asList(queueNames); } What made you to wrap, when you still use a simple long afterwards?

Target:
public ListenerContainerIdleEvent(Object source, long idleTime, @Nullable String id, String... queueNames) { super(source); this.idleTime = idleTime; this.listenerId = id; this.queueNames = Arrays.asList(queueNames); }
Source:
public static XARecoveryModule getRegisteredXARecoveryModule () { if (registeredXARecoveryModule == null) { RecoveryManager recMan = RecoveryManager.manager(); Vector recoveryModules = recMan.getModules(); if (recoveryModules != null) { Enumeration modules = recoveryModules.elements(); while (modules.hasMoreElements()) { RecoveryModule m = (RecoveryModule) modules.nextElement(); if (m instanceof XARecoveryModule) { START registeredXARecoveryModule = (XARecoveryModule) m; END } } } } return registeredXARecoveryModule; } you should break out of the loop early after finding the target module

Target:
public static XARecoveryModule getRegisteredXARecoveryModule () { if (registeredXARecoveryModule == null) { RecoveryManager recMan = RecoveryManager.manager(); Vector recoveryModules = recMan.getModules(); if (recoveryModules != null) { Enumeration modules = recoveryModules.elements(); while (modules.hasMoreElements()) { RecoveryModule m = (RecoveryModule) modules.nextElement(); if (m instanceof XARecoveryModule) { registeredXARecoveryModule = (XARecoveryModule) m; break; } } } } return registeredXARecoveryModule; }
Source:
public String getUrl() { START return PluginImpl.getInstance().getServer(serverName).getConfig().getGerritFrontEndUrlFor(tEvent); END } possible NPE

Target:
public String getUrl() { return url; }
Source:
public void testBoundarySignalProcessInstance() throws Exception { Long processInstanceId = processClient.startProcess(CONTAINER_ID, PROCESS_ID_BOUNDARY_SIGNAL_PROCESS); assertNotNull(processInstanceId); assertTrue(processInstanceId.longValue() > 0); try { START checkAvailableBoundarySignals(CONTAINER_ID, processInstanceId); END } catch (Exception e){ processClient.abortProcessInstance(CONTAINER_ID, processInstanceId); e.printStackTrace(); fail(e.getMessage()); } } Please move abortProcessInstance into the final statement, it should be done in any case. Also please delete e.printStackTrace(); - it doesn't bring any value. Also please delete fail(e.getMessage()); - unexpected exceptions should be thrown out of test method, JUnit will handle it as a failing test, printing exception with stacktrace to the log.

Target:
public void testBoundarySignalProcessInstance() throws Exception { Long processInstanceId = processClient.startProcess(CONTAINER_ID, PROCESS_ID_BOUNDARY_SIGNAL_PROCESS); assertNotNull(processInstanceId); assertTrue(processInstanceId.longValue() > 0); try { checkAvailableBoundarySignals(CONTAINER_ID, processInstanceId); } finally { processClient.abortProcessInstance(CONTAINER_ID, processInstanceId); } }
Source:
private void validateAppConfig(String fileName) throws Exception { String appsDir = getAppsDirectory(); if (appsDir.equalsIgnoreCase("apps") && !isAppConfiguredInSourceServerXml(fileName)) { // add application configuration applicationXml.createWebApplicationElement(fileName); } START else if (appsDir.equalsIgnoreCase("dropins") && isAnyAppConfiguredInSourceServerXml()) END throw new MojoExecutionException(messages.getString("error.install.app.dropins.directory")); } why not calling isAppConfiguredInSourceServerXml(fileName) to make sure the app installed to the dropins location is not configured?

Target:
private void validateAppConfig(String fileName) throws Exception { String appsDir = getAppsDirectory(); if (appsDir.equalsIgnoreCase("apps") && !isAppConfiguredInSourceServerXml(fileName)) { // add application configuration applicationXml.createWebApplicationElement(fileName); } else if (appsDir.equalsIgnoreCase("dropins") && isAppConfiguredInSourceServerXml(fileName)) throw new MojoExecutionException(messages.getString("error.install.app.dropins.directory")); }
Source:
START static RequestContextDataHolder getRequestContext(Context ctx) { END return ctx.getOrDefault(REQUEST_CONTEXT_DATA_HOLDER, null); } Please add `private` modifier

Target:
private static RequestContextDataHolder getRequestContext(Context ctx) { return ctx.getOrDefault(REQUEST_CONTEXT_DATA_HOLDER, null); }
Source:
public long getNumberOfImagesInStorageDomain(Guid storageDomainId) { START MapSqlParameterSource params = getCustomMapSqlParameterSource().addValue("storage_domain_id", storageDomainId); END return getCallsHandler().executeRead("GetNumberOfImagesInStorageDomain", getLongMapper(), params); } I'd inline this to conform with the rest of the class.

Target:
public long getNumberOfImagesInStorageDomain(Guid storageDomainId) { return getCallsHandler().executeRead("GetNumberOfImagesInStorageDomain", getLongMapper(), getCustomMapSqlParameterSource().addValue("storage_domain_id", storageDomainId)); }
Source:
public TestObjectAsync() { try { START Thread.sleep(100); END Thread.sleep(100); counter = 1; } catch (InterruptedException ie) { throw new RuntimeException(ie); } } Is it really necessary to wait 100 milliseconds? Why not `Thread.sleep(1)`. Why not `Thread.yield()`?

Target:
public TestObjectAsync() { try { Thread.sleep(1); Thread.sleep(1); counter = 1; } catch (InterruptedException ie) { throw new RuntimeException(ie); } }
Source:
private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) { Field field = getField(beanClass, beanProp.getName()); return field != null ? field.getAnnotationsByType(Optional.class).length > 0 START || beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0 END : beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0; } Maybe `beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0` should be checked before calling getField ? Method getField modifies field via reflection and optionally recursively calls itself, so it could be costly.

Target:
private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) { if (beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0) { return true; } Field field = getField(beanClass, beanProp.getName()); return field != null && field.getAnnotationsByType(Optional.class).length > 0; }
Source:
public int getImageselector () { return imageSelectorIndex; START } END Why is this method required? Didn't see it used anywhere in the code

Target:
int getImageselector () { return imageSelectorIndex; }
Source:
public InputStream getInputStream(FileHeader entry) throws IOException { if (entry == null) { return null; } InputStream inputStream = getEntryData(entry).getInputStream(); if (entry.getMethod() == ZipEntry.DEFLATED) { START inputStream = new ZipInflaterInputStream(inputStream, new Inflater(true), END (int) entry.getSize()); } return inputStream; } I don't think we want to pass in an `Inflater` and than have `ZipInflaterInputStream` call `end()` on it.

Target:
public InputStream getInputStream(FileHeader entry) throws IOException { if (entry == null) { return null; } InputStream inputStream = getEntryData(entry).getInputStream(); if (entry.getMethod() == ZipEntry.DEFLATED) { inputStream = new ZipInflaterInputStream(inputStream, (int) entry.getSize()); } return inputStream; }
Source:
private org.eclipse.swt.graphics.Image createImage() { org.eclipse.swt.graphics.Image newImage; RenderedImage image = renderManager.getImage(); START this.backBufferTrsf=renderManager.getMapInternal().getViewportModel().worldToScreenTransform(); END if (image != null) newImage = AWTSWTImageUtils.createSWTImage(image, false); else { newImage = new Image(getDisplay(), getWidth(), getHeight()); } return newImage; } Can you explain the idea behind storing transformation here and not anywhere else (at the very beginning of repaint())? Is it worth to keep this information and to compare it within getDoubleBufferGraphics() rather using the up-to-date viewportModel Transformation. is it because of a non-atomar opration betwenn getImage() and getDoubleBufferGraphics() calls?

Target:
private org.eclipse.swt.graphics.Image createImage() { org.eclipse.swt.graphics.Image newImage; RenderedImage image = renderManager.getImage(); if (image != null) newImage = AWTSWTImageUtils.createSWTImage(image, false); else { newImage = new Image(getDisplay(), getWidth(), getHeight()); } return newImage; }
Source:
public VirtualMachine getCurrentMachineBuild(ITmfEvent event) { VirtualMachine machine = innerGetCurrentMachine(event); if (machine == null) { synchronized (fStateSystem) { String hostId = event.getTrace().getHostId(); START machine = createMachine(fStateSystem, event.getTimestamp().toNanos(), hostId, event.getTrace().getName()); END fKnownMachines.put(hostId, machine); } } return machine; } this is nullable

Target:
public VirtualMachine getCurrentMachineBuild(ITmfEvent event) { VirtualMachine machine = innerGetCurrentMachine(event); if (machine == null) { synchronized (fStateSystem) { String hostId = event.getTrace().getHostId(); machine = createMachine(fStateSystem, event.getTimestamp().toNanos(), hostId, String.valueOf(event.getTrace().getName())); fKnownMachines.put(hostId, machine); } } return machine; }
Source:
public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && isDeterministic(expression) && !mayReturnNullOnNonNullInput(expression) && START !isDynamicFilter(expression)) { END ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getType() == ComparisonExpressionType.EQUAL) { // We should only consider equalities that have distinct left and right components return !comparison.getLeft().equals(comparison.getRight()); } } return false; }; } Why do we need it here?

Target:
public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && isDeterministic(expression) && !mayReturnNullOnNonNullInput(expression)) { ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getType() == ComparisonExpressionType.EQUAL) { // We should only consider equalities that have distinct left and right components return !comparison.getLeft().equals(comparison.getRight()); } } return false; }; }
Source:
private void updateGroup(final TupleBatch tb, final int row, final Object[] curAggStates) throws DbException { for (int agg = 0; agg < aggregators.length; ++agg) { if (!(aggregators[agg] .getClass() .getName() START .equals(StatefulUserDefinedAggregator.class.getName()))) { END aggregators[agg].addRow(tb, row, curAggStates[agg]); } } } instanceof

Target:
private void updateGroup(final TupleBatch tb, final int row, final Object[] curAggStates) throws DbException { for (int agg = 0; agg < aggregators.length; ++agg) { if (!(aggregators[agg] instanceof StatefulUserDefinedAggregator)) { aggregators[agg].addRow(tb, row, curAggStates[agg]); } } }
Source:
protected void update(float delta) { int lengthInterpretation; try { START lengthInterpretation = length == null ? 0 : length.interpretInteger(sprite); END } catch (InterpretationException interpretationException) { lengthInterpretation = 0; Log.d(getClass().getSimpleName(), "Formula interpretation for this specific Brick failed.", interpretationException); } this.sprite.runningStitch.activateStitching(sprite, new SimpleRunningStitch(sprite, lengthInterpretation)); } Please apply same changes as requested in first review here.

Target:
protected void update(float delta) { int lengthInterpretation = 0; try { if (length != null) { lengthInterpretation = length.interpretInteger(sprite); } } catch (InterpretationException interpretationException) { lengthInterpretation = 0; Log.d(getClass().getSimpleName(), "Formula interpretation for this specific Brick failed.", interpretationException); } this.sprite.runningStitch.activateStitching(sprite, new SimpleRunningStitch(sprite, lengthInterpretation)); }
Source:
protected void processSpanImpl(Span span, Map<String, String[]> servletRequestParameters) { long sum = 0; for (String weaselParameterToSum : weaselParametersToSum) { final Long timing = parsedLongOrNull(getParameterValueOrNull(weaselParameterToSum, servletRequestParameters)); if (timing == null) { START discardSpan(span); END return; } else { sum += timing; } } span.setTag(TIMING_RESOURCE, sum); } remove line

Target:
protected void processSpanImpl(Span span, Map<String, String[]> servletRequestParameters) { long sum = 0; for (String weaselParameterToSum : weaselParametersToSum) { final Long timing = parsedLongOrNull(getParameterValueOrNull(weaselParameterToSum, servletRequestParameters)); if (timing == null) { return; } else { sum += timing; } } span.setTag(TIMING_RESOURCE, sum); }
Source:
private void close(Path path) throws IOException { Path directoryWhereGeneratedArtifactsWasPlaced = path.getParent(); try (Stream<Path> s = Files.list(directoryWhereGeneratedArtifactsWasPlaced)) { START s.filter(p -> !Files.isDirectory(p)).map(ThrowingFunction.unchecked(p -> p)) END .forEach(ThrowingConsumer.unchecked(Files::delete)); } } `.map(ThrowingFunction.unchecked(p -> p))` unnecessary

Target:
private void close(Path path) throws IOException { Path directoryWhereGeneratedArtifactsWasPlaced = path.getParent(); try (Stream<Path> s = Files.list(directoryWhereGeneratedArtifactsWasPlaced)) { s.filter(p -> !Files.isDirectory(p)).forEach(ThrowingConsumer.unchecked(Files::delete)); } }
Source:
public void hashcodeVerifyEqualsContract() { START EqualsVerifier.forClass(MessageReference.class).suppress(Warning.NONFINAL_FIELDS).verify(); END } As a general rule: If you're unsure whether or not to suppress a warning, don't! You discovered the principal problem of mutable objects. The easy fix is to use [immutable objects](http://en.wikipedia.org/wiki/Immutable_object) whenever possible. `MessageReference` looks like it could be easily made immutable. So you should definitely do that instead of suppressing the warning.

Target:
public void hashcodeVerifyEqualsContract() { EqualsVerifier.forClass(MessageReference.class).verify(); }
Source:
public HttpRequest setUri(String uri) { ObjectUtil.checkNotNull(uri, "uri"); START this.uri = uri; END return this; } nit: you can merge both lines above as `checkNotNull` will return the given argument

Target:
public HttpRequest setUri(String uri) { this.uri = ObjectUtil.checkNotNull(uri, "uri"); return this; }
Source:
START protected ServiceKeyAuthentication(@Provider Supplier<Credentials> creds) { END this.creds = creds; } Make all Guice constructors package private by removing the method modifier. Just: ``` java @Inject ServiceKeyAuthentication(@Provider Supplier<Credentials> creds) { ```

Target:
ServiceKeyAuthentication(@Provider Supplier<Credentials> creds) { this.creds = creds; }
Source:
protected int countChildrenOf(IResource checkResource) throws CoreException { if (checkResource.getType() == IResource.FILE) { return 1; } int count = 0; if (checkResource.isAccessible()) { for (IResource START resource : END ((IContainer) checkResource).members()) { count += countChildrenOf(resource); } } return count; } rename 'child'

Target:
protected int countChildrenOf(IResource checkResource) throws CoreException { if (checkResource.getType() == IResource.FILE) { return 1; } int count = 0; if (checkResource.isAccessible()) { for (IResource child : ((IContainer) checkResource).members()) { count += countChildrenOf(child); } } return count; }
Source:
public String getAppFolderToMonitor() { START if (folder == null) { END File f = new File("Applications"); folder = f.getAbsolutePath(); } return folder; } If this is null, can't we keep it null? That way you can disable the folder watching if you're not interested in it. The `startMonitor` method below also checks for the return value of this method being `null`. I guess `null` would then also be the default.

Target:
public String getAppFolderToMonitor() { return folder; }
Source:
private static void count(Object inputBase, long inputAddress, int inputSize, int[] counts) { long input = inputAddress; Arrays.fill(counts, 0); START if (inputSize != 0) { END for (int i = 0; i < inputSize; i++) { int symbol = UNSAFE.getByte(inputBase, input) & 0xFF; input++; counts[symbol]++; } } } I don't think you need this

Target:
private static void count(Object inputBase, long inputAddress, int inputSize, int[] counts) { long input = inputAddress; Arrays.fill(counts, 0); for (int i = 0; i < inputSize; i++) { int symbol = UNSAFE.getByte(inputBase, input) & 0xFF; input++; counts[symbol]++; } }
Source:
public void submit(List<LuceneWork> workList, IndexingMonitor monitor) { Changeset changeset = new Changeset( workList, Thread.currentThread(), monitor ); transferQueue.add( changeset ); wakeUpConsumer(); boolean interrupted = false; while ( ! changeset.isProcessed() ) { LockSupport.park(); if ( Thread.interrupted() ) { START interrupted = true; END } } if ( interrupted ) { Thread.currentThread().interrupt(); } } If it's interrupted you might want to return too, rather than getting stuck in another park.

Target:
public void submit(List<LuceneWork> workList, IndexingMonitor monitor) { Changeset changeset = new Changeset( workList, Thread.currentThread(), monitor ); transferQueue.add( changeset ); wakeUpConsumer(); boolean interrupted = false; while ( ! changeset.isProcessed() && ! interrupted ) { LockSupport.park(); if ( Thread.interrupted() ) { interrupted = true; } } if ( interrupted ) { Thread.currentThread().interrupt(); } }
Source:
public void setHttpService(HttpService httpService) { START logger.info("setHttpService called"); END this.httpService = httpService; } could we directly reduce this to debug level?

Target:
public void setHttpService(HttpService httpService) { logger.debug("setHttpService called"); this.httpService = httpService; }
Source:
public boolean isInternal() { return getParentNode() .filter(parent -> parent instanceof Name) .map(parent -> (Name) parent) .flatMap(Name::getQualifier) START .map(parentNameQualifier -> parentNameQualifier == this) END .orElse(false); } Oh, yes, `Name` can only be qualified by another `Name`. I think it's a safe assumption to make :-)

Target:
public boolean isInternal() { return getParentNode() .filter(parent -> parent instanceof Name) .isPresent(); }
Source:
private void logStart() { log(3, "Running test " + m_testName + " on " + m_classMap.size() + " " + " classes, " START + " included groups:[" + Strings.mapToString(m_xmlMethodSelector.getIncludedGroups()) END + "] excluded groups:[" + Strings.mapToString(m_xmlMethodSelector.getExcludedGroups()) + "]"); if (getVerbose() >= 3) { for (ITestClass tc : m_classMap.values()) { ((TestClass) tc).dump(); } } } `valueOf` looks more appropriate (like `String#valueOf`)

Target:
private void logStart() { log(3, "Running test " + m_testName + " on " + m_classMap.size() + " " + " classes, " + " included groups:[" + Strings.valueOf(m_xmlMethodSelector.getIncludedGroups()) + "] excluded groups:[" + Strings.valueOf(m_xmlMethodSelector.getExcludedGroups()) + "]"); if (getVerbose() >= 3) { for (ITestClass tc : m_classMap.values()) { ((TestClass) tc).dump(); } } }
Source:
public NutchJob(Configuration conf) throws IOException { START super(conf, "NutchJob"); END } Does this mean that every Job will be named ```"NutchJob"```?

Target:
public NutchJob(Configuration conf) { super(conf, NutchJob.class); }
Source:
private void loadMachineUUID() { if START (System.getProperty(PROP_UUID) != END null) return; String uuid = loadExistingUUID(); if (uuid == null) { uuid = UUID.randomUUID().toString(); saveUUID(uuid); } EnvironmentInfo environment = environmentTracker.getService(); if (environment != null) { environment.setProperty(PROP_UUID, uuid); } else { System.setProperty(PROP_UUID, uuid); } } Should use BundleContext.getProperty here, or the EnvonmentInfo service.

Target:
private void loadMachineUUID() { EnvironmentInfo environment = environmentTracker.getService(); if (environment != null) { if (environment.getProperty(PROP_UUID) != null) return; } String uuid = loadExistingUUID(); if (uuid == null) { uuid = UUID.randomUUID().toString(); saveUUID(uuid); } if (environment != null) { environment.setProperty(PROP_UUID, uuid); } else { System.setProperty(PROP_UUID, uuid); } }
Source:
public synchronized boolean retry(ITestResult result) { if (currentTry < maxreruntimes) { START ++currentTry; END return true; } return false; } Maybe we can use `AtomicInteger` and get rid of `synchronized` keyword ? On a side note, I noticed that you haven't enabled the `parallel` attribute on `@DataProvider` annotation. So you can completely get rid of the need for ensuring Thread safety.

Target:
public boolean retry(ITestResult result) { if (currentTry < maxreruntimes) { ++currentTry; return true; } return false; }
Source:
public Statistics<T> visitIntConstant(ValueExpressions.IntExpression expr, Void value) throws RuntimeException { START return (Statistics<T>)getStatistics(expr.getInt()); END } It was much nicer when we did not have to explicitly cast everywhere to `(Statistics<T>)`. Please consider re-working this part your changes.

Target:
public Statistics<T> visitIntConstant(ValueExpressions.IntExpression expr, Void value) throws RuntimeException { return getStatistics(expr.getInt()); }
Source:
public ServiceDate getEnd() { START return end == UNBOUNDED_END ? null : end; END } It might even be more readable to export the symbolic constants outside the class, instead of null. Either way is fine. It might be clearer for debugging and logging.

Target:
public ServiceDate getEnd() { return end; }
Source:
START public boolean END isLoggedIn() { return token != null && hub != null; } no public

Target:
public boolean isLoggedIn() { return token != null && user != null; }
Source:
START public void setBuildStatus(String buildStatus) { END StashBuildState overwrittenBuildState = null; try { overwrittenBuildState = StashBuildState.valueOf(buildStatus); } catch (Exception e) { // ignore unknown or null values } this.buildStatus = overwrittenBuildState; } The complete method could be stripped down to: ``` try { this.buildStatus = StashBuildState.valueOf(buildStatus); } catch (Exception e) { // ignore unknown or null values } ```

Target:
public void setBuildStatus(String buildStatus) { try { this.buildStatus = StashBuildState.valueOf(buildStatus); } catch (Exception e) { // ignore unknown or null values } }
Source:
public void preInit(FMLPreInitializationEvent evt) { RegistryHelper.useOtherModConfigFor(MODID, BCCore.MODID); BCSiliconConfig.preInit(); BCSiliconItems.preInit(); BCSiliconBlocks.preInit(); // Reload after all of the definitions have been created. START BCSiliconConfig.reloadConfig(EnumRestartRequirement.GAME); END NetworkRegistry.INSTANCE.registerGuiHandler(INSTANCE, BCSiliconProxy.getProxy()); BCSiliconProxy.getProxy().fmlPreInit(); } Put this in the config preinit please

Target:
public void preInit(FMLPreInitializationEvent evt) { RegistryHelper.useOtherModConfigFor(MODID, BCCore.MODID); BCSiliconConfig.preInit(); BCSiliconItems.preInit(); BCSiliconBlocks.preInit(); NetworkRegistry.INSTANCE.registerGuiHandler(INSTANCE, BCSiliconProxy.getProxy()); BCSiliconProxy.getProxy().fmlPreInit(); }
Source:
public Hash(HashType type){ this.type = type; try { digest = type.get(); } finally { START type.recycle(digest); END } } Recycling a digest to which we still have references (namely in the member variable`digest`) is bound to give problems at some point: another thread may obtain it by means of `HashType.get()` while we are still using it! If you insist on recycling digests, I guess this could be done in the finalizer of `Hash`. Note that the semantics of `finally` don't have anything to do with finalizers!

Target:
public Hash(HashType type){ this.type = type; digest = type.get(); }
Source:
private boolean validateExternalVnicProfileMapping() { START drMappingHelper.mapVnicProfiles(vmTemplateFromConfiguration.getInterfaces(), getParameters().getExternalVnicProfileMappings()); END final ValidationResult validationResult = externalVnicProfileMappingValidator.validateExternalVnicProfileMapping( getParameters().getExternalVnicProfileMappings(), getParameters().getClusterId()); return validate(validationResult); } the mapping is still performed before the validation. it should be after it

Target:
private boolean validateExternalVnicProfileMapping() { final ValidationResult validationResult = externalVnicProfileMappingValidator.validateExternalVnicProfileMapping( getParameters().getExternalVnicProfileMappings(), getParameters().getClusterId()); return validate(validationResult); }
Source:
public void serDeTest() { START doSerDeTest(Collections.emptyList()); END doSerDeTest(Arrays.asList("a", "b", "/signedId/abcdef")); } do we need a `null` case?

Target:
public void serDeTest() { doSerDeTest(null); doSerDeTest(Collections.emptyList()); doSerDeTest(Arrays.asList("a", "b", "/signedId/abcdef")); }
Source:
protected void buildVmVideoCards() { createInfo.add(VdsProperties.display, vm.getdisplay_type().toString()); // vnc,qxl createInfo.add(VdsProperties.num_of_monitors, START (new Integer(vm.getnum_of_monitors())).toString()); END } use String.valueOf(vm.getnum_of_monitors()) instead.

Target:
protected void buildVmVideoCards() { createInfo.add(VdsProperties.display, vm.getdisplay_type().toString()); // vnc,qxl createInfo.add(VdsProperties.num_of_monitors, String.valueOf(vm.getnum_of_monitors())); }
Source:
START String encode(String segment) { END return URL.encodeQueryString(type.replacePathSeparator(segment)); } [optional] maybe this method can be static and should be moved to end of the class

Target:
private String encode(String segment) { return URL.encodeQueryString(type.replacePathSeparator(segment)); }
Source:
public List<String> getStrongDependencies() { List<String> strongDependencies = new ArrayList<>(); START strongDependencies.add(A_U_D_preferredMail); END strongDependencies.add(A_U_D_ISMail); strongDependencies.add(A_U_D_publicAliasMails); strongDependencies.add(A_U_D_privateAliasMails); strongDependencies.add(A_U_D_o365EmailAddressesMU); return strongDependencies; } This code is duplicate. Moreover, repeated "add" operations are not necessary. You can use something like this: ``` return Arrays.asList( A_U_D_preferredMail, A_U_D_ISMail, A_U_D_publicAliasMails, A_U_D_privateAliasMails, A_U_D_o365EmailAddressesMU); ```

Target:
public List<String> getStrongDependencies() { return Arrays.asList( A_U_D_preferredMail, A_U_D_ISMail, A_U_D_publicAliasMails, A_U_D_privateAliasMails, A_U_D_o365EmailAddressesMU); }
Source:
boolean isCacheable() { START return true; END } `isCacheable` is now `true`? I guess this was supposed to be `false` for generic extractors. Or am I wrong?

Target:
boolean isCacheable() { return false; }
Source:
START protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile, END String keyAlgorithm, File keyFile, String keyPassword, KeyManagerFactory kmf, String keyStore) throws KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, IOException, CertificateException, KeyException, UnrecoverableKeyException { return buildKeyManagerFactory(toX509Certificates(certChainFile), keyAlgorithm, toPrivateKey(keyFile, keyPassword), keyPassword, kmf, keyStore); } It does not make sense to expose a protected method and mark it as @Deprecated from the beginning. Maybe you should remove the annotation and make it package-private ?

Target:
static KeyManagerFactory buildKeyManagerFactory(File certChainFile, String keyAlgorithm, File keyFile, String keyPassword, KeyManagerFactory kmf, String keyStore) throws KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, IOException, CertificateException, KeyException, UnrecoverableKeyException { return buildKeyManagerFactory(toX509Certificates(certChainFile), keyAlgorithm, toPrivateKey(keyFile, keyPassword), keyPassword, kmf, keyStore); }
Source:
public void testWrongPortConnection() throws Exception { BlockingChannel channel = new SSLBlockingChannel(hostName, sslPort + 1, new MetricRegistry(), 10000, 10000, 10000, 2000, sslSocketFactory, clientSSLConfig); try { // send request channel.connect(); fail("should have thrown!"); } catch (IOException e) { START assertTrue(e.getMessage().contains("Connection refused")); END } } It's probably a bad idea to be checking for exception messages in the first place.

Target:
public void testWrongPortConnection() throws Exception { BlockingChannel channel = new SSLBlockingChannel(hostName, sslPort + 1, new MetricRegistry(), 10000, 10000, 10000, 2000, sslSocketFactory, clientSSLConfig); try { // send request channel.connect(); fail("should have thrown!"); } catch (IOException e) { } }
Source:
public void notifyParameterChanged(String name) { if (!fParameterNames.contains(name)) { throw new RuntimeException(String.format(Messages.TmfAbstractAnalysisModule_InvalidParameter, name, getName())); } START synchronized (fParameters) { END Object oldValue = fParameters.get(name); Object value = getParameter(name); if ((value != null) && !(value.equals(oldValue))) { parameterChanged(name); } } } the .contains() should probably be in the synchronized block too

Target:
public void notifyParameterChanged(String name) { synchronized (fParameters) { if (!fParameterNames.contains(name)) { throw new RuntimeException(String.format(Messages.TmfAbstractAnalysisModule_InvalidParameter, name, getName())); } Object oldValue = fParameters.get(name); Object value = getParameter(name); if ((value != null) && !(value.equals(oldValue))) { parameterChanged(name); } } }
Source:
public void testUnrecognizedSpec() { when(authentication.getAttributes().get(any(String.class))).thenReturn("strong_two_factor"); spec.setAuthenticationMethod("weak_two_factor"); START assertTrue(this.spec.isSatisfiedBy(this.assertion)); END } Is this idiomatic? In fact expect that won't be true, it's just that will be interrupted before the assertTrue returns? Would be clearer to omit the assertTrue?

Target:
public void testUnrecognizedSpec() { when(authentication.getAttributes().get(any(String.class))).thenReturn("strong_two_factor"); spec.setAuthenticationMethod("weak_two_factor"); spec.isSatisfiedBy(this.assertion); }
Source:
START public static Bundle updateBundleConfig(Connection connection, Bundle bundle) END throws SQLException { final String sql = "UPDATE portti_view_bundle_seq SET config=? WHERE bundle_id=? AND view_id=?"; try (final PreparedStatement statement = connection.prepareStatement(sql)) { statement.setString(1, bundle.config); statement.setLong(2, bundle.bundle); statement.setLong(3, bundle.view); statement.execute(); } return null; } Why does this claim to return Bundle? Doesn't really matter though :)

Target:
private void updateBundleConfig(Connection connection, Bundle bundle) throws SQLException { final String sql = "UPDATE portti_view_bundle_seq SET config=? WHERE bundle_id=? AND view_id=?"; try (final PreparedStatement statement = connection.prepareStatement(sql)) { statement.setString(1, bundle.config); statement.setLong(2, bundle.bundle); statement.setLong(3, bundle.view); statement.execute(); } }
Source:
protected int getOverProvisioningFactor() { START return Integer.valueOf(Framework.getProperty(WORKMANAGER_OVERPROVISIONING_PROP, DEFAULT_WORKMANAGER_OVERPROVISIONING)); END } `Integer.parseInt`

Target:
protected int getOverProvisioningFactor() { return Integer.parseInt( Framework.getProperty(WORKMANAGER_OVERPROVISIONING_PROP, DEFAULT_WORKMANAGER_OVERPROVISIONING)); }
Source:
protected void onDestroy() { START super.onDestroy(); END webView.setDownloadListener(null); } Please move `super.onDestroy` to the end of the method.

Target:
protected void onDestroy() { webView.setDownloadListener(null); super.onDestroy(); }
Source:
START public void closeTest() { END // request is keep-alive by default. HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.Close.toString()); EmbeddedChannel channel = createEmbeddedChannel(); channel.writeInbound(request); // drain the channel of content. while (channel.readOutbound() != null) { ; } assertFalse("Channel should be closed", channel.isOpen()); } Which part in this test calls `NettyResponseChannel.close()`?

Target:
public void closeTest() { // request is keep-alive by default. HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.Close.toString()); EmbeddedChannel channel = createEmbeddedChannel(); channel.writeInbound(request); // drain the channel of content. while (channel.readOutbound() != null) { } assertFalse("Channel should be closed", channel.isOpen()); }
Source:
public String getRuleLogsForVms() { START final Script cmd = new Script(_securityGroupPath, _timeout.getMillis(), s_logger); END cmd.add("get_rule_logs_for_vms"); final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); final String result = cmd.execute(parser); if (result == null) { return parser.getLine(); } return null; } Please consider adding an overridden version of the `Script(String, int, Logger)` constructor that accepts `Duration` to encapsulate this type conversion.

Target:
public String getRuleLogsForVms() { final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("get_rule_logs_for_vms"); final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); final String result = cmd.execute(parser); if (result == null) { return parser.getLine(); } return null; }
Source:
private void addReporter(Class<? extends IReporter> r) { START m_reporters.put(r, ClassHelper.newInstance(r)); END } We can avoid the instance creation if the reporter already exist

Target:
private void addReporter(Class<? extends IReporter> r) { if (!m_reporters.containsKey(r)) { m_reporters.put(r, ClassHelper.newInstance(r)); } }
Source:
START public final synchronized void addFunctions(List<? extends SqlFunction> functions) END { addFunctions(TEMP_DEFAULT_CATALOG, functions); } Don't mark methods as `final`.

Target:
public void addFunctions(List<? extends SqlFunction> functions) { addFunctions(TEMP_DEFAULT_CATALOG, functions); }
Source:
public synchronized void inputChanged(Viewer viewer, Object oldInput, Object newInput) { START if (oldInput != newInput) { END if (newInput != null) { ImportTraceContentProvider input = (ImportTraceContentProvider) newInput; clearCandidates(); fTraceTypes.putAll(input.fTraceTypes); fTraceFiles.putAll(fTraceFiles); } } } You can join the ifs. There's a content assist for that, it's awesome.

Target:
public synchronized void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (oldInput != newInput && newInput != null) { ImportTraceContentProvider input = (ImportTraceContentProvider) newInput; clearCandidates(); fTraceTypes.putAll(input.fTraceTypes); fTraceFiles.putAll(fTraceFiles); } }
Source:
START boolean isPowerManagementLegal() { END return IsPowerManagementLegal(getParameters().getVdsStaticData(), getVdsGroup() .getcompatibility_version().toString()); } please set a modifier - protected seem suitable

Target:
protected boolean isPowerManagementLegal() { return IsPowerManagementLegal(getParameters().getVdsStaticData(), getVdsGroup() .getcompatibility_version().toString()); }
Source:
public void info(String message) { START System.out.println(message); END info.add(message); } Should avoid `System.out` in tests. Instead can you write to log4j

Target:
public void info(String message) { info.add(message); }
Source:
public static File makeNumericDimFile(File dir, String dimension, ByteOrder order) { START return new File(dir, StringUtils.safeFormat("numeric_dim_%s_%s.drd", dimension, order)); END } Probably should crash if bad format string

Target:
public static File makeNumericDimFile(File dir, String dimension, ByteOrder order) { return new File(dir, StringUtils.format("numeric_dim_%s_%s.drd", dimension, order)); }
Source:
private AuditLogableBase createAuditLog(final VmNic iface) { AuditLogableBase logable = new AuditLogableBase(); START logable.setVmId(iface.getVmId()); END logable.addCustomValue("MACAddr", iface.getMacAddress()); logable.addCustomValue("IfaceName", iface.getName()); return logable; } Is there any longer a need for the VM ID ?

Target:
private AuditLogableBase createAuditLog(final VmNic iface) { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("MACAddr", iface.getMacAddress()); logable.addCustomValue("IfaceName", iface.getName()); return logable; }
Source:
public boolean equals( VirtualValue other ) { START if ( other == null || !(other instanceof MapValue) ) END { return false; } MapValue that = (MapValue) other; return size() == that.size() && Arrays.equals( keys, that.keys ) && Arrays.equals( values, that.values ); } same here, redundant?

Target:
public boolean equals( VirtualValue other ) { if ( other == null || other.getClass() != MapValue.class ) { return false; } MapValue that = (MapValue) other; return map.equals( that.map ); }
Source:
private void processSingleClusterChanges(ManageNetworkClustersParameters param) { final List<ActionParametersBase> setupNetworksParams = new ArrayList<>( createNetworkClustersToSetupNetworksParametersTransformer().transform( param.getAttachments(), param.getDetachments(), param.getUpdates()) ); HostSetupNetworksParametersBuilder.updateParametersSequencing(setupNetworksParams); setupNetworksParams.forEach(this::withRootCommandInfo); START runInternalMultipleActions(ActionType.PersistentHostSetupNetworks, setupNetworksParams, getContext().getExecutionContext()); END } nit: Formatting

Target:
private void processSingleClusterChanges(ManageNetworkClustersParameters param) { final List<ActionParametersBase> setupNetworksParams = new ArrayList<>( createNetworkClustersToSetupNetworksParametersTransformer().transform( param.getAttachments(), param.getDetachments(), param.getUpdates()) ); HostSetupNetworksParametersBuilder.updateParametersSequencing(setupNetworksParams); setupNetworksParams.forEach(this::withRootCommandInfo); runInternalMultipleActions(ActionType.PersistentHostSetupNetworks, setupNetworksParams); }
Source:
START private void setFixedLengthStreamingMode(HttpURLConnection connection, long length) { END try { // Not caching method as invocation is literally sending > 2GB, which means reflection isn't a limiter! HttpURLConnection.class.getMethod("setFixedLengthStreamingMode", long.class).invoke(connection, length); } catch (Exception e) { throw new IllegalArgumentException("Cannot transfer 2 GB or larger chunks due to JDK 1.6 limitations." + " Use chunked encoding or multi-part upload, if possible, or use a different http driver." + " For more information: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6755625"); } } [minor] Can be static?

Target:
private static void setFixedLengthStreamingMode(HttpURLConnection connection, long length) { try { // Not caching method as invocation is literally sending > 2GB, which means reflection isn't a limiter! HttpURLConnection.class.getMethod("setFixedLengthStreamingMode", long.class).invoke(connection, length); } catch (Exception e) { throw new IllegalArgumentException("Cannot transfer 2 GB or larger chunks due to JDK 1.6 limitations." + " Use chunked encoding or multi-part upload, if possible, or use a different http driver." + " For more information: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6755625"); } }
Source:
START String getErrorMessage(ClientResponse clientResponse) { END String response = clientResponse.getEntity(String.class); try { // Try to see if the server responded with an error message from the API ApiError error = getJsonParser().readValue(response, ApiError.class); return error.getMessage(); } catch (IOException e) { // If not, inform the user of the underlying response (e.g. if server threw NPE or whatever) int statusCode = clientResponse.getStatus(); ClientResponse.Status status = clientResponse.getClientResponseStatus(); String responseText = clientResponse.getEntity(String.class); return "Server returned "+status+"("+statusCode+"); "+responseText; } } Method should probably be protected, given writing this for sub-classing.

Target:
protected String getErrorMessage(ClientResponse clientResponse) { String response = clientResponse.getEntity(String.class); try { // Try to see if the server responded with an error message from the API ApiError error = getJsonParser().readValue(response, ApiError.class); return error.getMessage(); } catch (IOException e) { // If not, inform the user of the underlying response (e.g. if server threw NPE or whatever) int statusCode = clientResponse.getStatus(); ClientResponse.Status status = clientResponse.getClientResponseStatus(); String responseText = clientResponse.getEntity(String.class); return "Server returned "+status+"("+statusCode+"); "+responseText; } }
Source:
public int hashCode() { int bits = 1; bits = 31 * bits + this.type.ordinal(); bits = 31 * bits + getToX(); bits = 31 * bits + getToY(); bits = 31 * bits + getToZ(); bits = 31 * bits + getFromX(); bits = 31 * bits + getFromY(); bits = 31 * bits + getFromZ(); START return bits; END } `b ^ (b >> 31)` is missed here.

Target:
public int hashCode() { int bits = 1; bits = 31 * bits + this.type.ordinal(); bits = 31 * bits + getToX(); bits = 31 * bits + getToY(); bits = 31 * bits + getToZ(); bits = 31 * bits + getFromX(); bits = 31 * bits + getFromY(); bits = 31 * bits + getFromZ(); return bits ^ (bits >> 31); }