auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testStash() { try { // 1) call stash create command git.stashCreate().call(); readFile("Stash Created", git.getRepository().getWorkTree() + "/File1.txt"); // 2) call stash list git.stashList().call(); // 3) apply stash git.stashApply().call(); // 4) verify stash applied by outputting file readFile("Stash Created", git.getRepository().getWorkTree() + "/File1.txt"); } catch (Exception e) { e.printStackTrace(); } }

Target:
Never catch exceptions in test code unless you actually want to do something use. Just declare that this method throws Exception
Source:
public List<WorkerInfo> getWorkerInfoList() throws UnavailableException { if (mSafeModeManager.isInSafeMode()) { throw new UnavailableException(ExceptionMessage.MASTER_IN_SAFEMODE.getMessage()); } try { return mWorkerInfoCache.get(WORKER_INFO_CACHE_KEY); } catch (ExecutionException e) { throw new UnavailableException("Unable to get worker info list from cache"); } }

Target:
Can we include the information from `e` in this exception message?
Source:
public static void tearDownTestCase() throws Exception { if(dataSource != null) { Connection con = dataSource.getConnection(); if(con != null) { // rollback any changes done to DB during the test case execution con.rollback(); } } }

Target:
Rollback should be done after each test case (i.e., with an @After notation, not an @AfterClass notataion), and I think we should preserve the current behavior od tearDownTestCase(). I suggest creating a new tearDown() method for performing the rollback.
Source:
public void checkSelectFilter(final String label, final String value) { selectInputs.computeIfPresent(label, (key, values) -> { values.forEach(i -> { if ((i.getValue().equals(value) || i.getValue() == value) && i.getChecked() == false) { i.setChecked(true); } }); return values; }); }

Target:
Why do we have equality check here? it should have been done by the equals.
Source:
public ColdMergeVDSCommandParameters(Guid storageJobId, SubchainInfo subchainInfo) { super(); this.storageJobId = storageJobId; this.subchainInfo = subchainInfo; }

Target:
needed?
Source:
private void putResize (K key, V value) { K[] keyTable = this.keyTable; V[] valueTable = this.valueTable; for (int i = place(key); ; i = (i + 1) & mask) { // space is available so we insert and break (resize is later) if (keyTable[i] == null) { keyTable[i] = key; valueTable[i] = value; break; } } if (++size >= threshold) { resize(keyTable.length << 1); } }

Target:
I think we don't need to check this, as we know that the resize will not result in the threshold being exceeded.
Source:
protected void onLoad() { enableForm(false); super.onLoad(); Util.PROJECT_SVC.projectDetail(projectName, new GerritCallback<ProjectDetail>() { public void onSuccess(final ProjectDetail result) { enableForm(true); display(result); addPanel.setVisible(result.canModifyData); delRight.setVisible(result.canModifyData); } }); }

Target:
This isn't canModifyData. I think you've overloaded the variable for too many meanings. What we need is: * canModifyDescription * canModifyMergeType * canModifyAgreements * canModifyAccess The first 3 are true only if projectControl.isOwner() is true. The last one is true if projectControl.isOwnerAnyRef() is true, and is what you want to be using here for addPanel.
Source:
public static EncodeFormat checkedValueOf(String name) { try { return Enum.valueOf(EncodeFormat.class, name); } catch (Exception ex) { VoltDB.crashLocalVoltDB("Illegal encoding format " + name, true, ex); } return null; }

Target:
Why not use `EncodeFormat.valueOf`
Source:
public Set<K> keySet(Predicate predicate) { checkNotNull(predicate, "Predicate cannot be null!"); Set<K> resultingSet = new HashSet<K>(); Set<QueryableEntry> query = indexes.query(predicate); if (query != null) { for (QueryableEntry entry : query) { K key = (K) serializationService.toObject(entry.getKeyData()); resultingSet.add(key); } } else { doFullKeyScan(predicate, resultingSet); } return resultingSet; }

Target:
Minor: there is a shortcut `toObject()` method for doing the deserialization in this class and in `DefaultQueryCache`. Maybe that should be used to be consistent at all places.
Source:
public void getChildCollection_shouldThrowAPIExceptionIfGetterMethodNotFound() throws Exception { ClassWithBadGetter oo = new ClassWithBadGetter(); oo.setMyLocations(new HashSet<>()); Assertions.assertThrows(APIException.class,() ->RequiredDataAdvice.getChildCollection(oo, ClassWithBadGetter.class.getDeclaredField("locations"))); }

Target:
also a tiny thing, but sometimes you miss a whitespace after the `->`
Source:
protected void configure() { DynamicSet.setOf(binder(), CacheRemovalListener.class); install(new FactoryModule() { @Override protected void configure() { factory(ForwardingRemovalListener.Factory.class); } }); bind(DefaultCacheFactory.class); bind(MemoryCacheFactory.class).to(DefaultCacheFactory.class); bind(PersistentCacheFactory.class).to(H2CacheFactory.class); listener().to(H2CacheFactory.class); }

Target:
This should be declared in GerritGlobalModule.
Source:
private void createDisabledImage() { if (this.disabledImage != null && !this.disabledImage.isDisposed()) disabledImage = new Image(this.image.getDevice(), this.image, SWT.IMAGE_DISABLE); }

Target:
This doesn't seem right: we're building `disabledImage` from `image`, so we need to check that `image` has not been disabled. I think something like the following? if (this.image != null && !this.image.isDisposed()) { if (this.disabledImage != null && !this.disabledImage.isDisposed()) { this.disabledImage.dispose(); } disabledImage = new Image(this.image.getDevice(), this.image, SWT.IMAGE_DISABLE); }
Source:
public synchronized void releaseSample(DecoderInputBuffer sample) { sample.data.clear(); mSamplePool.offerLast(sample); }

Target:
Should probably be sample.clear().
Source:
private String buildClipboardMessage(Row row) { StringBuilder builder = new StringBuilder(); builder.append(row.getLevel()) .append(", ") .append(row.getMessage()); return builder.toString(); }

Target:
Looks like this builder just concatenate 3 strings without any loops. I guess, it is unnecessary here.
Source:
public RepositoryObject getParent() { return driver.getParentObject(this); }

Target:
Since a Tombstone is no longer in the hierarchy (result of removing the proxy), this method should probably either return a null or throw an exception
Source:
private void setLastUsedBranch() { String lastBranch = settings.get(lastBranchKey); if (lastBranch != null) { branchText.setText(lastBranch); } }

Target:
no braces here, more occurrences in this file
Source:
public String toString() { return toStringHelper(this) .omitNullValues() .add("equiCriteria", this.equiCriteria) .add("filter", filter.orElse(null)) .toString(); }

Target:
`this` is not needed?
Source:
private void validateKeyPatternsInConfig(Dictionary<String, ?> config) { Enumeration<String> keys = config.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); // the config-key enumeration contains additional keys that we // don't want to process here ... if ("service.pid".equals(key)) { continue; } Matcher matcher = EXTRACT_PLUGWISE_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.error("Given plugwise-config-key '" + key + "' does not follow the expected pattern '<PlugwiseId>.<mac|type|port|interval>'"); continue; } } }

Target:
Seems more appropriately `logger.warn`.
Source:
public Void visitFilter(FilterNode node, Void context) { String expression = isExpression(node.getPredicate()) ? node.getPredicate().toString() : formatter.formatRowExpression(node.getPredicate()); printNode(node, "Filter", expression, NODE_COLORS.get(NodeType.FILTER)); return node.getSource().accept(this, context); }

Target:
`GraphvizPrinter` (and all other plan printer) should not expect an `Expression`. Rather than having `isExpression` here, let's fix the tests if they are failing.
Source:
public void run() { resetGlobalProgress(); indexingAll = true; for (ObjectType objectType : ObjectType.values()) { startIndexing(objectType); } try { sleep(pause); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("Thread interrupted: " + e.getMessage()); } currentIndexState = ObjectType.NONE; indexingAll = false; pollingChannel.send(INDEXING_FINISHED_MESSAGE); }

Target:
Move this line after logging the error, so in any case the error get logged.
Source:
public boolean isAC3() { return getCodecA() != null && ("ac3".equals(getCodecA()) || "a52".equals(getCodecA()) || "liba52".equals(getCodecA())); }

Target:
`return getCodecA() != null && ("ac3".equals(getCodecA()) || "a52".contains(getCodecA()));`
Source:
ShardRewriter createShardRewriter( FileSystemContext fileSystemContext, FileSystem fileSystem, long transactionId, OptionalInt bucketNumber, UUID shardUuid, int shardRowCount, Optional<UUID> deltaShardUuid, boolean tableSupportsDeltaDelete, Map<String, Type> columns) { if (tableSupportsDeltaDelete) { return new DeltaShardRewriter( shardUuid, shardRowCount, deltaShardUuid, deletionExecutor, transactionId, bucketNumber, this, fileSystemContext, fileSystem); } else { return new InplaceShardRewriter( shardUuid, columns, deletionExecutor, transactionId, bucketNumber, nodeId, this, fileSystem, storageService, shardRecorder, backupManager); } }

Target:
redundant
Source:
public void init() { setLabel("Plugin"); addAttribute(ID, ROLE_ID).setLabel("Identifier"); addAttribute(LABEL, ROLE_LABEL, ROLE_LOOKUP).setNillable(false).setUnique(true).setLabel("Label"); addAttribute(DESCRIPTION, ROLE_LOOKUP).setLabel("Description").setDataType(HTML); }

Target:
TEXT datatype would be more appropriate.
Source:
@Override public Long call() throws IOException{ String oldname = Thread.currentThread().getName(); Thread.currentThread().setName(oldname+"Decode-"+this.parent.columnChunkMetaData.toString()); this.parent.processPages(recordsToReadInThisPass); Thread.currentThread().setName(oldname); return recordsToReadInThisPass; }

Target:
Space between IOException and {
Source:
public CompositeMetricsCollector(MetricsCollector... collectors) { this.collectors = new ArrayList<>(asList(collectors)); }

Target:
Does additional list creation (`new ArrayList<>()`) provide any benefits when compared with the following? ```java this.collectors = asList(collectors); ```
Source:
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_READ_CONTACTS) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { loadContacts(); } else { Toast.makeText(getApplicationContext(), "Read contacts permission denied", Toast.LENGTH_LONG).show(); finish(); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } }

Target:
to nitpick: just use `this` instead of the application.
Source:
private static void appendBodyColorsRule(StringBuilder buffer, RGB fgRGB, RGB bgRGB) { StringBuilder fg= new StringBuilder(); appendColor(fg, fgRGB); StringBuilder bg= new StringBuilder(); appendColor(bg, bgRGB); buffer.append("body {color:" + fg.toString() + "; background-color:" + bg.toString() + ";}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ }

Target:
I must be missing something. Why not simply buffer.append("body {color:"); appendColor(buffer, fgRGB); buffer.append("; background-color:"); appendColor(buffer, bgRGB); buffer.append(";}"); ?
Source:
public static synchronized VoltDBInterface instance() { if (singleton == null) { singleton = new RealVoltDB(); } return singleton; }

Target:
what .... synchronized access to the VoltDB instance not cool. it has transaction performance impact if you want to initialize without invoking the full thing we can do that without having to resource to this
Source:
public int getRenderState() { int state = speed.ordinal(); if (getReverse()) state = 14; if (isPowered()) { if (getReverse()) state += 1; else state += 7; } return state; }

Target:
You can simplify this by reordering the states.
Source:
public void ensureSettingsSavedShowsFormIfValidationFails() throws Exception { doAnswer(invocation -> { Errors errors = (Errors) invocation.getArgument(1); errors.rejectValue("absenceSettings", "error"); return null; }).when(settingsValidator).validate(any(), any()); perform(post("/web/settings")) .andExpect(view().name("settings/settings_form")); }

Target:
Den cast auf (Errors) ist hier überflüssig.
Source:
private String extractConnectionKey(final iOSVariant iOSVariant) { final StringBuilder sb = new StringBuilder() .append(iOSVariant.getVariantID()) .append(iOSVariant.isProduction() ? "-prod" : "-dev"); return sb.toString(); }

Target:
I know this is not directly part of this PR, but this could be changed to `new StringBuilder(iOSVariant.getVariantID())` to avoid one useless `append` (the `StringBuilder()` constructor create StringBuilder with capacity 16, that we immediately expand with the next append)
Source:
public void printCertificates() { DefaultTable table = new DefaultTable(); for (int i = 0; i < table.rowCount(); i++) { System.out.println("On index " + i + " is : " + table.getItem(i).getText(1)); } }

Target:
Use logger instead for sysout for logging.
Source:
public void lockEdge() throws Exception { edgeLockTest(LockResource.LockMode.WRITE, LockResource.LockMode.READ, true); edgeLockTest(LockResource.LockMode.READ, LockResource.LockMode.WRITE, true); edgeLockTest(LockResource.LockMode.WRITE, LockResource.LockMode.WRITE, true); edgeLockTest(LockResource.LockMode.READ, LockResource.LockMode.READ, false); }

Target:
can we revert back to using `LockMode.X` instead of `LockResource.LockMode.X`?
Source:
private String getClientId() { return ( (ClientMessageBusImpl) clientMessageBus ).getClientId(); }

Target:
cast to busimpl should not be needed. getClientId is on the ClientMessageBus interface, no?
Source:
private void configureManagementNetwork() { final NetworkConfigurator networkConfigurator = new NetworkConfigurator(getVds()); if (networkConfigurator.awaitVdsmResponse()) { try { networkConfigurator.refreshNetworkConfiguration(); networkConfigurator.createManagementNetworkIfRequired(); } catch (VDSNetworkException e) { throw new VdsInstallException(VDSStatus.NonResponsive, "Network error during communication with the host"); } catch (VdsInstallException e) { throw new VdsInstallException(VDSStatus.NonOperational, "Failed to configure manamgent network on the host"); } } else { throw new VdsInstallException(VDSStatus.NonResponsive, "Network error during communication with the host"); } }

Target:
Are you sure VdsInstallException is the right exception here?
Source:
public static Response newResetResponse(Header header) { return newRestartResponse(header, newNoServerError()); }

Target:
I think you forgot to change this to - `return newResetResponse(header, newNoServerError());`
Source:
private static Optional<TimeValue> getTimeValue(Optional<TimeValue> primaryValue, Optional<TimeValue> safetyValue) { if (!primaryValue.isPresent()) { return safetyValue; } return primaryValue; }

Target:
Why does this need to be `static`?
Source:
public Uris(String scheme, String host) { this.scheme = scheme; this.host = host; this.port = 0; this.rcnamespace = "0|120"; }

Target:
This should be a constant, not a magic string.
Source:
private void carryOntoHistory(RevCommit c, int carry) { stack = null; for (;;) { carryOntoHistoryInnerLoop(c, carry); CarryStack s = stack; if (s != null) { stack = s.prev; c = s.c; carry = s.carry; continue; } break; } }

Target:
can change the order to save a temp variable s.
Source:
private FactHandle[] insertFacts(KieSession ksession, int n) { FactHandle[] fhs = new FactHandle[n]; for (int i = 0; i < n; i++) { fhs[i] = ksession.insert(i); ksession.insert("" + String.valueOf(i)); } return fhs; }

Target:
Could be just ksession.insert(String.valueOf(i));
Source:
public SecureStore get() { return injector.getInstance(getSecureStoreImpl()); }

Target:
This will create a new instance every time. Cache the instance in a member variable?
Source:
protected void handleSwingDropTargetChanged(TreePath path, Transferable swingTransferable) { if (getUpdateSwingFromScoutLock().isAcquired()) { return; } // if (swingTransferable != null) { if (getScoutObject() != null) { final ITreeNode scoutNode = treePathToScoutNode(path); // notify Scout (asynchronous !) Runnable t = new Runnable() { @Override public void run() { getScoutObject().getUIFacade().fireNodeDropTargetChangedFromUI(scoutNode); } }; getSwingEnvironment().invokeScoutLater(t, 0); // end notify } } }

Target:
if (swingTransferable != null && getScoutObject() != null) {...}
Source:
public void setDiskSpaceThreshold(float diskSpaceThreshold, float diskUsageWarnThreshold) { validateThreshold(diskSpaceThreshold, diskUsageWarnThreshold); this.diskUsageThreshold = diskSpaceThreshold; this.diskUsageWarnThreshold = diskUsageWarnThreshold; }

Target:
I don't see this called anywhere in the patch. Is there a reason to make it public?
Source:
public static void setInstance(Object source, @MappingTarget Object target) { Integer level = LEVEL.get(); fireMethodCalled( level, "setInstance", source, target ); if ( level == null ) { LEVEL.set( 1 ); MAPPING.set( new IdentityHashMap<Object, Object>() ); } else { LEVEL.set( level.intValue() + 1 ); } MAPPING.get().put( source, target ); }

Target:
not needed unboxing
Source:
public List<StandardPreset> getAllStandardPresets() throws MiddlewareQueryException { return this.workbenchDataManager.getStandardPresetDAO().getAll(); }

Target:
Remove throws MiddlewareQueryException
Source:
protected void executeVDSCommand() { if (_vdsManager != null) { try { _vdsManager.getLockObj().lock(); executeVdsIdCommand(); } finally { _vdsManager.getLockObj().unlock(); } } else { executeVdsIdCommand(); } }

Target:
why did you change this?
Source:
public void whenTemplateWithGivenInputTemplate_String_shouldRenderBlobAsIt() throws IOException { TemplateSourceDocument templateSrc = createTemplateSourceDoc("We are introducing ${myStringInCtxt} !", WEBVIEW_RENDITION); TemplateBasedDocument templateBase = createTemplateBasedDoc(templateSrc.getAdaptedDoc()); List<TemplateInput> params = Arrays.asList( factory("myStringInCtxt", StringValue, "Beautiful String") ); templateBase.saveParams(TEMPLATE_NAME, params, true); Blob result = templateBase.renderWithTemplate(TEMPLATE_NAME); assertNotNull(result); assertEquals("We are introducing Beautiful String !", result.getString()); }

Target:
Could you use `List#of` or `Collections#singletonList`?
Source:
public static PDPrintStyle getLineStyle (JSONObject oskariStyle) { PDPrintStyle style = new PDPrintStyle(); JSONObject stroke = JSONHelper.optJSONObject(oskariStyle, "stroke", () -> new JSONObject()); setStrokeStyle(style, stroke); // polygon doesn't have cap style setLabelStyle(style, oskariStyle); style.setLineCap(LINE_CAP_STYLE.getOrDefault(JSONHelper.optString(stroke,"lineCap"), 0)); return style; }

Target:
Wonder if this would work/read better if PDPrintStyle had the default values itself and we could just return early instead of creating new objects to make the rest of the code work properly.
Source:
public static void init(Configuration conf) { if (!initDone) { DefaultConfiguration.conf = conf; DefaultConfiguration.initDone = true; } }

Target:
All of the methods on this class should be `synchronized`. Otherwise this change looks good.
Source:
private void rollBackToTimestamp(long timestamp) { if (getVersionUnsafe() > timestamp) { try { rollbackObjectUnsafe(timestamp); // Rollback successfully got us to the right // version, we're done. if (getVersionUnsafe() == timestamp) { return; } } catch (NoRollbackException nre) { log.warn("Rollback[{}] to failed {}", this, timestamp, nre); resetUnsafe(); } } }

Target:
We return even if this is false. Should we do something in the else case?
Source:
public void prepare(Properties options) { Objects.requireNonNull(mapper, "mapper can not be null"); Objects.requireNonNull(topicSelector, "topicSelector can not be null"); producer = new KafkaProducer<K, V>(options); }

Target:
Nit: I think `new KafkaProducer<>(options)` will work here
Source:
protected Control createSWTControl(Composite parent) throws DatabindingFailedException { final Control control = super.createSWTControl(parent); final ComposedAdapterFactory composedAdapterFactory = new ComposedAdapterFactory(new AdapterFactory[] { new ReflectiveItemProviderAdapterFactory(), new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE) }); adapterFactoryItemDelegator = new AdapterFactoryItemDelegator(composedAdapterFactory); return control; }

Target:
this must be disposed
Source:
public boolean isRegistered(VeluxProduct product) { logger.trace("isRegistered(VeluxProduct {}) called.", product.toString()); if (product.isV2()) { return isRegistered(product.getSerialNumber()); } else { return isRegistered(product.getProductUniqueIndex()); } }

Target:
`else` is redundant here.
Source:
public void tearDown() throws Exception { FileUtils.deleteQuietly(nuxeoHome); // Restore or clear all the system properties manipulated by the current test originSystemProps.forEach((key, originValue) -> { if (originValue == null) { System.clearProperty(key); } else { System.setProperty(key, originValue); } }); originSystemProps.clear(); }

Target:
You can call the value just `value`
Source:
private void checkDeployedProject(String projectName) { ServersView2 serversView = new ServersView2(); serversView.open(); ServerModule module = serversView.getServer(FULL_SERVER_NAME) .getModule(new RegexMatcher(".*" + projectName + ".*")); new WaitUntil(new ServerModuleHasState(module, ServerState.STARTED), TimePeriod.getCustom(30)); ModuleLabel moduleLabel = module.getLabel(); ServerState moduleState = moduleLabel.getState(); assertTrue("Module has not been started!", moduleState == ServerState.STARTED); }

Target:
Are these two lines of definitions necessary? Isn't it shorter to just use module.getLabel().getState() in assert?
Source:
SlackService getSlackService(final String baseUrl, final String teamDomain, final String authTokenCredentialId, final boolean botUser, final String room) { return new StandardSlackService(baseUrl, teamDomain, null, authTokenCredentialId, botUser, room); }

Target:
Oh please, no! Don't ship a null object! :cry:
Source:
private boolean isAnnotationPresent(AnnotatedType annotatedType, Set<Annotation> processedAnnotations) { if ( annotatedType instanceof AnnotatedParameterizedType ) { for ( AnnotatedType type : ( (AnnotatedParameterizedType) annotatedType ).getAnnotatedActualTypeArguments() ) { if ( isAnnotationPresent( type, processedAnnotations ) ) { return true; } } } if ( isAnnotationPresentIn( annotatedType.getDeclaredAnnotations(), processedAnnotations ) ) { return true; } return false; }

Target:
I would move this one first.
Source:
static int staticFunc() { InvokeStatic f = new InvokeStatic() { // Noncompliant @Override public String func(int n) { unknown(); staticFunc(); return 0; } }; return f.func(); }

Target:
int func();
Source:
private synchronized void resetGeneration() { this.generation = Generation.NO_GENERATION; rejoinNeeded = true; // only reset the state to un-joined when it is not already in rebalancing if (state != MemberState.REBALANCING) state = MemberState.UNJOINED; }

Target:
But we are moving to UNJOINED anyway, so it won't affect the result right?
Source:
public Path generateArtifact(URI uri, int size) throws IOException { new NpmPackageGenerator(Paths.get(uri)); buildPublishJson(); return getPackagePath(); }

Target:
why you need this here?
Source:
public void nextTuple() { Utils.sleep(100); Random rand = new Random(); Integer value = rand.nextInt(1000); collector.emit(new Values(value)); }

Target:
Minor nit, declaring a new Random each time is not really good practice.
Source:
public void register(final Class<?> clazz, final Object converter) { otherWord = ""; }

Target:
these 3 methods are `public` do you really need them?
Source:
public void testMarkerOnLastLineNoNewline_495842() throws Exception { try(BufferedWriter writer = new BufferedWriter(new FileWriter(loadcode("", false)))) { writer.write(getAboveComment().trim()); } PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.ENSURE_NEWLINE_AT_EOF, true); indexFiles(); PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.ENSURE_NEWLINE_AT_EOF, false); String result = runQuickFixOneFile(); assertContainedIn("int func() { } // @suppress(\"No return\")", result); }

Target:
Why are we setting it to true during indexing?
Source:
public void onLanguageTabSelected(String selectedLanguageCode) { Log.e("####", "HERE"); searchLanguageCode = selectedLanguageCode; startSearch(query, query != null && query.length() > 1); }

Target:
What is the Log.e for?
Source:
public T insert(SQLiteDatabase db, T entityAdapter, boolean isSyncAdapter) { Log.d("Logging EntityProcessor", "before insert"); T result = mDelegate.insert(db, entityAdapter, isSyncAdapter); Log.d("Logging EntityProcessor", "after insert on " + entityAdapter.id()); return result; }

Target:
Move the tag to a constant?
Source:
protected UfsStatus(UfsStatus status) { mIsDirectory = status.mIsDirectory; mName = status.mName; mOwner = status.mOwner; mGroup = status.mGroup; mMode = status.mMode; mLastModifiedTimeMs = status.mLastModifiedTimeMs; mXAttr = status.mXAttr; }

Target:
This won't copy the map?
Source:
boolean isProjectStyle() { if (myIsFrameworkStyle) { return false; } ProjectResourceRepository repository = ProjectResourceRepository.getProjectResources(myConfiguration.getModule(), true); assert repository != null : repository.getDisplayName(); return repository.hasResourceItem(ResourceType.STYLE, myStyleName); }

Target:
if repository is null, this will throw an NPE.
Source:
public void setUserProperty(String prop, String value) { getUserProperties().put(prop, value); Context.clearCacheForCurrentUser(); }

Target:
Let's use @CacheEvict(value="userSearchLocales") public User saveUser(User user, String password) instead. We will get rid of CacheManager in Context as well. It would be better to evict just for the specified user, but our key consists of user and currentLocale. SaveUser is not called that often so invalidating all entries is no issue anyway.
Source:
JarFileUtils(IPostProcessor processor, String xmlPathInJar, List<String> testNames) { this.processor = processor; this.xmlPathInJar = xmlPathInJar; //Ensure that dynamic list operations supported this.testNames = (testNames == null ? null : new ArrayList<>(testNames)); }

Target:
You can revert this change because you don't need it in this specific class.
Source:
public String resolve(String variable, String defaultValue) { IVariableResolver delegate = new ExpressionResolver.SystemPropertiesVariableResolver(); //ignoring argument here, as we want to fall back on the propertiesProvider. String result = delegate.resolve(variable, null); if (result == null) { try { result = propertiesProvider.getValue(variable, defaultValue, new NullProgressMonitor()); } catch (CoreException e) { throw new ExpressionResolutionException(e); } } return result; }

Target:
will properties provider return the defaultValue in case of no network or value not found ?
Source:
public static boolean isVirtIoScsiDiskInterfaceExists(VmBase vmBase) { if (vmBase.getImages().stream().anyMatch(i -> i.getDiskVmElementForVm(vmBase.getId()) .getDiskInterface() == DiskInterface.VirtIO_SCSI)) { return true; } return false; }

Target:
you can simply return the result of anyMatch without the 'if' and 'return true/false' statements. imo, it would also be nicer to extract the "i -> i.getDiskVmElementForVm(vmBase.getId()).getDiskInterface() == DiskInterface.VirtIO_SCSI" part to a separate method "isVirtioScsiDisk" to make it easier to read
Source:
public void setContext(String context){ typingRule.setContext(BloodTestContext.valueOf(context.replaceAll("\\s","").toUpperCase(Locale.FRENCH))); }

Target:
Is there a reason for using `Locale.FRENCH`? Also, why is it needed to remove all spaces? Are you just trying to do a `trim()`, or are you removing spaces between words?
Source:
private String readClasspathResource(String c) throws IOException { InputStream is = getClass().getResourceAsStream(c); try { return Util.read(is); } finally { if (is != null) { is.close(); } } }

Target:
close already done in Util.read(..)
Source:
protected void build(UnitVmModel frontend, VM backend) { String name = (String) frontend.getName().getEntity(); VmTemplate template = (VmTemplate) frontend.getTemplate().getSelectedItem(); backend.setVmtGuid(template.getId()); backend.setName(name); backend.setVmDescription((String) frontend.getDescription().getEntity()); backend.setCustomProperties(frontend.getCustomPropertySheet().getEntity()); }

Target:
can be inlined
Source:
public void getAllDrugs_shouldReturnAListOfAllDrugs() throws Exception { int resultWhenTrue = 4; int resultWhenFalse = 2; List<Drug> allDrugs = conceptService.getAllDrugs(); assertEquals(resultWhenTrue, allDrugs.size()); allDrugs = conceptService.getAllDrugs(false); assertEquals(resultWhenFalse, allDrugs.size()); }

Target:
@mavrk one test should only be for one method and one combination of parameters. and the goal is that every public method in the service layer is tested. so you should write tests for the methods * getAllDrugs() * getAllDrugs(includeRetired) and for the latter you need one test passing true and one passing false. another case is also what if there are no drugs will it return an empty list? I know this is tedious but thats because when this was written [TDD|https://en.wikipedia.org/wiki/Test-driven_development] which would start with tests wasnt used.
Source:
public List<BithumbTransactionHistoryResponse.BithumbTransactionHistory> getBithumbTrades( CurrencyPair currencyPair) throws IOException { final BithumbResponse<List<BithumbTransactionHistoryResponse.BithumbTransactionHistory>> transactionHistory = bithumb.transactionHistory(BithumbUtils.getBaseCurrency(currencyPair)); return transactionHistory.getData(); }

Target:
those inner classes make reading all of this much worse
Source:
public void addChild(String name, Long id) { if (mChildren.put(name, id) == null) { mWeight.incrementAndGet(); } }

Target:
`mChildren` could be `null`
Source:
static void reTryKerberos(boolean enabled) { if (enabled) { log.debug("Try relogin kerberos at first!"); try { if (UserGroupInformation.isLoginKeytabBased()) { UserGroupInformation.getLoginUser().reloginFromKeytab(); } else if (UserGroupInformation.isLoginTicketBased()) { UserGroupInformation.getLoginUser().reloginFromTicketCache(); } } catch (IOException e) { log.error("Try relogin kerberos failed!"); throw new RuntimeException(e); } } }

Target:
nit: This will result in double logging
Source:
void resetLogic() { for (int i = 0; i < fieldSize; i++) for (int j = 0; j < fieldSize; j++) fieldArray[i][j] = 0; playerMark = CROSS_MARK; aIMark = ZERO_MARK; turn = 0; //first turn autoGameEnabled = false; }

Target:
braces
Source:
protected Stream<URL> listBundleComponents(Bundle bundle) { String list = OSGiRuntimeService.getComponentsList(bundle); String name = bundle.getSymbolicName(); log.debug("PartialBundle: " + name + " components: " + list); if (list == null) { return Stream.empty(); } else { return Arrays.stream(list.split("[, \t\n\r\f]")).map(bundle::getEntry).filter(Objects::nonNull); } }

Target:
Could you replace `Arrays#stream` by `Stream#of` for consistency ?
Source:
public void testLoadDataObjectsWithNonNullWorkspaceProject() { assertTrue(dataObjectsService.loadDataObjects(workspaceProject).isEmpty()); }

Target:
Please use assertj assertion. In case of fail it gives error message explaining different list sizes. Current implementation will just print assertion error, expected true but was false with no reference to list size.
Source:
public Graphics2D prepareImageRenderer(MapTransform mt, BufferedImage img, ProgressMonitor pm) { Graphics2D g2 = img.createGraphics(); if (backgroundColor != null) { g2.setBackground(backgroundColor); g2.clearRect(0, 0, width, height); } ImageRenderer renderer = new ImageRenderer(); renderer.draw(mt, g2, width, height, rootLayer, pm); return g2; }

Target:
Why this function is public ? It will be used outside of this class ?
Source:
public static void refreshResources(IResource[] resources, IProgressMonitor monitor) throws CoreException { try { SubMonitor progress = SubMonitor.convert(monitor, CoreText.ProjectUtil_refreshing, resources.length); for (IResource resource : resources) { if (progress.isCanceled()) break; resource.refreshLocal(IResource.DEPTH_INFINITE, progress.newChild(1)); progress.worked(1); } } finally { monitor.done(); } }

Target:
Not needed, delete.
Source:
private boolean isInSelection(Event event) { if (selection.x == selection.y) return false; int offset = getOffsetAtPoint(event.x, event.y, null, true); if (selection.x <= offset && offset < selection.y) return true; else return false; }

Target:
we can just use 'return false' instead of 'else return false'
Source:
public void setUp() throws Exception { cuMarshalService = new CUMarshalServiceImpl(); xmlFile = new File(EXAMPLE_FILE_NAME); }

Target:
Is the throws Exception needed here?
Source:
public void actionPerformed(ActionEvent e) { if(e.getSource() == okButton){ //controller should be passed to this class only if there is need to modification content of Keystore. System.out.println(certControll); if (certControll != null) { certControll.setAddToKeystore(true); } this.dispose(); }else if(e.getSource() == cancelButton){ if (certControll != null) { certControll.setAddToKeystore(false); } this.dispose(); } }

Target:
System.out? Booh!
Source:
public FilteredSourceFiles( List<Path> rawSrcFiles, BuildTarget buildTarget, GoToolchain goToolchain, GoPlatform platform, List<FileType> fileTypes) { this.rawSrcFiles = rawSrcFiles; this.extraSrcFiles = new ArrayList<>(); initFilterSteps(buildTarget, goToolchain, platform, fileTypes); }

Target:
instead of initializing `filterSteps` in `initFilterSteps` could you do the following? ``` filterSteps = createFilterSteps(buildTarget, goToolchain, platform, fileTypes); ```
Source:
public static char complementBase(char base, boolean RNA) { if (base == 'A' && RNA) return 'U'; if (base == 'A') return 'T'; if (base == 'T' && !RNA) return 'A'; if (base == 'U' && RNA) return 'A'; if (base == 'C') return 'G'; if (base == 'G') return 'C'; return ' '; }

Target:
Isn't this already present elsewhere in biojava?
Source:
public TCCLObjectInputStream(InputStream in) throws IOException { super(in); this.classLoader = Thread.currentThread().getContextClassLoader(); }

Target:
Replace with `this(in, null)`
Source:
private void run() { try { boolean valid = connectionSanityCheck.isValid(); if (!valid) { onInvalidConnection.run(); } } catch (Exception e) { logger.warn("Impossible to correctly monitor the Axon Server connection state."); } }

Target:
Add the cause to the log.
Source:
protected String getStateParameter(final WebContext context) { final String stateParameter; final String stateData = getState(); if (CommonHelper.isNotBlank(stateData)) { stateParameter = stateData; } else { stateParameter = CommonHelper.randomString(10); } return stateParameter; }

Target:
Why did you remove the `stateData`?
Source:
public DSpaceCommandLineParameter(String parameter) { this(StringUtils.substringBefore(parameter, " "), StringUtils.substringAfter(parameter, " ")); }

Target:
This logic seems potentially fragile. What if someone accidentally types in *two spaces*, e.g. `-c[space][space]test`. Also, have you investigated whether there is a way to potentially use the tools/API in Apache Commons CLI to do this parameter parsing for us (instead of doing string parsing)? If we could just use that CLI API directly, it'd be better than rewriting it ourselves.
Source:
protected Transferable createTransferable(JComponent c) { indices = list.getSelectedIndices(); if (list.isSelectionEmpty()) return null; return new ActionTransferable((ArrayList<Action>) list.getSelectedValuesList()); }

Target:
Does this have to be after the above line? Seems like it may as well be right before. Or you could just check that the returned list is empty. Or you can do both.
Source:
public List<NimbusInfo> getAllNimbuses() { List<NimbusInfo> nimbusInfos = new ArrayList<>(); try { Collection<Participant> participants = leaderLatch.get().getParticipants(); for (Participant participant : participants) { nimbusInfos.add(Zookeeper.toNimbusInfo(participant)); } } catch (Exception e) { LOG.warn("failed to get nimbuses", e); } return nimbusInfos; }

Target:
Again don't eat the exception throw it, and wrap it if you cannot update the interface.
Source:
protected void doBegin() throws TransactionException { if (txManager == null) { throw new IllegalStateException(CoreMessages .objectNotRegistered("javax.transaction.TransactionManager", "Transaction Manager").getMessage()); } try { txManager.setTransactionTimeout(getTimeoutInSeconds()); txManager.begin(); synchronized (this) { transaction = txManager.getTransaction(); } } catch (Exception e) { throw new TransactionException(cannotStartTransaction("XA"), e); } }

Target:
deprecate this
Source:
public int hashCode() { int hash = 7; hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; }

Target:
Why not use `org.modeshape.common.util.HashCode.compute(...)` instead of this? Or better yet, why not just return `name.hashCode()`? (When can `name` be null?)
Source:
public void postProcessRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; frontendMetrics.securityServicePostProcessRequestRate.mark(); long startTimeMs = System.currentTimeMillis(); if (!isOpen) { exception = new RestServiceException("SecurityService is closed", RestServiceErrorCode.ServiceUnavailable); } else if (restRequest == null || callback == null) { throw new IllegalArgumentException("RestRequest or Callback is null"); } callback.onCompletion(null, exception); frontendMetrics.securityServicePostProcessRequestTimeInMs.update(System.currentTimeMillis() - startTimeMs); }

Target:
this should be before the callback I think
Source:
private IMethod[] toArray(List<IMethod> methods) { return methods.toArray(new IMethod[methods.size()]); }

Target:
static
Source:
public UserProfileParameters() { profile.setId(Guid.newGuid()); }

Target:
update wouldn't work if the id is always a new id setting a new id is the job of add command
Source:
public void onActivityPaused(Activity activity) { if (null != mCurInAppNotification) { mCurInAppNotification.dismiss(); } }

Target:
It is safe to call dismiss multiple times, in the source for dismiss(), there's a nice global if check along the lines of (mView != null && isVisible()) or something.
Source:
public void createReplyReplyDone() { createButton(buttonparent, buttonReply_ID, buttonReply_caption, true); createButton(buttonparent, buttonReplyDone_ID, buttonReplyDone_caption, true); buttonBar.pack(); }

Target:
Done
Source:
public void noMoreBubble() { config.setProperty(PARTITION_OPERATION_THREAD_COUNT.getName(), "1"); initExecutor(); final DummyPartitionTaskFactory taskFactory = new DummyPartitionTaskFactory(); taskFactory.delayMs = 1000; executor.executeOnPartitions(taskFactory, newPartitions()); final DummyOperation op = new DummyOperation(); executor.execute(op); assertTrueEventually(new AssertTask() { @Override public void run() { assertTrue(op.completed); } }, SECONDS.toMillis(5)); }

Target:
`SECONDS.toMillis(5)` -> `5`. Timeout parameter of `assertTrueEventually(..)` is in seconds, not milliseconds.
Source:
public void equal_shouldReturnTrueIfObjectReferenceAreTheSame() { CohortMembership cohortMembership = new CohortMembership(12); boolean result = cohortMembership.equals(cohortMembership); assertTrue(result); }

Target:
I guess we could just assert without the temporary variable.
Source:
public DynamicState withPendingLocalization(Future<Void> pendingDownload) { return new DynamicState(this.state, this.newAssignment, this.container, this.currentAssignment, this.pendingLocalization, this.startTime, pendingDownload, this.profileActions, this.pendingStopProfileActions); }

Target:
nit, could return: withPendingLocalization(this.pendingLocalization, pendingDownload);
Source:
public boolean verifyUser(String username, String password, ESClientVersionInfo clientVersionInfo) { try { final Optional<ESAuthenticationInformation> information = doVerifyUser(username, password, clientVersionInfo); if (!information.isPresent()) { /* to many bad attempts, otherwise we get an exception */ ModelUtil.logWarning( MessageFormat.format(Messages.LoginService_VerifyUserTooManyFailedRequests, username, delay)); } return information.isPresent(); } catch (final AccessControlException ex) { /* regular bad attempt */ return false; } }

Target:
We could also return true here, which seems to be more obvious to me
Source:
public void test() throws Exception { ExternalBuildReport report = new ExternalBuildReport("http://some.url.com"); assertEquals("View External Report", report.getDisplayName()); assertEquals("graph.gif", report.getIconFileName()); assertEquals("graph.gif", report.getIconFileName()); assertEquals("http://some.url.com", report.getUrlName()); assertEquals(null, report.getTarget()); }

Target:
duplicate assert
Source:
public void publishEvent(Object event) { publishEvent(new PayloadApplicationEvent<Object>(null, event)); }

Target:
The null `source` looks odd.
Source:
public boolean isList() { if (isProperty) return prop.isList(); else return false; }

Target:
Personally for all these simple things, I would simple it down to a ternary operation for code simplicity. Always keep in mind code size.
Source:
private GlusterGeoRepSession getGeoRepSession() { if (getParameters().getGeoRepSessionId() != null) { return geoRepDao.getById(getParameters().getGeoRepSessionId()); } return null; }

Target:
I don't think we need this check nor this method. simply call geoRepDao.getById(getParameters().getGeoRepSessionId()) when needed, if getParameters().getGeoRepSessionId() we will simply won't get any result
Source:
protected Statement createFailOnTimeoutStatement( Statement statement, Description description) throws Exception { return FailOnTimeout.builder() .withTimeout(timeout, timeUnit) .withLookingForStuckThread(lookForStuckThread) .withDescription(description) .build(statement); }

Target:
Unfortunately this method is protected. Changing the signature may break someone. @junit-team/junit-committers how should we handle this? We could not add the new feature without breaking the extension point. I'm in favour of modifying the methods signature and making it private. Users should create a new rule instead of extending Timeout. They could use the builder for creating the statement.
Source:
@Override public Iterator<? extends TripPatternInfo<TripSchedule>> patternIterator( IntIterator stops ) { Set<TripPatternInfo<TripSchedule>> activeTripPatternsForGivenStops = new HashSet<>(); int stopIndex = stops.next(); while (stopIndex > 0) { activeTripPatternsForGivenStops.addAll(activeTripPatternsPerStop.get(stopIndex)); stopIndex = stops.next(); } return activeTripPatternsForGivenStops.iterator(); }

Target:
The loop fails if `stops` contains _the first_ stop (`0`). The method should be: ``` Set<TripPatternInfo<TripSchedule>> activeTripPatternsForGivenStops = new HashSet<>(); while (stops.hasNext()) { activeTripPatternsForGivenStops.addAll(activeTripPatternsPerStop.get(stops.next())); } return activeTripPatternsForGivenStops.iterator(); ```
Source:
public ContextHolder(T context, Class<T> type, Set<Annotation> qualifiers) { this.context = context; this.type = type; this.qualifiers = asSet(DefaultLiteral.INSTANCE, AnyLiteral.INSTANCE); this.qualifiers.addAll(qualifiers); }

Target:
This is likely unnecessary. The set of qualifiers is expected to contain all elements. See also `org.jboss.weld.bootstrap.WeldStartup.createContexts(ServiceRegistry)` and other places where this constructor is used.
Source:
public void setUp() { jenkins.CLI.get().setEnabled(true); Set<String> agentProtocols = new HashSet<>(j.jenkins.getAgentProtocols()); agentProtocols.add(ExtensionList.lookupSingleton(CliProtocol2.class).getName()); j.jenkins.setAgentProtocols(agentProtocols); }

Target:
Unnecessary; it is still enabled by default in core, disabled in wizard.
Source:
public FieldWrapper(HighlightExecutionContext executionContext, HighlighterContext context, BasicQueryWeigher weigher) { this.executionContext = executionContext; this.context = context; this.weigher = weigher; this.positionGap = 1; }

Target:
There is a lack of symmetry here. `positionGap` should be initialized in both ctors.
Source:
public StripeFooter(List<Stream> streams, List<ColumnEncoding> columnEncodings, List<Slice> stripeEncryptionGroups) { this.streams = ImmutableList.copyOf(requireNonNull(streams, "streams is null")); this.columnEncodings = ImmutableList.copyOf(requireNonNull(columnEncodings, "columnEncodings is null")); this.stripeEncryptionGroups = requireNonNull(stripeEncryptionGroups, "stripeEncryptionGroups is null"); }

Target:
`ImmutableList.copyOf`
Source:
public Double getValue() { //do not miss the last tuple try { estimator.accumulate(cx); } catch (ExecException ex) { throw new RuntimeException("Error while accumulating sample frequency: " + ex); } return estimator.getEntropy(); }

Target:
i'm not sure how getValue() is supposed to be called, but I would make it work correctly even if it is called twice. that is, set cx back to zero after you accumulate.
Source:
private boolean usesCatalogsAsSchemas(DatabaseMetaData metaData) { boolean result = true; ResultSet rs = null; try { rs = metaData.getSchemas(); while (rs.next() && result) { result = false; } } catch (SQLException e) { throw JdbcUtils.wrapException(e, "retrieve schema and catalog metadata", JdbcActionType.METADATA); } finally { FileHelper.safeClose(rs); close(null); } return result; }

Target:
Hmm I think we should remove this line. Seems like it's not needed since `close(null)` will just do nothing. Maybe it's a left-over line from some previous version of the file where the result set got closed properly or something :-)
Source:
public void processCacheEntryDestroyed(CacheEntryRemovedEvent event) { if (!event.isPre()) { emitSessionDestroyedEvent((String) event.getKey()); } }

Target:
those `if (!event.isPre())` can be avoided by adding `@Listener(observation = Observation.POST)` at class level
Source:
public void invalidate(@Nullable String path) { if (path == null) { return; } invalidate(Uri.parse(path)); }

Target:
Flip the `if` and move the invalidate call up inside
Source:
public MerlinBuilder withRxCallbacks() { rxCallbacksManager = new RxCallbacksManager(); if (connectableRegisterer == null && disconnectableRegisterer == null) { return this.withConnectableCallbacks().withDisconnectableCallbacks(); } else if (connectableRegisterer == null) { return this.withConnectableCallbacks(); } else if (disconnectableRegisterer == null) { return this.withDisconnectableCallbacks(); } return this; }

Target:
could this block be simplified? ``` java public MerlinBuilder withRxCallbacks() { rxCallbacksManager = new RxCallbacksManager(); if (connectableRegisterer == null) { withConnectableCallbacks(); } if (disconnectableRegisterer == null) { withDisconnectableCallbacks(); } return this; } ```
Source:
public static String localizeProvider(String name) { if (name==null) { Assert.isTrue(false); return null; } switch (name) { case DIRECT_PROVIDER: return Messages.ProxySelector_0; case ECLIPSE_PROVIDER: return Messages.ProxySelector_1; case NATIVE_PROVIDER: return Messages.ProxySelector_2; default: break; } Assert.isTrue(false); return null; }

Target:
I don't like this code duplication. How about if (name != null) { switch (name) { ... } } Assert.isTrue(false); return null;
Source:
public String removeSuffix(String loaderFileName, char suffixTerm) { return loaderFileName.substring(0, loaderFileName.lastIndexOf(suffixTerm)); }

Target:
Does this need to be public?