auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void startRuntime() { String tempDir = AppConstants.getInstance().getString("log.dir", null); v8 = V8.createV8Runtime("J2V8Javascript", tempDir); }

Target:
Setting the alias and temp directory can be quite important. Perhaps make this an optional argument? So you can overwrite the alias when needed (i.e. to improve performance). Right now all instances will be cached under the same name.
Source:
public GWCConfig getConfig() { if (gsEnvironment != null && gsEnvironment.isStale()) { syncEnvironment(); } return gwcConfigPersister.getConfig(); }

Target:
This bloc of code is repeated many times, should be centralized in a single method.
Source:
private BlackboardArtifact createDownloadArtifact(AbstractFile zoneFile, ZoneIdentifierInfo zoneInfo) { Collection<BlackboardAttribute> bbattributes = createDownloadAttributes( null, null, zoneInfo.getURL(), null, (zoneInfo.getURL() != null ? NetworkUtils.extractDomain(zoneInfo.getURL()) : ""), null); return addArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_DOWNLOAD, zoneFile, bbattributes); }

Target:
again, maybe StringUtils.defaultString()
Source:
public IncrementalScoreDirector(IncrementalScoreDirectorFactory scoreDirectorFactory, boolean constraintMatchEnabledPreference, IncrementalScoreCalculator<Solution_> incrementalScoreCalculator) { super(scoreDirectorFactory, constraintMatchEnabledPreference); if (constraintMatchEnabledPreference && !(incrementalScoreCalculator instanceof ConstraintMatchAwareIncrementalScoreCalculator)) { throw new IllegalStateException("The score calculator " + incrementalScoreCalculator + " must implement " + ConstraintMatchAwareIncrementalScoreCalculator.class.getSimpleName() + " when constraintMatchEnabledPreference is true."); } this.incrementalScoreCalculator = incrementalScoreCalculator; }

Target:
I fear we won't be able to add this fail fast (although I always like any proposal to add more fail fasts :)). The other fail fasts added in the PR are fine.
Source:
public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { if (inputStream == null || outputStream == null) { if (outputStream != null) { IOUtils.closeQuietly(outputStream); } return; } try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(outputStream); return; } }

Target:
no need for the return statement.
Source:
protected void before() throws Throwable { if (session == null) { throw new IllegalStateException("Session was not initialized"); } session.execute(String.format("CREATE KEYSPACE %s WITH durable_writes = false AND " + "replication = {'class': 'SimpleStrategy', 'replication_factor' : 1};", keyspaceName)); session.execute(String.format("USE %s;", keyspaceName)); }

Target:
Change to `Assert.state(session != null, "Session was not initialized");`
Source:
private void lockImageInDb() { final DiskImage diskImage = getDiskImage(); TransactionSupport.executeInNewTransaction(() -> { getCompensationContext().snapshotEntityStatus(diskImage.getImage()); diskImage.setImageStatus(ImageStatus.LOCKED); ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.LOCKED); getCompensationContext().stateChanged(); return null; }); }

Target:
Not needed, the next statement handles it in the DB, do we really care if we have the status changed in the instance?
Source:
public synchronized void close() { try { Closer closer = Closer.create(); if (mJournalOutputStream != null) { closer.register(mJournalOutputStream); } closer.register(mGarbageCollector); closer.close(); } catch (IOException e) { LOG.warn("Failed to close UfsJournalLogWriter with error: {}.", e.getMessage()); } mClosed = true; }

Target:
What's the motivation for swallowing this exception, and is it really only a warning? Also, could we use `closeQuietly` (or an improved version if we want the logging)?
Source:
public void testFooPing() { // change logging level, does NOT work Logger logger = Logger.getLogger(JMXMethodExecutor.class.getName()); Level originalLevel = logger.getLevel(); logger.setLevel(Level.OFF); // Initialize weld, Foo bean is used in observer new Weld().initialize(); logger.setLevel(originalLevel); }

Target:
The logging actually happens on the "client" side. So we'll need to setup the log level there, maybe using `@BeforeClass` and `@AfterClass`? I tried to move this code to the `AbstractShutdownHookTest.deploy()` method and it seemed to work.
Source:
public void searchForProcesses() throws Exception { desktopPage.searchInSearchField("process"); int numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); searchResultPage.searchInSearchField("proc"); numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); searchResultPage.searchInSearchField("möhö"); numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be no process found",0,numberOfResults); }

Target:
One empty line too much.
Source:
public AS7ManagementDetails(IServer server) { this(server, new HashMap<String,Object>()); }

Target:
new HashMap<String,Object>(0) or Collections.<String, Object>emptyMap() if immutable
Source:
public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext context) { final CommandResult<RuleViolation> results = allow(context); if (!results.getType().equals(CommandResult.Type.ERROR)) { final org.kie.workbench.common.stunner.core.graph.Graph graph = getGraph(context); graph.addNode(candidate); getMutableIndex(context).addNode(candidate); } return results; }

Target:
Do we need FQCN?
Source:
private static void dataTableHeaderMayOnlyContainVariableNames(ASTNode stat) throws InvalidSpecCompileException { throw new InvalidSpecCompileException(stat, "Header of data table may only contain variable names"); }

Target:
might be better to return the exception so that you can directly see that it exits in the code `throw dataTableHeaderMayOnlyContainVariableNames(column.get(0));`
Source:
public static <T> MutableMessageBuilder<T> fromMessage(Message<T> message) { Assert.notNull(message, "message must not be null"); if (message instanceof CloneableMessage) { logger.warn("For CloneableMessages consider to use regular MessageBuilder. " + "Otherwise custom Message context may be lost."); } return new MutableMessageBuilder<T>(message); }

Target:
If we move the logic to the builder factories, this would not be needed.
Source:
public Image getColumnImage(Object element, int columnIndex) { TaskReview reviewContainer = (TaskReview) element; switch (columnIndex) { case 0: return getIncomingChangesImage(); case 1: try { return getReviewStateImage(Integer.parseInt(reviewContainer.getCr())); } catch (Exception e) { break; } case 2: try { return getVerifiedStateImage(Integer.parseInt(reviewContainer.getV())); } catch (Exception e) { break; } } return null; }

Target:
This implies you're expecting that "Code Review" and "Verified" below to always be integers (otherwise, you break silently so you must be.) I think this seems to have an underlying implication that the data type for both getters really should be "Integer". You can always convert an integer to a string safely but this isn't true for parsing some arbitrary string IMO. Thoughts?
Source:
WorkerErrantRecordReporter workerErrantRecordReporter() { return workerErrantRecordReporter; }

Target:
let's add `protected` here to be symmetric to what other fields that are accessed by the context have as scope
Source:
public static VmInterfaceType getDefaultNicType(Collection<VmInterfaceType> items) { return items.contains(VmInterfaceType.pv) ? VmInterfaceType.pv : items.iterator().next(); }

Target:
According to logic in BaseEditVmInterfaceModel: nicTypes = nicTypes == null ? new ArrayList<VmInterfaceType>() : nicTypes; the items are expected to be an empty ArrayList. In that case the items.iterator().next() would fail on NoSuchElementException.
Source:
public CompletionStage<Void> removeRecoveryInformationFromCluster(Collection<Address> where, long internalId) { if (rpcManager != null) { TxCompletionNotificationCommand ftc = commandFactory.buildTxCompletionNotificationCommand(internalId); CompletionStage<Void> stage = sendTxCompletionNotification(where, ftc); return stage.thenRun(() -> removeRecoveryInformation(internalId)); } else { removeRecoveryInformation(internalId); return CompletableFutures.completedNull(); } }

Target:
Don't need to wait for the tx completion responses before removing the local info here either, although since removing the local info is expensive you could still send the command first.
Source:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() >= 1) { throw new IAE("Function[%s] needs 0 argument", name()); } return ExprEval.of(Math.PI); }

Target:
Could be extracted to a `private static final` constant.
Source:
public static List<CPListElement> getExistingEntries(IJavaProject project) throws JavaModelException { ArrayList<CPListElement> newClassPath= new ArrayList<>(); for (IClasspathEntry curr : project.getRawClasspath()) { newClassPath.add(CPListElement.createFromExisting(curr, project)); } return newClassPath; }

Target:
rename to entry
Source:
public final List<A> minus(final Equal<A> eq, final List<A> xs) { return this.removeAll(compose(Monoid.disjunctionMonoid.sumLeft(), xs.mapM(Function.<A, A, Boolean>curry(eq.eq())))); }

Target:
Hmm, I am suprised this is the case. I am using Intellij 14.0.2. Yourself?
Source:
public Builder withDefaultHint(QueryEvaluationHint engineDefaultHints) { this.engineDefaultHints = engineDefaultHints; this.defaultBackendFactory = engineDefaultHints.getQueryBackendFactory(); return this; }

Target:
This is not a good way to set up things. If both defaultHint and defaultBackend is set, the end result depends on the order... Either some checking (and possibly logging) is required here, or we should define a clear priority between the settings, and the build method should ensure that.
Source:
public Integer getIdle() { HikariPool pool = getHikariPool(); if (Objects.nonNull(pool)) { return pool.getIdleConnections(); } return super.getIdle(); }

Target:
I don't think calling super is what I'd do here
Source:
ElasticsearchTableDescriptionProvider(ElasticsearchConnectorConfig config, JsonCodec<ElasticsearchTableDescription> codec) { requireNonNull(config, "config is null"); requireNonNull(codec, "codec is null"); checkArgument(config.getScrollTimeout().toMillis() >= 10, "scrollTimeout must be at least 10 ms"); checkArgument(config.getRequestTimeout().toMillis() >= 10, "requestTimeout must be at least 10 ms"); tableDefinitions = createTableDescriptions(config, codec); }

Target:
Let's remove these `checkArgument`s as these are not critical checks & we will probably forget to remove these when `MinDuration` gets fixed.
Source:
public void dispose() { if (fRegisterInProvider) { unregisterActions(); } fSelectionProvider = null; fFindDeclarationsAction = null; fFindDeclarationsInProjectAction = null; fFindDeclarationsInHierarchyAction = null; fFindDeclarationsInWorkingSetAction = null; updateGlobalActionHandlers(); super.dispose(); }

Target:
What if fSelectionProvider is null? NPE will be thrown.
Source:
public void addError(Throwable error) { if (error == null) { throw new NullPointerException("Error cannot be null"); } if (error instanceof AssumptionViolatedException) { AssertionError e = new AssertionError(error.getMessage()); e.initCause(error); error = e; } errors.add(error); }

Target:
Minor thing: I'm generally not happy with reassigning method parameters.
Source:
protected void handleIdle() { if (streams.isEmpty()) { return; } super.handleIdle(); }

Target:
Shouldn't the test be synchronized as in `Http1xClientConnection.java`?
Source:
public String get(String key) { Map<String, String> Map = inheritableThreadLocal.get(); if ((Map != null) && (key != null)) { return Map.get(key); } else { return null; } }

Target:
I know this was pre-existing, but the variable is capitalized Map, but should be just map.
Source:
public void containsConversion(Class<?> from, Class<?> to) { isNotNull(); boolean foundMatchingConversion = false; for ( GroupConversionDescriptor groupConversionDescriptor : actual ) { if ( groupConversionDescriptor.getFrom().equals( from ) && groupConversionDescriptor.getTo().equals( to ) ) { foundMatchingConversion = true; break; } } if ( !foundMatchingConversion ) { fail( String.format( Locale.getDefault(), "<%s> does not contain a conversion from <%s> to <%s>.", actual, from, to ) ); } }

Target:
@marko-bekhta Is this still a left-over? I.e. are you planning to revert this change as per our discussion above? Same question for some more places where `Locale.getDefault()` is used now.
Source:
public synchronized void setTailSegment(long tailSegment) { dataStore.put(Long.class, PREFIX_TAIL_SEGMENT, KEY_TAIL_SEGMENT, tailSegment); // Set the epoch in the router as well. //TODO need to figure out if we can remove this redundancy serverRouter.setServerEpoch(tailSegment); }

Target:
Copy paste error ?
Source:
public void sleep(IInteger seconds) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(seconds.longValue())); } catch (InterruptedException e) { } }

Target:
FYI, `TimeUnit.SECONDS.sleep(seconds.longValue())`
Source:
public void release() { JdbcConnectionAccess connectionAccess = jdbcContext.getJdbcConnectionAccess(); if( !( connectionAccess instanceof JdbcConnectionAccessProvidedConnectionImpl ) ) { throw new IllegalStateException( "DdlTransactionIsolatorProvidedConnectionImpl should always use a JdbcConnectionAccessProvidedConnectionImpl" ); } JdbcConnectionAccessProvidedConnectionImpl connectionAccessProvidedConnection = (JdbcConnectionAccessProvidedConnectionImpl) connectionAccess; try { connectionAccess.releaseConnection( null ); } catch (SQLException ignore) { LOG.unableToReleaseIsolatedConnection( ignore ); } }

Target:
I see that `connectionAccessProvidedConnection` isn't used. Is the check on `connectionAccess` and the cast there just to make sure that the connection was provided?
Source:
public boolean isRead(Tip tip) { return fReadList.contains(new Integer(tip.hashCode())); }

Target:
Integer.valueOf(...) instead.
Source:
public IContentProvider getContentProvider() { if (useDynamic) return dynamicProvider; return super.getContentProvider(); }

Target:
Please use brackets, even for one-line blocks
Source:
public BlobStore getById(Function<String, InputStream> configGetter, String storeId) { logger.debug("Looking blob store with id {}", storeId); try { HierarchicalConfiguration config = getConfiguration(configGetter); if (config != null) { return findStore(config, store -> StringUtils.equals(storeId, store.getString(CONFIG_KEY_ID))); } } catch (ConfigurationException e) { logger.error("Error reading blob store configuration", e); } return null; }

Target:
Why are we swallowing the exception? Isn't this something the caller should know?
Source:
public void disconnect() { // Set the terminal control state to CLOSED. fControl.setState(TerminalState.CLOSED); }

Target:
Add a null check, as the class may not be initialized just yet.
Source:
public SymmetricHashJoin construct(final ConstructArgs args) { SymmetricHashJoin join = new SymmetricHashJoin( null, null, argColumns1, argColumns2, argSelect1, argSelect2, argSetSemanticsLeft, argSetSemanticsRight, argColumnNames); join.setPullOrder(argOrder); return join; }

Target:
If this setter is only called here then it should be moved into the constructor.
Source:
public String toString() { return "VM [" + vmStatic.getvm_name() + "]"; }

Target:
you can use getName() instead of vmStatic.getvm_name()
Source:
DropDownMenu updateContextMenu(DropDownMenu menuBar, List<ActionButtonDefinition<T>> actions) { return updateContextMenu(menuBar, actions, true); }

Target:
public, protected, private?
Source:
private static synchronized Session session() { final Properties properties = new Properties(); final ConfigurationProperties conf = EmailDispatchConfiguration.getConfiguration(); properties.put("mail.smtp.host", conf.mailSmtpHost()); properties.put("mail.smtp.name", conf.mailSmtpName()); properties.put("mail.smtp.port", conf.mailSmtpPort()); properties.put("mailSender.max.recipients", conf.mailSenderMaxRecipients()); SESSION = Session.getDefaultInstance(properties, null); return SESSION; }

Target:
Don't spam final keywords in code that is not part of your changeset
Source:
public void testInterrupt() throws Exception { Pipelining<String> pipelining = new Pipelining<String>(1); pipelining.add(mock(ICompletableFuture.class)); TestThread t = new TestThread() { @Override public void doRun() throws Throwable { pipelining.add(mock(ICompletableFuture.class)); } }; t.start(); t.interrupt(); t.assertFailsEventually(InterruptedException.class); }

Target:
You need to mark the pipelining as `final` as the code needs to be JDK6 compatible.
Source:
public void traceClosed(@Nullable TmfTraceClosedSignal signal) { cancelUpdate(); super.traceClosed(signal); setDataProvider(null); if (signal != null) { fXYPresentationProvider.remove(signal.getTrace().getUUID()); } }

Target:
If the trace is an experiment, it has already been disposed and its UUID has changed (experiment no longer has any children, its UUID computed from an empty string).
Source:
private String author(int line) { PersonIdent author = db.getMailmap().map(blame.getSourceAuthor(line)); if (author == null) return ""; //$NON-NLS-1$ String name = showAuthorEmail ? author.getEmailAddress() : author .getName(); return name != null ? name : ""; //$NON-NLS-1$ }

Target:
the other option is to do it on the commands exposing this information to the user only. I think internally we should stick to the original author/committer/tagger
Source:
public void deactivate() { // retrieve the view and the element managed by the edit part View view = getView(); if (view == null) { return; } getDiagramEventBroker().removeNotificationListener(view, this); if (hostSemanticElement == null) { return; } // remove listeners to applied stereotyped for (EObject stereotypeApplication : hostSemanticElement.getStereotypeApplications()) { getDiagramEventBroker().removeNotificationListener(stereotypeApplication, this); } // remove notification on element getDiagramEventBroker().removeNotificationListener(hostSemanticElement, this); // removes the reference to the semantic element hostSemanticElement = null; }

Target:
Avoid multiple returns.
Source:
public DefaultSchedulerMessageSource(MuleContext muleContext, PeriodicScheduler scheduler, boolean disallowConcurrentExecution) { this.muleContext = muleContext; this.scheduler = scheduler; this.disallowConcurrentExecution = disallowConcurrentExecution; notificationFunctions = new LinkedList<>(); // Add message received notification notificationFunctions .add((event, component) -> createConnectorMessageNotification(this, event, component.getLocation(), MESSAGE_RECEIVED)); }

Target:
isn't this the exact same notification that the FlowProcessMediator is already sending?
Source:
public void requestHandleWithNonHealthCheckRequestTest() throws IOException { testNonHealthCheckRequest(HttpMethod.POST, "POST"); testNonHealthCheckRequest(HttpMethod.GET, "GET"); testNonHealthCheckRequest(HttpMethod.GET, MockBlobStorageService.ECHO_REST_METHOD); testNonHealthCheckRequest(HttpMethod.DELETE, "DELETE"); }

Target:
Don't understand this. Why aren't you doing `MockBlobStorageService.ECHO_REST_METHOD` for everything?
Source:
public DockerTemplateOptions volumes(Map<String, String> volumes) { for (Map.Entry<String, String> entry : checkNotNull(volumes, "volumes").entrySet()) { checkNotNull(entry.getKey(), "host paths must not be null"); checkNotNull(entry.getValue(), "container paths must not be null"); } this.volumes = Optional.<Map<String, String>>of(ImmutableMap.copyOf(volumes)); return this; }

Target:
In general for the whole PR, are these checks really needed? Guava's immutable collections don't allow null values so checking the null input in the map and list options here looks redundant?
Source:
private String getMethodCallback(JMethod method) { if (isVoidMethod(method)) { return "org.fusesource.restygwt.client.MethodCallback<java.lang.Void> callback"; } else if (method.getReturnType().isPrimitive() != null) { JPrimitiveType primitiveType = method.getReturnType().isPrimitive(); return "org.fusesource.restygwt.client.MethodCallback<" + primitiveType.getQualifiedBoxedSourceName() + "> callback"; } return "org.fusesource.restygwt.client.MethodCallback<" + method.getReturnType().getParameterizedQualifiedSourceName() + "> callback"; }

Target:
Correct me if it's wrong, but I think the first block with "if (isVoidMethod(method)) {" is not needed anymore
Source:
protected GoogleApiClient createGoogleApiClient() { return GoogleApiClientFactory.createWithoutSignIn(getApplicationContext()); }

Target:
I am not sure if it is a good practice to create GoogleApiClient with ApplicationContext. GoogleApiClient is really tied to the Activity. We are recreating it on every Activity. That's how it needs to be done. So I am not sure if this makes sense.
Source:
private boolean matchNamePattern(String value, String namePattern) { boolean match = true; if (value != null && StringUtils.isNotBlank(value)) { match = value.matches(namePattern); } return match; }

Target:
Doesn't StringUtils.isNotBlank already compare for null?
Source:
public void setStatus(int sc, String sm) { if (super.getStatus() == OK) { super.setStatus(sc, sm); } status = sc; }

Target:
I think this check should happen before applying the wrapper (i.e. if the current status code is 200 don't apply the wrapper, if it is not 200 don't let it be modified). Otherwise if there are multiple calls to setStatus the first one may work and the second will fail.
Source:
public final GHIntArrayList reverse() { final int[] buffer = this.buffer; for (int start = 0, end = size() - 1; start < end; start++, end--) { // swap the values int tmp = buffer[start]; buffer[start] = buffer[end]; buffer[end] = tmp; } return this; }

Target:
Maybe we should define the int outside of the for? Not sure if this gets optimized, but I introduced a "bug" with String once, so I became a bit cautious with these things.
Source:
public Collection<TreeNode> getTreeNodes(Diff diff) { final Collection<EStructuralFeature.Setting> settings = treeNodeToDiffCrossReferencer .getNonNavigableInverseReferences(diff, false); final Set<TreeNode> nodes = new LinkedHashSet<TreeNode>(settings.size()); for (EStructuralFeature.Setting setting : settings) { final EObject referencing = setting.getEObject(); if (referencing instanceof TreeNode) { nodes.add((TreeNode)referencing); } } return nodes; }

Target:
Is a Set really necessary here? A treenode can wrap a single eobject so the same treenode will be returned only once by #getNonNavigableInverseReferences()
Source:
public int lookupId(String name) { if (value == null) { return Strings.isNullOrEmpty(name) ? 0 : -1; } else { return value.equals(name) ? 0 : -1; } }

Target:
This branch is not needed
Source:
public String getAbsoluteFilePath(String relPath) { Bundle bundle = Platform.getBundle(MulticoreVisualizerUIPlugin.PLUGIN_ID); URL fileURL = bundle.getEntry(relPath); File file = null; try { file = new File(FileLocator.resolve(fileURL).toURI()); } catch (URISyntaxException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return file.getAbsolutePath(); }

Target:
private
Source:
private void timeoutEvent(TimeoutMap.Listener.Type type, String cid) { switch (type) { case Remove: case Evict: correlationIds.remove(cid); break; case Put: default: correlationIds.add(cid); } dirty = true; }

Target:
Can we avoid the switch as its not common practice and maybe people dont know about how it works and would think that remove and put does nothing in this example etc. Make the code understandable and maintainable for everyone.
Source:
public void setUp() throws Exception { createProject(); baseActivityTestRule.launchActivity(null); }

Target:
please use baseActivityTestRule.launchActivity() (without the "null")
Source:
public void tearDown() { col.drop(); client.close(); }

Target:
The closing is already done in the driver. No need to repeat it here.
Source:
private View makeSpaceView(int width, int height) { View view = new View(getActivity()); view.setLayoutParams(new ListView.LayoutParams(width, height)); view.setClickable(true); view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { dismiss(); } return false; } }); return view; }

Target:
Shouldn't we return true?
Source:
public boolean needsInput() { // Since SetBuildOperator is always the last operator (no next operator that needs input from it), // we handle the unfinished work in this method instead of getOutput(). The Driver always // calls it in each iteration. if (unfinishedWork != null) { boolean done = processUnfinishedWork(); channelSetBuilder.updateMemoryReservation(); if (!done) { return false; } } return !finished; }

Target:
fmt
Source:
public void onLoad() { offset = world.rand.nextInt(10); }

Target:
Add ````java super.onLoad(); ```` Just so that we don't have to worry about future additions to the parent's onLoad function not being called by this.
Source:
protected Message<?> doPollForMessage(String groupIdKey) { List<Message<?>> messages = jdbcTemplate.query(getQuery(Query.POLL_FROM_GROUP), new Object[] { groupIdKey, region, groupIdKey }, mapper); Assert.isTrue(messages.size() == 0 || messages.size() == 1); if (messages.size() > 0){ return messages.get(0); } return null; }

Target:
How about to use here `NamedParameterJdbcTemplate` as you've done in the `JdbcChannelMessageStore#doPollForMessage` ?
Source:
public static boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException { Thread watcherThread = ThreadDeathWatcher.watcherThread; if (watcherThread != null) { watcherThread.join( ObjectUtil.checkNotNull(unit, "unit").toMillis(timeout)); return !watcherThread.isAlive(); } else { return true; } }

Target:
move the null check as first action in the method to ensure we also throw if `watcherThread == null` and `unit` is null
Source:
public Builder toBuilder() { Builder builder = new Builder(type); builder.members.putAll(members); for (Map.Entry<String, List<CodeBlock>> entry : builder.members.entrySet()) { entry.setValue(new ArrayList<>(entry.getValue())); } return builder; }

Target:
I think I'd have rather looped over the `members`' entry set to `put()` each entry into `builder.members` instead of using `putAll` and then replacing the entries' values.
Source:
public void closeJob(GeneralSecurityException gse) { callback.onCompletion(new EncryptJobResult(null, null, null), gse); }

Target:
why isn't this `onCompletion(null, gse)`?
Source:
private ChangeInfo getChange(PushOneCommit.Result pr) throws IOException { return getChange(pr.getChangeId(), ListChangesOption.DETAILED_LABELS); }

Target:
Nit: in another file you've imported ListChangesOption statically (for MESSAGES). Umport it statically here too?
Source:
private void clearIfNeeded(Address lockHolder) { if(!rpcManager.getMembers().contains(lockHolder)) { final Directory directory = getDirectoryProvider().getDirectory(); log.warn("Forcing clear of index lock"); ((DirectoryExtensions) directory).forceUnlock(IndexWriter.WRITE_LOCK_NAME); } }

Target:
Spacing
Source:
public Capable canUpload() { Capable result = projectControl.canPushToAtLeastOneRef(); if (result != Capable.OK) { return result; } result = MagicBranch.checkMagicBranchRefs(repo, project); return Capable.OK; }

Target:
You ignore result here. You need to return result.
Source:
private int getColumnWidth(final Pattern52 pattern) { if (pattern.getBoundName() == null || pattern.getBoundName().trim().isEmpty()) { return 1; } else { return pattern.getChildColumns().size(); } }

Target:
Maybe also here `StringUtils` but I am thinking if it is good idea to bring dependency for that class.
Source:
public void onStart(ITestContext iTestContext) { getLifecycle().fire(new TestSuiteStartedEvent( getSuiteUid(iTestContext), iTestContext.getSuite().getName() ).withTitle( getCurrentSuiteTitle(iTestContext) ).withLabels( AllureModelUtils.createTestFrameworkLabel("TestNG"), AllureModelUtils.createFeatureLabel(getCurrentSuiteTitle(iTestContext)) )); }

Target:
Could you please remove this line?
Source:
public boolean supportsSorting(SortBy[] sortAttributes) { if (super.supportsSorting(sortAttributes)) return true; for (SortBy sort : sortAttributes) { if (!supportsPropertySorting(sort.getPropertyName())) return false; } return true; }

Target:
Not sure about this one @taba90, even if the default implementation supports it we still want to override the default check no?
Source:
public static boolean hasGitFolder(InputStream inputStream) throws IOException { TarArchiveInputStream tarInputStream = null; try { boolean gitFolderPresent = false; tarInputStream = new TarArchiveInputStream(new GzipCompressorInputStream(inputStream)); for (TarArchiveEntry entry; (entry = tarInputStream.getNextTarEntry()) != null;) { if (GIT_FOLDER_NAME.equals(entry.getName()) && entry.isDirectory()) { gitFolderPresent = true; break; } } return gitFolderPresent; } finally { StreamUtils.close(tarInputStream); } }

Target:
yes but if you change the impl to something that would not always set it and forget about changing the initialization.... It's simply very good but simple practice: always initialize local variables, instance variable are automagically always in a sane state. I really dont see the point of removing the existing initializations. Spare some characters? And as said, it's a good practice to always initialize local variables to a defined state.
Source:
protected void updateDetailsAvailability() { super.updateDetailsAvailability(); NetworkView network = (NetworkView) getSelectedItem(); networkExternalSubnetListModel.setIsAvailable(network.isExternal()); }

Target:
I think this might return null.
Source:
public Object getResponse() { return true; }

Target:
seems `false` is also a valid response.
Source:
public InputContent parseInputStream( InputStream inputStream, Boolean strict ) throws IOException, ReadException { Description description = deserialize(new InputStreamReader(inputStream), strict); Content content = complexify(description); return new InputContent(content, description.getType()); }

Target:
this doesnt need to be on a different line
Source:
private void setUpAccessBaseAgingExpectations() { ReferenceQueue<Integer> queue = mock(ReferenceQueue.class); map = new ReapedMap<String, Integer>(1000, true, queue); when(queue.poll()).thenReturn(null); }

Target:
Why is this necessary? This is the default behaviour for mocked Object returning methods.
Source:
protected RollCycle decodeRollCycle(String retentionDuration) { if (retentionDuration == null || retentionDuration.isEmpty()) { return DAILY; } String rollingPeriod = retentionDuration.substring(retentionDuration.length() - 1); switch (rollingPeriod) { case SECOND_ROLLING_PERIOD: return RollCycles.TEST_SECONDLY; case MINUTE_ROLLING_PERIOD: return MINUTELY; case HOUR_ROLLING_PERIOD: return HOURLY; case DAY_ROLLING_PERIOD: return DAILY; default: throw new IllegalArgumentException("Unknown rolling period: " + rollingPeriod); } }

Target:
Can use the static import too. And I assume you can then remove the `RollCycles` import.
Source:
void process(BitVector changedBits, BitVector deletedBits) { toEntityIntBags(changedBits, deletedBits); // note: processAll != process subscriptions.get(0).processAll(changed, deleted); for (int i = 0, s = subscriptions.size(); s > i; i++) { subscriptions.get(i).process(changed, deleted); } }

Target:
`i` should start at 1, as it's already processed by the preceding LOC.
Source:
void setMinMax(double min, double max) { this.min = min; this.max = max; }

Target:
private?
Source:
private void checkTableNotExists(SchemaTableName tableName) { if (tables.values().stream() .map(MemoryTableHandle::toSchemaTableName) .anyMatch(tableName::equals)) { throw new PrestoException(ALREADY_EXISTS, format("Table [%s] already exists", tableName.toString())); } if (views.keySet().stream() .anyMatch(tableName::equals)) { throw new PrestoException(ALREADY_EXISTS, format("View [%s] already exists", tableName.toString())); } }

Target:
Nit: I wouldn't wrap here, since it's short and there's only one item, so wrapping makes it harder to read
Source:
private static void addCaseFileVariableToResult(Collection<Pair<Object, String>> result, String element) { if (element.length() > 0) { List<String> list = Arrays.asList(element.split(",")); list.forEach(s1 -> { String value = CaseFileVariables.CASE_FILE_PREFIX + s1.split(":")[0]; result.add(new Pair<>(value, value)); }); } }

Target:
same, I think this method has no need to be `static`
Source:
public SessionPresenterView showError(final String message) { Notify.hideAll(); getSettings().setType(kieNotificationCssClass(NotifyType.DANGER)); showNotification(translate(SessionPresenterView_Error), translate(SessionPresenterView_Notifications), IconType.EXCLAMATION_CIRCLE); return this; }

Target:
This causes the `message` argument to be unsued.... IMO is confusing, as the Alerts panel could be not present (standalone/submarine)...
Source:
private void encodeDistribution(DBObject dbObject, Described entity) { TranslatorUtils.fromIterable(dbObject, DISTRIBUTION_KEY, entity.getDistributions(), new Function<Distribution, DBObject>() { @Override public DBObject apply(Distribution distribution) { return distributionTranslator.toDBObject(new BasicDBObject(), distribution); } }); }

Target:
lambda
Source:
private boolean checkJoinGroupNode(StaticAnalysis sa, JoinGroupNode node, Set<IVariable<?>> projectedVars) { AtomicBoolean res = new AtomicBoolean(); node.forEach(child -> { res.compareAndSet(false, checkIfNodeProducesVars(sa, child, projectedVars)); }); return res.get(); }

Target:
Why we aren't using foreach here like in checkServiceNode()? Wouldn't it do extra work if the first child already contains the variable but there many more children?
Source:
public HashMap<String, ObjectId> getUpdated() { return updated; }

Target:
Style-nit: Our public API should return Map, Set, List and not a concrete implementation type. Sorry I missed this during earlier review iterations.
Source:
public void timeUnitNullFail() throws Exception { Timed<Integer> t1 = new Timed<Integer>(1, 5, null); }

Target:
`t1` shows up as unused variable, please remove the assignment.
Source:
public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_for_leads, null); return root; }

Target:
``` View root = inflater.inflate(R.layout.fragment_for_leads, container, false); ``` should be used instead
Source:
public Map<String,Integer> listLanguages() throws IOException { return root.retrieve().to(getApiTailUrl("languages"), HashMap.class); }

Target:
Size in bytes, max Integer will be 2Gb, i think some crazy repo may have such number. Long looks better.
Source:
public static Win32VK fromValue(final int code) { if (code < 0 || code > 0xFF) { throw new IllegalArgumentException(String.format("No mapping for %02x", code)); } for (Win32VK vk : Win32VK.values()) { if (vk.code == code) { return vk; } } // We shall not reach here. throw new IllegalArgumentException(String.format("No mapping for %02x", code)); }

Target:
Any reason to special case this? The fall through to line 300 should catch it.
Source:
public <R> R execute(ResultProducer<R> producer) { if (bindings.isEmpty()) { throw new IllegalStateException("No batch parts to execute"); } try { return producer.produce(() -> internalBatchExecute().stmt, getContext()); } catch (SQLException e) { throw new UnableToProduceResultException("Exception producing batch result", e, getContext()); } }

Target:
It might be good to add a sanity check to validate that `getBinding()` is empty, to catch users who forget to call `add()`. Mockito does something similar e.g. if you call `verify(mock)` without chaining a method call on the mock.
Source:
private void print() { if (canceled) { out.print("[CANCELED] "); } else if (total == IProgressMonitor.UNKNOWN) { out.print(animationFrames[animationFrameId]); animationFrame = (animationFrame + 1) % animationFrames.length; } else { out.printf("[%2d%%] ", worked / total); } out.print(task); if (subTask != null) { out.printf(" - %s", subTask); } out.print('\r'); }

Target:
Has to be animationFrameId = (animationFrameId + 1) ...
Source:
default ListenableFuture<Resolved<I>> resolveIds(Iterable<Id> ids, Boolean refreshCache) { throw new UnsupportedOperationException(); }

Target:
should this just proxy to the plain resolveIds method?
Source:
public URI createAdminUnit(URI path, Model model) { // Add types to the object being created model = populateModelTypes(path, model, Arrays.asList(Cdr.AdminUnit, PcdmModels.Object)); return createContentContainerObject(path, model); }

Target:
Should be PcdmModels.Collection to agree with the rest of the code
Source:
public final String readUTF() throws IOException { int numberOfBytes = readInt(); if (numberOfBytes == NULL_ARRAY_LENGTH) { return null; } checkAvailable(pos, numberOfBytes); String result = new String(data, pos, numberOfBytes, UTF_8); pos += numberOfBytes; return result; }

Target:
It looks like the bounds check is also done by String constructor. Can you check if this line is still necessary ?
Source:
private S3StorageProvider getS3StorageProvider() { if (!storageAccountManager.isInitialized()) { throw new DuraCloudRuntimeException("storageAccountManager is not initialized!!!"); } StorageAccount account = storageAccountManager.getPrimaryStorageAccount(); StorageProviderType type = account.getType(); if (!type.equals(StorageProviderType.AMAZON_S3)) { throw new DuraCloudRuntimeException( "The type of primary storage provider on " + storageAccountManager.getAccountName() + " must be " + StorageProviderType.AMAZON_S3); } return new S3StorageProvider(account.getUsername(), account.getPassword(), account.getOptions()); }

Target:
This type check should be removed. There are storage provider types build on top of the AMAZON_S3 implementation which would have a different type, but would still work just as well for streaming. For example, using the CHRONOPOLIS provider but where some spaces are not used for snapshots (left in S3) could support this. Also, the 4Science-proposed AMAZON_ONE type would fit this category.
Source:
private static void closeSettingsChangedShell() { new WaitUntil(new ShellIsAvailable("Validator Settings Changed"), TimePeriod.LONG); DefaultShell shell = new DefaultShell("Validator Settings Changed"); String shellText = shell.getText(); new PushButton("Yes").click(); new WaitWhile(new ShellIsActive(shellText), TimePeriod.LONG); }

Target:
ShellIsAvailable
Source:
public void setUp() throws Exception { User.disableStorage(); // don't change the app login from this test }

Target:
Can this throw an Exception?
Source:
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { if (delegate instanceof X509ExtendedTrustManager) { ((X509ExtendedTrustManager)delegate).checkClientTrusted(chain, authType, socket); } else { throw new UnsupportedOperationException(); } verifier.checkChain(chain); }

Target:
IMHO copy-paste bug - should be `checkServerTrusted` instead.
Source:
private boolean isEmailValid(String email) { EmailValidator emailValidator = EmailValidator.getInstance(); return emailValidator.isValid(email); }

Target:
Can you combine these 2 lines into 1
Source:
public void evict(WrappedBytes key) { Lock lock = locks.getLock(key).writeLock(); lock.lock(); try { checkDeallocation(); long address = memoryLookup.getMemoryAddress(key); if (address != 0) { // TODO: this could be more efficient InternalCacheEntry<WrappedBytes, WrappedBytes> ice = performGet(address, key); passivator.passivate(ice); performRemove(address, key); } } finally { lock.unlock(); } }

Target:
We should add an if check here for ice and only do this line and the next if it is not null. Prevents another possible loop through the linked list if it exists.
Source:
public static Put getHadoopVersionPut(int historyFileVersion, byte[] jobKeyBytes) { Put pVersion = new Put(jobKeyBytes); byte[] valueBytes = null; valueBytes = Bytes.toBytes(Integer.toString(historyFileVersion)); byte[] qualifier = Bytes.toBytes(JobHistoryKeys.hadoopversion.toString().toLowerCase()); pVersion.add(Constants.INFO_FAM_BYTES, qualifier, valueBytes); return pVersion; }

Target:
If having subclasses inherit a common implementation is the goal, using an instance method is preferred (i.e. non-static). Using static methods for inheritance purposes is bit of an anti-pattern.
Source:
public Map<String, Object> getMetadata() { return this.metadata; }

Target:
+1 to future proofing the name Have a look at one of the Adapters in [NovaParserModule.java](https://github.com/jclouds/jclouds/blob/master/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaParserModule.java). You'll want to do something like that for the Image class. Don't forget to add it to the [provideCustomAdapterBindings()](https://github.com/jclouds/jclouds/blob/master/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaParserModule.java#L57) method.
Source:
protected Node[] createNodes(AbstractFile t) { Node[] node = new Node[1]; if(t.isDir()){ //TODO log an error ??? return node; } else { //replace FileNode with our own subclass of its base type or similar node[0] = new DataResultFilterNode(new FileNode(t, false), DirectoryTreeTopComponent.findInstance().getExplorerManager()); return node; } }

Target:
This check is not necessary, we do not compute MD5 hashes for directories.
Source:
public ByteBuffer newByteBuffer(byte[] b, int offset, int length) { return b == null || b.length == 0 || length == 0 ? ByteBufferImpl.EMPTY_INSTANCE : new ByteBufferImpl(b, offset, length); }

Target:
Can be: ```java return ByteBufferImpl.create(b, offset, length);` ```
Source:
public List<ExtensionProxy> getExtensionsByService(String provides) { List<ExtensionProxy> results = new ArrayList<>(); for (ExtensionEntry entry : initializedEntries.values()) { if (entry.initialized && entry.extension.getContext().<List> get(Base.ContextKeys.PROVIDES).contains(provides)) { results.add(entry.extension); } } return results; }

Target:
of course it is initialized if it is in the initialized entries... now?
Source:
private boolean isBrokerWithPRTSupport(final Intent intent) { if (intent == null) { throw new IllegalArgumentException("intent"); } // Only new broker with PRT support will send down the value and the version will be v2 final String brokerVersion = intent.getStringExtra(AuthenticationConstants.Broker.BROKER_VERSION); if (!StringExtensions.IsNullOrBlank(brokerVersion) && AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion)) { return true; } return false; }

Target:
you can do return (!StringExtensions.IsNullOrBlank(brokerVersion) && AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion)); #Closed
Source:
public PluginClassLoader pluginClassLoader(String name) { if (PluginUtils.shouldLoadInIsolation(name)) { SortedMap<PluginDesc<?>, ClassLoader> inner = pluginLoaders.get(name); if (inner != null) { ClassLoader pluginLoader = inner.get(inner.lastKey()); if (pluginLoader instanceof PluginClassLoader) { return (PluginClassLoader) pluginLoader; } } } return null; }

Target:
I believe the existing behavior may be intentional and have something to do with the parent of the `DelegatingClassLoader` being something other than the system class loader. However, I'm not familiar enough with this part of the code base to say for sure; we should probably err on the side of keeping the existing functionality as-is unless someone else (e.g., @kkonstantine or a committer) can vouch that the current changes here wouldn't break anything.
Source:
private PyUDFExpression() { name = ""; //set default return type this is changed once pythonfunction is retrived. outputType = Type.BLOB_TYPE; }

Target:
I don't understand how this is used, or why BLOB_TYPE is the default here. Can you give me an example of where you use it?
Source:
public void removeInstance(Object instance) { deployedCacheStores.put(instance.getClass().getName(), new CompletableFuture<>()); }

Target:
Why are we setting it to new a new empty CompletableFuture? Is removing not sufficient?
Source:
protected String createRecordName(String objectType) { StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb, Locale.US); formatter.format("ManagerTest_%s_%08d", objectType, System.currentTimeMillis()); return sb.toString(); }

Target:
You don't need `Formatter`. You can replace these lines with a single `String.format(...)` statement.
Source:
EagerQueryResult() { fields = originalResult.columns().toArray( new String[originalResult.columns().size()] ); }

Target:
Change it to `new String[0]`, it's just shorter.
Source:
public ArtifactoryClientBuilder addInterceptorLast(HttpRequestInterceptor httpRequestInterceptor) { if (this.requestInterceptorList == null) { this.requestInterceptorList = new ArrayList<>(); } this.requestInterceptorList.add(httpRequestInterceptor); return this; }

Target:
I suggest to add an initialization in the declaration, instead of this `if` and the `if` in line 148: private List<HttpRequestInterceptor> requestInterceptorLis = new ArrayList<>();
Source:
public Stock(String symbol, String name, double price) { super(); this.symbol = symbol; this.name = name; this.price = price; }

Target:
super() is not necessary
Source:
public boolean removeAll(Collection<?> c) { boolean removedSomething = false; for (Object removeMe : c) { removedSomething |= remove(removeMe); } return removedSomething; }

Target:
s/`removeMe`/`key`/ ?
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DimFilterHavingSpec that = (DimFilterHavingSpec) o; return dimFilter != null ? dimFilter.equals(that.dimFilter) : that.dimFilter == null; }

Target:
dimFilter is non-null, so could be simplified unless you want to stick to "as IntelliJ generated" form.
Source:
private Session openSession() { final Session currentSession = (Session) this.emProvider.get().getDelegate(); final SessionFactory factory = currentSession.getSessionFactory(); return factory.openSession(); }

Target:
Same question as above: why change the scope?
Source:
Pair<IAnnotationModel, List<ContributionAnnotation>> addNewEntry( final List<ContributionAnnotation> annotations) { if (queue.size() > maxHistoryLength) { throw new IllegalStateException( "The queue already contains the allowed number of annotations."); } Pair<IAnnotationModel, List<ContributionAnnotation>> removedEntry = removeEntryIfFull(); queue.add(annotations); return removedEntry; }

Target:
Amend message as it no longer represent the correct error state? A full queue on call is now allowed (which you correctly test for by now using `>` instead of `>=`). The issue you are checking for now it that there already are too many entries before the addition, meaning the queue was already in an illegal state before the call.
Source:
public Optional<Guid> getUserIdIfExternal() { return isInternalExecution() ? Optional.empty() : Optional.ofNullable(getUserId()); }

Target:
this can be reduced to protected.
Source:
public Group removeAccount(Account account) { Assert.notNull(account, "account cannot be null"); GroupMembership groupMembership = null; for (GroupMembership accountGroupMembership : getAccountMemberships()) { if (accountGroupMembership.getAccount().getHref().equalsIgnoreCase(account.getHref())) { groupMembership = accountGroupMembership; break; } } if (groupMembership != null){ groupMembership.delete(); } else { throw new IllegalStateException("The specified account does not belong to this Group."); } return this; }

Target:
`href`s are case sensitive. Please use `equals(String)` instead of `equalsIgnoreCase(String)`
Source:
private boolean canPasteAll(IJavaElement destination) { for (TypedSource fSource : fSources) { if (!canPaste(fSource.getType(), destination)) { return false; } } return true; }

Target:
rename to source