auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void showResource(final IResource resource) { IProject project = resource.getProject(); RepositoryMapping mapping = RepositoryMapping.getMapping(project); if (mapping == null) return; Repository newRep = mapping.getRepositoryOrNestedSubmoduleRepository(resource); if (newRep != currentRepository) { reload(newRep); } }

Target:
style nit: we don't use braces around single line blocks
Source:
public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.REGULAR_FILE); ent.setLength(1); ent.setObjectId(data); }

Target:
a length of 1? That's wrong in most cases, or?
Source:
private List<Action> handleChangesCanceled(Session session, Resource resource, ResourceStatus newStatus) { final List<Action> actions = Lists.newArrayList(); actions.add(Action.RELOAD); return actions; }

Target:
Would be simpler as: return Arrays.asList(Action.RELOAD);
Source:
public LocalDateTime toLocalDateTimeBin(TimeZone tz, byte[] bytes) throws PSQLException { ParsedBinaryTimestamp parsedTimestamp = this.toParsedTimestampBin(null, bytes, true); if (parsedTimestamp.infinity == Infinity.POSITIVE) { return LocalDateTime.MAX; } else if (parsedTimestamp.infinity == Infinity.NEGATIVE) { return LocalDateTime.MAX; } return LocalDateTime.ofEpochSecond(parsedTimestamp.millis / 1000L, parsedTimestamp.nanos, ZoneOffset.UTC); }

Target:
Is this change required?
Source:
void hideCurrentToolTip () { checkWidget (); if (this.selectedMenuItem != null) { selectedMenuItem.hideToolTip (); } }

Target:
For non-public methods checkWidget() is not required.
Source:
public void installEdition(Set<String> pluginKeys) { Optional<UpdateCenter> updateCenter = updateCenterMatrixFactory.getUpdateCenter(true); Set<Release> pluginsToInstall = new HashSet<>(); if (updateCenter.isPresent()) { for (String pluginKey : pluginKeys) { pluginsToInstall.addAll(updateCenter.get().findInstallablePlugins(pluginKey, Version.create(""))); } } pluginsToInstall.forEach(super::download); }

Target:
no need to create this Set when updateCenter is not present
Source:
public boolean isApplicable(String requestPath) { List<String> applicablePaths = ImmutableList.of("druid/coordinator/v1/security/"); for (String path : applicablePaths) { if (requestPath.startsWith(path) && !requestPath.equals(path)) { return true; } } return false; }

Target:
Looks that the list isn't needed.
Source:
public void execute(Runnable command) { final Runnable runnable = doWrap(command, controlPoint); try { super.execute(doIdentityWrap(runnable)); } catch (RejectedExecutionException e) { controlPoint.requestComplete(); throw e; } }

Target:
should be catching Exception here too
Source:
public void shouldFormatUniquenessConstraints() { final int[] propertyKeyIds = new int[]{42}; assertEquals( "new UniquenessConstraint( SchemaDescriptorFactory.forLabel( 23, 42 ) )", formatArgument( new UniquenessConstraint( SchemaDescriptorFactory.forLabel( 23, propertyKeyIds ) ) ) ); }

Target:
not needed
Source:
private void launchUserBrickScriptActivity(Context context, UserBrick userBrick) { ((ScriptActivity) context).removeFormulaEditorFragment(); Intent intent = new Intent(context, UserBrickScriptActivity.class); ProjectManager.getInstance().setCurrentUserBrick(userBrick); context.startActivity(intent); }

Target:
can we be sure that context is a ScriptActivity?
Source:
protected void revertTask() { getEnclosingCommand().getParameters().getDiskImage().setImageStatus(ImageStatus.ILLEGAL); ImagesHandler.updateImageStatus( getEnclosingCommand().getParameters().getDestinationImageId(), ImageStatus.ILLEGAL); }

Target:
please perform the update explicitly on the image that you modified in the line before (add .getId)
Source:
public void checkIPAdress() { Set<ConstraintViolation<VmNic>> validate = validator.validate(createVmNic(), groups); assertEquals(validMacAddress, validate.isEmpty()); if (validMacAddress) { assertTrue(validate.isEmpty()); } else { assertEquals(1, validate.size()); assertTrue(validate.iterator().next().getMessage().equals(message)); } }

Target:
why not use assertEquals as well ?
Source:
public State advance() throws IOException { mCheckpointStream = null; mNextEntry = null; while (true) { updateInputStream(); if (mCheckpointStream != null) { return State.CHECKPOINT; } advanceEntry(); if (mNextEntry != null) { return State.LOG; } if (mInputStream == null || mInputStream.isDone() || mInputStream.mFile.isIncompleteLog()) { return State.DONE; } } }

Target:
if `mNextEntry` is `null`, will this if statement always evaluate to `true`? If not, then it would just loop again, and what would happen?
Source:
public boolean hasNext() { if (saveNext != null) { return true; } try { saveNext = internalNext(); return true; } catch (NoSuchElementException e) { return false; } }

Target:
This is not a good convention. How about changing `internalNext()` to be able to return null to indicate there's no more elements?
Source:
public void process(IProgressMonitor monitor) throws CoreException { if (monitor == null) monitor = new NullProgressMonitor(); SubMonitor subMonitor = SubMonitor.convert(monitor, "Searching unused members", this.units.length); //$NON-NLS-1$ for (ICompilationUnit unit : this.units) { doSearchCU(unit, subMonitor.newChild(1)); } }

Target:
This can be removed. The SubMonitor itself can handle null
Source:
public void teardownTest() throws InterruptedException { sharedStorageApi().delete(currentSharedStorage.id()); assertNodeAvailable(currentServer); deleteServer(currentServer.id()); }

Target:
Does it make sense to try to delete the server even if the shared storage delete operation failed? We should try to avoid leaking resources.
Source:
public BenchmarkSuiteConfig setSuite(String suite) { if (suite != null) { this.suite = suite; } return this; }

Target:
This is unnecessary
Source:
private boolean isCloseable(Type type) { return type.isSubtypeOf(JAVA_IO_AUTO_CLOSEABLE) || type.isSubtypeOf(JAVA_IO_CLOSEABLE); }

Target:
I'm not sure you need to remove all of these `static` modifiers. Some of them are probably still valid (this one notably)
Source:
public synchronized CryptoService getCryptoService() { if (cryptoService == null) { throw new CryptoService.CryptoException("Crypto service not initialized."); } return cryptoService; }

Target:
not sure if this needs to be synchronized
Source:
public Segment(String path, String etag, long sizeBytes) { this.path = checkNotNull(path, "path"); this.etag = checkNotNull(etag, "etag of %s", path); this.sizeBytes = sizeBytes; }

Target:
@archupsg03 I think we can remove this change?
Source:
public double @NonNull getXAxis() { return fXValues; }

Target:
@NonNull double[] ?
Source:
public void eachNonZeroInColumn(int j, MatrixProcedure procedure) { int k = columnPointers[j], i = rowIndices[k]; while (i < columnPointers[j+1]) { procedure.apply(rowIndices[i],j,values[i]); i++; } }

Target:
What about having a simple `for` loop here. Like: ``` java for (int i = columnPointers[k]; i < columnPointers[j + 1]; i++) { procedure.apply(rowIndices[i], j, values[i]); } ``` There is something wrong with your code. First, `i = rowIndicies[k]`. And then you're getting row by `rowIndicies[i]`. This is strange. I guarantee it will fail tests.
Source:
public ApiAuthenticationResult authenticate(HttpRequest httpRequest) { Assert.notNull(httpRequest, "httpRequest argument cannot be null."); if (ServletHttpRequest.class.isAssignableFrom(httpRequest.getClass())){ this.httpRequest = (ServletHttpRequest) httpRequest; } else { Assert.isInstanceOf(HttpRequest.class, httpRequest, "The specified httpRequest argument must be an instance of " + HttpRequest.class.getName() + " or " + ServletHttpRequest.class.getName()); this.httpRequest = httpRequest; } return this.execute(); }

Target:
wrong casting
Source:
public static Mode fromString(String inStr) { if (inStr == null || inStr.isEmpty()) { throw new IllegalArgumentException("String representation of MultiAuthenticator.Mode can not be null nor empty."); } inStr = inStr.toLowerCase(); if (inStr.equals("any")){ return ANY; } if (inStr.equals("all") || inStr.equals("every")){ return ALL; } throw new IllegalArgumentException("Unknown string representation [" + inStr + "] for MultiAuthenticator.Mode"); }

Target:
could be also just `.equalsIgnoreCase()`
Source:
protected CoverageAgendaListener createCoverageAgendaListenerWithData(Map<String, Integer> rulesToNumberOfTimes) { CoverageAgendaListener coverageAgendaListener = new CoverageAgendaListener(); for (Map.Entry<String, Integer> ruleToNumberOfTimes : rulesToNumberOfTimes.entrySet()) { BeforeMatchFiredEvent beforeMatchFiredEventMock = createBeforeMatchFiredEventMock(ruleToNumberOfTimes.getKey()); IntStream.range(0, ruleToNumberOfTimes.getValue()).forEach(i -> coverageAgendaListener.beforeMatchFired(beforeMatchFiredEventMock)); } ; return coverageAgendaListener; }

Target:
Typo?
Source:
private void startListFragment(byte[] bytes, Uri dataUri, String serverQuery, Preferences.CloudSearchPrefs cloudSearchPrefs) { Fragment listFragment = ImportKeysListFragment.newInstance(bytes, dataUri, serverQuery, false, cloudSearchPrefs); getSupportFragmentManager().beginTransaction() .replace(R.id.import_keys_list_container, listFragment, TAG_FRAG_LIST) .commitAllowingStateLoss(); // we commitAllowingStateLoss for when the Activity is already started but an Intent is // received and to be rendered }

Target:
I'm really not a fan of `commitAllowingStateLoss`, and the general android advice is to use it as a last resort only. see above on handling `onNewIntent`.
Source:
public Webhook(String componentUuid, @Nullable String ceTaskUuid, @Nullable String analysisUuid, String name, String url) { this.componentUuid = requireNonNull(componentUuid); this.ceTaskUuid = ceTaskUuid; this.analysisUuid = requireNonNull(analysisUuid); this.name = requireNonNull(name); this.url = requireNonNull(url); }

Target:
:warning: `requireNonNull` on a nullable argument highlights that a UT is missing (could be testing that `Optional.empty()` is returned when argument is `null`)
Source:
private static List<String> toStringList(final Object toCast) { // Return object as an ArrayList wherever it's defined as // list or not // // ### Example // object: // - firstValue // - secondValue // ### OR // object: singleValue // ### if (toCast instanceof List) { return (List<String>) toCast; } return Collections.singletonList((String) toCast); }

Target:
I just want to make sure the result of this call is not expected to be modified anywhere. I see one assignment to a instance variable `this.excludeTags`
Source:
protected String getNameFromTopic(String topic) { if (!topic.startsWith(prefix)) { throw new IllegalArgumentException(String.format("topic %s with invalid prefix %s", topic, prefix)); } return topic.replaceFirst(prefix, ""); }

Target:
`topic.substring(prefix.length())`
Source:
protected Buffer getBuffer(Dsn dsn) { File bufferDir; String bufferDirOpt = Lookup.lookup(BUFFER_DIR_OPTION, dsn); if (bufferDirOpt != null) { bufferDir = new File(bufferDirOpt); } else { bufferDir = new File(this.ctx.getCacheDir().getAbsolutePath(), DEFAULT_BUFFER_DIR); } Log.d(TAG, "Using buffer dir: " + bufferDir.getAbsolutePath()); return new DiskBuffer(bufferDir, getBufferSize(dsn)); }

Target:
// nitpick-mode-on Can you change `this.ctx` to `ctx`? // nitpick-mode-off
Source:
public void run(final SpringConfiguration configuration, final Environment environment) throws Exception { log.info("_____spring scanning________*******************"); initializeSpring(configuration, environment); // Do the dropwizard registrations addResources(environment); addHealthChecks(environment); addTasks(environment); addManaged(environment); }

Target:
clean up message
Source:
private static JSONObject createJsonFileObject(InputStream stream) throws IOException, JSONException { String line; StringBuilder result = new StringBuilder(); // Reads from stream BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { // Read each line of the GeoJSON file into a string while ((line = reader.readLine()) != null) { result.append(line); } } finally { reader.close(); } // Converts the result string into a JSONObject return new JSONObject(result.toString()); }

Target:
This can potentially throw an `IOException`.
Source:
public void setExecutionAudit(BiConsumer<RequestData, Authentication> executionAudit) { this.executionAudit = executionAudit; }

Target:
Since it's a testing facility I'd make the methods around it at least package private. Another possible approach would be to manually register a RequestPostProcessor that does the same work using GeoServerExtensionsHelper.singleton
Source:
public void useEqualsWhenTrueThenCustomMediaTypeIsMatched() throws HttpMediaTypeNotAcceptableException { request.addHeader("Accept", "text/unique"); matcher = new MediaTypeRequestMatcher(new MediaType("text", "unique")); matcher.setUseEquals(true); assertThat(matcher.matches(request)).isTrue(); }

Target:
A number of these tests don't actually throw an `HttpMediaTypeNotAcceptableException`. Will you please remove the `throws` from the signature where it is unnecessary? This way, the expectations of the test are clearer.
Source:
default void executeTask(final KeyFilter<? super K> filter, BiConsumer<? super K, InternalCacheEntry<K, V>> action) throws InterruptedException { iterator().forEachRemaining(ice -> { if (filter == null || filter.accept(ice.getKey())) { action.accept(ice.getKey(), ice); } }); }

Target:
Could use `forEach` here too, otherwise we're not really gaining anything from using a lambda
Source:
private void sendRelationshipErrorMessage( final String relationName, final User user ) { SystemMessageEventUtil systemMessageEventUtil = SystemMessageEventUtil.getInstance(); try { systemMessageEventUtil.pushMessage( new SystemMessageBuilder() .setMessage(LanguageUtil.format( user.getLocale(), "contenttypes.field.properties.relationship.required.error", relationName) ) .setSeverity(MessageSeverity.INFO) .setType(MessageType.SIMPLE_MESSAGE) .create(), list(user.getUserId()) ); } catch (LanguageException e) { throw new DotRuntimeException(e); } }

Target:
set as final
Source:
public synchronized void updateCommittedTail(long newCommittedTail) { committedTail.updateAndGet(curr -> { if (newCommittedTail <= curr) { return curr; } return newCommittedTail; }); }

Target:
Is synchronized necessary here?
Source:
private boolean isNestedCopyfile(CopyFile copyfile) { if (copyfile.dest.indexOf('/') == -1) // If the copyfile is at root level then it won't be nested. return false; for (RepoProject proj : filteredProjects) { if (proj.getPath().compareTo(copyfile.dest) > 0) // Early return as remaining projects can't be ancestor of this // copyfile config (filteredProjects is sorted). return false; if (proj.isAncestorOf(copyfile.dest)) { return true; } } return false; }

Target:
nit: missing braces around if bodies (https://wiki.eclipse.org/EGit/Contributor_Guide#Braces_for_one-line_statements)
Source:
public void write(OutputStream out) { try { IOUtils.copy(results.getInputStream(), out); } catch (IOException e) { log.warn(e.getMessage()); throw new WebApplicationException(Response.status(Status.SERVICE_UNAVAILABLE) .entity("Service Unavailable, IO Exception with Search Engine").build()); } finally { results.disconnect(); } }

Target:
The exception should be logged completely.
Source:
private static Collection<@NonNull TmfAbstractAnalysisRequirement> getSubRequirements() { Set<@NonNull String> requiredEventsFields = Collections.singleton( ITraceEventConstants.DURATION); TmfAnalysisEventFieldRequirement entryReq = new TmfAnalysisEventFieldRequirement( StringUtils.EMPTY, requiredEventsFields); return Collections.singleton(entryReq); }

Target:
this can fit on one line
Source:
protected boolean allowPausedModeWork(boolean internalCall, boolean adminConnection) { return (VoltDB.instance().getMode() != OperationMode.PAUSED || internalCall || adminConnection); }

Target:
Why not static as others? Same to function `makeQuickResponse `.
Source:
public Queue<ControllerAction> getInputQueue() { Queue<ControllerAction> result = new ArrayDeque<>(); result.addAll(queuedActions); queuedActions.clear(); return result; }

Target:
Have you considered skipping the line above by having something like `Queue<ControllerAction> result = new ArrayDeque(queuedActions);`
Source:
private void runLibertyMojoCreate() throws MojoExecutionException { createParams.addAll(commonParams); createParams.addAll(commonServerParams); Xpp3Dom config = stripConfigElements(getLibertyPluginConfig(), createParams); log.info("Running liberty:create goal"); runLibertyMojo("create", config); }

Target:
If `createParams` should always have `commonParams` and `commonServerParams`, why not just define it that way to start with? And I think you could make the collection a static final variable at the class level.
Source:
private ProgramState closeResource(ProgramState programState, final SymbolicValue target) { if (target != null && isOpened(programState, target)) { return programState.addConstraint(target.wrappedValue(), NullConstraint.CLOSED); } return programState; }

Target:
Please fix this issue.
Source:
public LongWrappingDimensionSelector(LongColumnSelector selector, ExtractionFn extractionFn) { this.delegate = selector; this.exFn = extractionFn; }

Target:
This selector is going to throw NPE on get() if extractionFn is null, so it's better to throw it in construction: ``` this.extractionFn = Preconditions.checkNotNull(extractionFn, "extractionFn"); ```
Source:
private String getCurrentUser() { // authenticator is not used if there is not any user Account[] accountList = mAcctManager .getAccountsByType(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE); return accountList[0].name; }

Target:
can account list be null or empty here?
Source:
private boolean isExpired(Long issuedAt, Long lifetime) { return lifetime != -1 && issuedAt + lifetime < System.currentTimeMillis() / 1000; }

Target:
Suggest using parenthesis to clarify order of operator evaluation
Source:
private void onSafeDelete() { if (context.getEditorModelContent().getOriginalClassName() != null) { //if we are about to delete a .java file that could be parsed without errors, and we can calculate the //className then we can check for class usages prior to deletion. final String className = context.getEditorModelContent().getOriginalClassName(); showAssetUsagesDisplayer.showAssetUsages(Constants.INSTANCE.modelEditor_confirm_deletion_of_used_class(className), versionRecordManager.getCurrentPath(), className, ResourceType.JAVA, () -> onDelete(versionRecordManager.getPathToLatest()), () -> { }); } else { //we couldn't parse the class, so no check can be done. Just proceed with the standard //file deletion procedure. onDelete(versionRecordManager.getPathToLatest()); } }

Target:
Looks to me like the last parameter never does anything, but not sure if there is some location that uses it and it is just not in the diff.
Source:
public V get(final String key) { return super.get(key.toLowerCase()); }

Target:
Missing @Override annotations?
Source:
public static byte[] byteBufferToArray(ByteBuffer buf) { byte[] arr = new byte[buf.remaining()]; int prevPosition = buf.position(); buf.get(arr); buf.position(prevPosition); return arr; }

Target:
nit: maybe use `finally` to restore this value.
Source:
private boolean deleteRef() { if (!fs.retryFailedLockFileCommit()) return ref.delete(); // file deletion fails on windows if another // thread is reading the file concurrently // So let's try 10 times... for (int i = 0; i < 10; i++) { if (ref.delete()) { return true; } try { Thread.sleep(100); } catch (InterruptedException e) { // ignore } } return false; }

Target:
Style-nit: Braces aren't necessary here.
Source:
public Partition getPartitionObj(int idx) throws Exception { return partitionObjs == null ? null : (Partition)JSONMessageFactory.getTObj(partitionObjs.get(idx), Partition.class); }

Target:
Some of the partitionObjs entries can be NULL if the table is not partitioned. Need to handle it.
Source:
public void lock() { try { this.mutex.acquire(); } catch (Exception e) { throw new MessagingException("Failed to aquire mutex at " + this.path, e); } }

Target:
This isn't a Messaging component and from other side using this one within a Messaging component, raising a `MessagingException` from here, we prevent re-throwing a correct `MessagingException` with `failedMessage` context. So, for me simple `RuntimeException` is enough in this context. WDYT?
Source:
protected void executeCommand() { initConnectionList(true); for (Map.Entry<StorageType, List<StorageServerConnections>> connectionToType : getConnectionsTypeMap().entrySet()) { disconnectStorageByType(connectionToType.getKey(), connectionToType.getValue()); } if (FeatureSupported.cinderProviderSupported(getStoragePool().getCompatibilityVersion())) { // Unregister all libvirt secrets if needed unregisterLibvirtSecrets(); } }

Target:
please move it to inside the method to be consistent...
Source:
protected void executeVdsBrokerCommand() { UpdateGlusterGeoRepKeysVDSParameters parameters = getParameters(); status = getBroker().glusterGeoRepKeysUpdate(parameters.getRemoteUserName(), new ArrayList<>(parameters.getGeoRepPubKeys())); proceedProxyReturnValue(); }

Target:
Why you create new List here? getGeoRepPubKeys returns a list already.
Source:
public static void beforeClass() throws Exception { // Create a user adminSynapse = new SynapseAdminClientImpl(); SynapseClientHelper.setEndpoints(adminSynapse); adminSynapse.setUsername(StackConfigurationSingleton.singleton().getMigrationAdminUsername()); adminSynapse.setApiKey(StackConfigurationSingleton.singleton().getMigrationAdminAPIKey()); synapse = new SynapseClientImpl(); userId = SynapseClientHelper.createUser(adminSynapse, synapse); }

Target:
You are not setting the endpoints for this client
Source:
public void close() { waitForSendComplete(); // Close the buffers before closing the operators; this is needed as buffer ownership // is attached to the receive operators. suppressingClose(buffers); // close operator context for (OperatorContextImpl opContext : contexts) { suppressingClose(opContext); } closeNotConsumedRFWs(); suppressingClose(bufferManager); suppressingClose(allocator); }

Target:
I see that all the bloomFilters of RFW are allocated using [fragment context allocator](https://github.com/apache/drill/blob/master/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/join/HashJoinBatch.java#L836) not operator context so why does the order in which `closeNotConsumedRFWs()` is called matters here ?
Source:
public Long getPeerRouterId(String publicMacAddress, final long routerId) { final SearchCriteria<NicVO> sc = PeerRouterSearch.create(); sc.setParameters("instanceId", routerId); sc.setParameters("macAddress", publicMacAddress); sc.setParameters("vmType", VirtualMachine.Type.DomainRouter); NicVO nicVo = findOneBy(sc); if (nicVo != null) { return (new Long(nicVo.getInstanceId())); } return null; }

Target:
Let the auto-boxing and auto-unboxing do this for you. When you do this manually the pool of String/numbers of java will not be used. You just need to return `nicVo.getInstanceId()`
Source:
public List<Tree.Kind> nodesToVisit() { ArrayList<Tree.Kind> nodesToVisit = new ArrayList<>(super.nodesToVisit()); nodesToVisit.add(Tree.Kind.CLASS); nodesToVisit.add(Tree.Kind.ASSIGNMENT); nodesToVisit.add(Tree.Kind.STATIC_INITIALIZER); return nodesToVisit; }

Target:
Use `List<Tree.Kind>` for the variable declaration (always use interface for declaration, and implementation for instantiation.)
Source:
public void testXmlDeniesDuplicateGroupConfig() { expectDuplicateElementError("group"); String groupConfig = " <group>\n" + " <name>foobar</name>\n" + " <password>dev-pass</password>\n" + " </group>\n"; buildConfig(HAZELCAST_START_TAG + groupConfig + groupConfig + HAZELCAST_END_TAG, null); }

Target:
Super Minor: Format XMLs in this test to look like (unless you have some autoformatting, etc., then you can leave it as it is): ``` String groupConfig = " <group>\n" + " <name>foobar</name>\n" + " <password>dev-pass</password>\n" + " </group>\n"; ```
Source:
public boolean accepts( Event<?> evt ) { return applicationStatusSource.getSystemStatus().isNexusStarted() && ( evt instanceof RepositoryRegistryRepositoryEvent ) || ( evt instanceof RepositoryConfigurationUpdatedEvent ); }

Target:
You could also put the isNexusStarted method call after the "evt instanceof ..." checks - this should perform better because you'd avoid calling the synchronous method for other Nexus events. Also maybe add brackets to make it clear whether the status check applies to both events or just the registry one.
Source:
public static ISynchronizeService getSyncService(String syncServiceId) { ISynchronizeServiceDescriptor desc = SynchronizeServiceRegistry.getSynchronizeServiceDescriptor(syncServiceId); if(desc == null) return null; return desc.getService(); }

Target:
Braces required by coding convention.
Source:
private int getExtendedFlags() { if (!isExtended()) { return 0; } return NB.decodeUInt16(info, infoOffset + P_FLAGS2) << 16; }

Target:
I would prefer: if (isExtended()) return NB.decodeUInt16(info, infoOffset + P_FLAGS2) << 16; else return 0;
Source:
protected void update(final Map<String, Object> attributes) { final String id = (String) attributes.get(getIdAttribute()); logger.debug("Updating id: with attributes: {}", id, attributes); final Map<String,Object> profile = profiles.get(id); if (profile != null) { profile.putAll(attributes); } else { insert(attributes); } }

Target:
Cannot we just do: `profiles.put(id, attributes);`?
Source:
private <T extends DAO> T getDao(Class<T> daoType) { for (DAO dao : daos) { if (daoType.isAssignableFrom(dao.getClass())) { if (dao instanceof BaseDAODbFacade) { initBaseDAO((BaseDAODbFacade) dao); } return (T) dao; } } log.error("Can't find dao for " + daoType); return null; }

Target:
I still be able to see this line :/
Source:
private DatabaseClient(final String url) { MongoClient mongoClient = null; try { mongoClient = new MongoClient(url); } catch (UnknownHostException e) { LOG.info(LoggingConstants.EXCEPTION_MESSAGE, e); } if (mongoClient == null) { return; } database = mongoClient.getDB("submissions"); if (database == null) { LOG.info("Db is null!"); } else { setUpIndexes(); } }

Target:
chnge to error
Source:
public void undo() { if (fbType instanceof BasicFBType) { ((BasicFBType) fbType).getAlgorithm().add(((BasicFBType) fbType).getAlgorithm().indexOf(newAlgorithm), oldAlgorithm); updateECActions(false); ((BasicFBType) fbType).getAlgorithm().remove(newAlgorithm); } }

Target:
this shows that the algorithm list should be moved to the base fb. otherwise change alg type will not work for siimple fbs.
Source:
public long getLastSchedulingCycleRuntimeDelayMs() { return System.currentTimeMillis() - lastSchedulingCycleRunTimeMs.get(); }

Target:
nit: static import currentTimeMillis
Source:
public void synchronizeMailboxSynchronous_withAccountPolicySetToExpungeOnPoll_shouldExpungeRemoteFolder() throws Exception { messageCountInRemoteFolder(1); when(account.getExpungePolicy()).thenReturn(Account.Expunge.EXPUNGE_ON_POLL); configureRemoteStoreWithFolder(); controller.synchronizeMailboxSynchronous(account, FOLDER_NAME, listener, null); verify(remoteFolder).expunge(anySet()); }

Target:
`anySet()` is pretty weak. Can't we verify we pass in the right IDs?
Source:
public void onBackPressed() { Fragment currentFragment = fragmentManager .findFragmentById(R.id.fragment_holder); if (currentFragment instanceof About) { fragmentManager.popBackStack(FragmentTags.CARD_LIST, 0); return; } super.onBackPressed(); }

Target:
I prefer an `else` instead of this `return`.
Source:
public boolean select(Viewer viewer, Object parent, Object element) { IBreakpoint breakpoint = (IBreakpoint) element; IInteractionElement interactionElement = ContextCore.getContextManager().getElement( structureBridge.getHandleIdentifier(breakpoint)); if (interactionElement == null) { return true; } return !interactionElement.getInterest().isInteresting(); }

Target:
An instanceof check would be good in case other items are added to the view in the future.
Source:
public void scanFile(JavaFileScannerContext context) { super.context = context; if (isRegularExpression) { try { searchPattern = Pattern.compile(headerFormat, Pattern.DOTALL); } catch (RuntimeException e) { throw new IllegalArgumentException("[" + getClass().getSimpleName() + "] Unable to compile the regular expression: " + headerFormat, e); } } else { expectedLines = headerFormat.split("(?:\r)?\n|\r"); } visitFile(context.getFile()); }

Target:
seems quite wide to catch all RuntimeException : http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#compile(java.lang.String)
Source:
private boolean isAllowedToClone(Object value) { if(value == null){ System.out.print("null"); } return Objects.nonNull(value) && ((value instanceof String) || (classUtils.isPrimitiveClass(value.getClass()))); }

Target:
This method needs to enhance. I mean If the first `if` is true, then the code bellow is always false. Also I think `System.out.print("null");` should be replaced with some log.
Source:
public void validate(GlobalConfiguration globalConfig) { if(mediaType != null) { CONFIG.ignoringSpecificMediaTypes(); key().mediaType(mediaType); value().mediaType(mediaType); } keyContentTypeBuilder.validate(); valueContentTypeBuilder.validate(); }

Target:
Nitpick: space
Source:
public static void createDir(String path) throws IOException { try { Files.createDirectories(Paths.get(path)); } catch (AccessDeniedException e) { LOG.info("Fail to create folder " + path + "caused by AccessDeniedException"); } }

Target:
1. trick to use `LOG`: add exception as the last argument and it will be logged as the cause automatically. like this: ```java LOG.info("Fail to create folder " + path, e); ``` 2. actually i think we should throw this exception rather than swallow it. Why do you catch and convert the exception to log message?
Source:
public TraceStatusDMData() { this(false, false, false, 0, 0, 0, "", "", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ fTracingSupported = false; }

Target:
Why not use null instead of ""?
Source:
public ThrottlingExceptionRoutePolicy(int threshold, long failureWindow, long halfOpenAfter, List<Class<?>> handledExceptions) { this.throttledExceptions = handledExceptions; this.failureWindow = failureWindow; this.halfOpenAfter = halfOpenAfter; this.failureThreshold = threshold; this.keepOpen.set(false); }

Target:
I would replace those statements above with `this(handledExceptions,failureWindow,halfOpenAfter,threshold,false)`.
Source:
public void markRequestException(Exception e) { String errorMessage = e.getMessage().replaceAll(REGEX, "."); metricsRegistry.meter(errorNamespace(metricNamespace, e, errorMessage)).mark(); }

Target:
Using the error message in the metric could get really messy. These are arbitrary strings, and could be very long. For Error, we're using the error code–a _very_ different thing, since these are well known, and short. The exception type name is enough for Exceptions.
Source:
public void anonUserOnMobileCanSeeAppPromotion() { Promoting promoting = findPromoting(); Assertion.assertTrue(promoting.isMobileBannerDisplayed()); Assertion.assertStringContains(promoting.getPromotionAppMobileText(), MOBILE_PROMOTION_TEXT); }

Target:
Perhaps you can use static imports for everything form Assertion?
Source:
public void testWrongSelectionBug534319singleThread() throws Exception { waitForNonConsoleJobs(); // Run a few times since the problem doesn't occur always int iterations = 5; final String typeName = "Bug534319singleThread"; final String breakpointMethodName = "breakpointMethod"; doTestWrongSelectionBug534319(iterations, typeName, breakpointMethodName); }

Target:
Maybe move this to doTestWrongSelectionBug534319.
Source:
private boolean validateServers(Set<String> serverNames) { for (String serverName : serverNames) { if (getVdsStaticDao().getAllForHost(serverName).size() > 0 || getVdsStaticDao().getAllWithIpAddress(serverName).size() > 0) { return true; } } return false; }

Target:
Normally, a 'validate' method should return true in case of success, and false if validation failed.
Source:
public void update() { fboId = frameBuffersManager.getFBO(fboName).fboId; task.setFboId(fboId); task.setFboName(fboName); }

Target:
I don't think the fboName is ever going to change, will it?
Source:
public static String getContext() { return Bugsnag.getClient().getContext(); }

Target:
Ah - guessing that we are using static `Bugsnag` everywhere to make this whole interface possible. Any workarounds you can think of that would avoid depending on the static class?
Source:
public NameRevCommand add(Iterable<ObjectId> ids) throws MissingObjectException, JGitInternalException { for (ObjectId id : ids) { add(id); } return this; }

Target:
No curly braces.
Source:
public ParseFirewallRules(Json json) { super(json, TypeLiteral.get(FirewallRules.class)); }

Target:
Remove the public modifier from all injection constructors.
Source:
public int value( ) { return rand.nextInt(); }

Target:
shouldn't be private for all the types ?
Source:
private void setUpHttpLogging() throws IOException { if ( !getConfig().get( http_logging_enabled ) ) { return; } AsyncRequestLog requestLog = new AsyncRequestLog( dependencyResolver.resolveDependency( FileSystemAbstraction.class ), config.get( GraphDatabaseSettings.log_timezone ).getZoneId(), config.get( http_log_path ).toString(), config.get( http_logging_rotation_size ), config.get( http_logging_rotation_keep_number ) ); webServer.setRequestLog( requestLog ); }

Target:
Static import, for consistency? :)
Source:
public void testIterationStart(LoopIterationEvent event) { JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables(); if ((getControlledByThread() && !jMeterVariables.isSameUserOnNextIteration()) || getClearEachIteration()) { log.debug("Initialise cookies from pre-defined list"); // No need to call clear setProperty(initialCookies.clone()); } }

Target:
Does that mean `getClearEachIteration` impacts the result no matter of `getControlledByThread`?
Source:
private void appendRows(Map<Integer, Map<Integer, String>> rowsMap) { if (!rowsMap.isEmpty()) { rowsMap.forEach((rowIndex, cellValueMap) -> { model.insertRow(rowIndex, new ScenarioGridRow()); cellValueMap.forEach((columnIndex, cellValue) -> model.setCell(rowIndex, columnIndex, () -> new ScenarioGridCell(new ScenarioGridCellValue(cellValue)))); }); } }

Target:
I believe using `forEach` ensures nothing is done if collection is empty. We should remove the outer `if`.
Source:
public static boolean isAllowedToSettings(String loginId, Project project) { if(loginId == null) { return false; } User user = User.findByLoginId(loginId); if(user == null || user.isAnonymous()) { return false; } if(user.isSiteManager() || ProjectUser.isManager(user.id, project.id)) { return true; } return false; }

Target:
findByLoginId은 구조적으로 null을 return 하지 않음 (...) 방어코드를 줄이기 위해 NullUser Pattern이 쓰였는데 나중에 도입된거라 조금 아쉽게 만들어져 있긴 함
Source:
public void invalidate() { mActionMode.invalidate(); if (mMenu != null) { mMenu.invalidate(); } }

Target:
Either no brackets or put invalidate on its own line.
Source:
private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(myProjectSystemId); out.writeObject(myModuleName); out.writeObject(myRootDirPath); synchronized (myProxyDelegateLock) { if (myProxyDelegate == null) { // Compute the proxy object in case the proxy operation scheduled in the pooled thread is not yet completed. myProxyDelegate = reproxy(AndroidProject.class, myDelegate);; } } out.writeObject(myProxyDelegate); out.writeObject(mySelectedVariantName); out.writeObject(mySelectedTestArtifactName); }

Target:
double semicolon
Source:
public MainEventHandler() { String connectionlessProtocolList = Context.getConfig().getString("status.ignoreOffline"); if (connectionlessProtocolList != null) { connectionlessProtocols.addAll(Arrays.asList(connectionlessProtocolList.split(","))); } logEvents = Sets.newHashSet(Context.getConfig().getString("logger.events", DEFAULT_LOGGER_EVENTS).split(",")); }

Target:
I would prefer to use standard Java API instead and minimize dependencies usage when possible.
Source:
public E getRandomValue() throws NoSuchElementException { List<E> enumConstants = getFilteredList(); if (enumConstants.isEmpty()) { throw new NoSuchElementException("No enum element available for random picking."); } int randomIndex = random.nextInt(enumConstants.size()); return enumConstants.get(randomIndex); }

Target:
this should be checked at construction time. If the guy is excluding all values from the enum, throw him a beautiful IllegalArgumentException. Hence, `getRandomValue` should not declare throwing NoSuchElementException
Source:
public void setColor(int color) { this.setColor(color, color); }

Target:
remove this.
Source:
private boolean shouldBypassThrottling(HttpServletRequest request) { if (enableThrottlingIfHeader == null || enableThrottlingIfHeader.length() == 0) { return false; } return request.getHeader(enableThrottlingIfHeader) == null; }

Target:
A HTTP header named "" should probably be treated as invalid, I think we should refuse it at construction, not try to coerce it here.
Source:
private void print(List<List<Object>> keys, List<ValueUpdater> updaters) { for (int i = 0; i < keys.size(); i++) { ValueUpdater valueUpdater = updaters.get(i); Object arg = ((CombinerValueUpdater) valueUpdater).getArg(); LOG.debug("updateCount = {}, keys = => updaterArgs = {}", updateCount, keys.get(i), arg); } }

Target:
should this just print with info level since this is a debugState why make another hop to enable debug for this topology.
Source:
public MockSCMSource(String controllerId, String repository, List<SCMSourceTrait> traits) { super(); this.controllerId = controllerId; this.repository = repository; this.traits = new ArrayList<SCMSourceTrait>(traits); }

Target:
can be omitted
Source:
public MockSerializationResult(Proxifier proxifier, XStreamBuilder xstreambuilder, GsonSerializerBuilder gsonBuilder) { super(proxifier); this.response = new MockHttpServletResponse(); this.extractor = new DefaultTypeNameExtractor(); this.xstreambuilder = xstreambuilder; this.gsonBuilder = gsonBuilder; this.environment = new NullEnvironment(); }

Target:
change to `this(proxifier, ...., new NullEnvironment())`
Source:
public LocalCacheFileSystem(FileSystem fs, FileSystemContext fsContext) { super(fs); mFsContext = fsContext; // needs to be moved outside FileSystem constructor mLocalCacheManager = new LocalCacheManager(mFsContext); }

Target:
I don't feel very good about this constructor. It seems counter-intuitive to have the fsContext as an argument here. There is already an fsContext embededed within the `fs` object. Is there a better way to access it?
Source:
public long getID() { if (!isConnected()) { throw new IllegalStateException("Session must be connected first."); } return mSessionID; }

Target:
I'd remove the whole guard, and simply return null (mSessionID MUST be set to null when the session has left a realm already - and of course it must be null when the transport is detached then too)
Source:
static public <T> Flux<T> fluxInlineIfPossibleAsObs(Callable<Flux<T>> function, IRetryPolicy retryPolicy) { if (retryPolicy == null) { // shortcut return Flux.defer(() -> { try { return function.call(); } catch (Exception e) { return Mono.error(e); } }); } else { return BackoffRetryUtility.fluxExecuteRetry(() -> function.call(), retryPolicy); } }

Target:
Shouldn't this return `Flux.error(e)` ?
Source:
public int getTreeDepth() { if (currVisit == null) return 0; return currVisit.depth; }

Target:
style nit: missing braces
Source:
public Future<BlobInfo> getBlobInfo(String blobId) { FutureResult<BlobInfo> futureResult = new FutureResult<BlobInfo>(); OperationController oc = getOperationController(); if (oc == null) { completeOperation(futureResult, null, null, ROUTER_CLOSED_EXCEPTION); } else { oc.getBlobInfo(blobId, futureResult, null); } return futureResult; }

Target:
Any reason not to do `getBlobInfo(blobId, null)` directly? `completeOperation()` handles null callbacks anyway. Similar question for similar functions.
Source:
public void shouldNotLogMessageAsInfo() { logFeature.setLevel(DEPRECATED_LOGGER, "FATAL"); System.setProperty(Framework.NUXEO_DEV_SYSTEM_PROP, "false"); logDeprecatedMessageAndVerify(false); }

Target:
Talked in real, we can use `loggerClass` to do what we want.
Source:
public TimeGraphScale(Composite parent, TimeGraphColorScheme colors) { super(parent, colors, SWT.NO_BACKGROUND | SWT.NO_FOCUS | SWT.DOUBLE_BUFFERED); TmfSignalManager.register(this); addMouseListener(this); addMouseMoveListener(this); TimeDraw.updateTimeZone(); addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { TmfSignalManager.deregister(TimeGraphScale.this); } }); }

Target:
lambda?
Source:
private Map<String, TopologyIracVersion> generateNewVectorFunction(Integer s, Map<String, TopologyIracVersion> versions) { if (versions == null) { return Collections.singletonMap(localSite, TopologyIracVersion.newVersion(topologyId)); } else { Map<String, TopologyIracVersion> copy = new HashMap<>(versions); copy.compute(localSite, this::incrementVersionFunction); return Collections.unmodifiableMap(copy); } }

Target:
I would say just store the actual Map directly and instead return the map wrapped by an unmodifiable map. Otherwise we will have extra allocations on every operation for the unmodifiable wrappers internally when they aren't needed.
Source:
private HashMap<String, String> getParamsForQuery() { HashMap<String, String> params = new HashMap<>(); params.put(METRIC_PARAM, getValidTableName(name)); params.put(AGGREGATOR_PARAM, SUM_AGGREGATOR); params.put(TIME_PARAM, DEFAULT_TIME); return params; }

Target:
`Map`
Source:
public String getDisplayValue() { CutoffFacetNode lastNode = this.getHighestTierNode(); if (lastNode == null) return null; return lastNode.getSearchKey(); }

Target:
Why use getSearchKey rather than getDisplayValue?
Source:
public PagesSpatialIndexFactory(List<Type> types, List<Type> outputTypes) { this.types = ImmutableList.copyOf(types); this.outputTypes = outputTypes; }

Target:
nit: `ImmutableList.copyOf(`
Source:
public boolean isStreamedTrace() { if (fSessionInfo.isSnapshotSession()) { return fSessionInfo.getSnapshotInfo().isStreamedSnapshot(); } return fSessionInfo.isStreamedTrace(); }

Target:
these lines should be moved in the SessionInfo class instead. Otherwise each user of SessionInfo has to do the same check (see SessionConfigGenerator)
Source:
public void releaseMacsOnCommit(List<String> macs) { log.debug("Non-tx, non-compensation state, immediately releasing macs {}.", Arrays.toString(macs.toArray())); macs.forEach(macPool::freeMac); }

Target:
why not to rely on AbstractCollection..toString?
Source:
public String getDescription(String ruleKey) { ConnectedRuleDetails details = ruleDetails(ruleKey); if (details == null) { return null; } String extendedDescription = details.getExtendedDescription(); if (extendedDescription.isEmpty()) { return details.getHtmlDescription(); } return details.getHtmlDescription() + "<br/><br/>" + details.getExtendedDescription(); }

Target:
```suggestion return details.getHtmlDescription() + "<br/><br/>" + extendedDescription; ```
Source:
private void verifyRunListForEnvironment(Map<String, List<String>> envRunList, String envName, String... expectedEntries) { assertTrue(envRunList.containsKey(envName), "envRunList contains " + envName); assertEquals(envRunList.get(envName).size(), expectedEntries.length, "envRunList size for '" + envName); assertTrue(envRunList.get(envName).containsAll(Arrays.asList(expectedEntries)), "envRunList for e1 contains " + Arrays.asList(expectedEntries)); }

Target:
Make this public static so you can call it from the live test too and avoid the code duplication?
Source:
private void checkStoreAvailability() { if (!enabled) return; if (!isAvailable()) { throw unavailableException; } }

Target:
Couldn't this just check `unavailableException` if it is null or not? Seems we wouldn't need the `managerAvailable` variable as well then.
Source:
public void addTest(Class<?> testClass) { System.out.println("Adding class without a run: " + testClass.getName()); allTestClasses.add(testClass); }

Target:
use logger
Source:
public CompatibilityModeConfiguration(boolean enabled, Marshaller marshaller) { this.enabled = enabled; this.marshaller = marshaller; }

Target:
If this constructor is to be called only by the builder, remove the public modifier
Source:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_USER_ATTR_VIRT); attr.setFriendlyName("loa"); attr.setDisplayName("Level of assurance"); attr.setType(Integer.class.getName()); attr.setDescription("The highest value of LoA from all user's userExtSources."); return attr; }

Target:
We historically use "String" value type for LoA, since it's like that in all production DBs. Please fix type to String in both modules (user|member:virt:loa). Thank you.
Source:
public Intersection(SimpleFeature intersectionFeature, AttributeGetter getter) { this.point = (Point) intersectionFeature.getDefaultGeometry(); this.attGet = getter; this.transectId = (Integer) attGet.getValue(TRANSECT_ID_ATTR, intersectionFeature); this.distance = (Double) attGet.getValue(DISTANCE_ATTR, intersectionFeature); this.isMeanHighWater = getBooleanFromMhwAttribute(attGet.getValue(MHW_ATTR, intersectionFeature)); this.feature = intersectionFeature; }

Target:
One suggestion, this might be useful to put in the AttributeGetter code since it is a special case for this attribute. I don't know whether that would cause issues elsewhere though.
Source:
Parent( String parentAttribute ) { this.parentAttribute = parentAttribute; }

Target:
Let's make it public.
Source:
public static List<SchemaPath> projectList(String... names) { List<SchemaPath> selected = new ArrayList<>(); for (String name : names) { if (name.equals(SchemaPath.DYNAMIC_STAR) || name.equals("*")) { selected.add(SchemaPath.STAR_COLUMN); } else { selected.add(SchemaPath.parseFromString(name)); } } return selected; }

Target:
As far as I understand start column is replaced with `**` in Calcite, do we need to check for `*` as well?
Source:
private static String asText(JsonNode node) { Preconditions.checkState(node.isValueNode()); return node.isNull() ? null : node.asText(); }

Target:
static import
Source:
public void testFilterOptionsForConstraintTypeLiteralWhenConstraintValueIsFormula() { when(plugin.constraintValue()).thenReturn(BaseSingleFieldConstraint.TYPE_RET_VALUE); final String[] result = page.filterOptionsForConstraintTypeLiteral(OperatorsOracle.EXPLICIT_LIST_OPERATORS); final List<String> operators = Arrays.asList(result); assertFalse(operators.contains("in")); assertFalse(operators.contains("not in")); assertEquals(0, operators.size()); }

Target:
Are these "contains" assertions necessary? You're checking ```operators.size() == 0```
Source:
public static Future<?> deleteFeedMediaOfItem(final Context context, final long mediaId) { if (UserPreferences.shouldDeleteRemoveFromQueue()) { DBWriter.removeQueueItem(context, DBReader.getFeedMedia(mediaId).getItem(), false); } return doDeleteFeedMediaOfItem(context, mediaId); }

Target:
The main logic is run at the end: it is somewhat counter-intuitive. More of a style issue: as both the `dodeleteFeedMediaOfItem()` and `removeQueueItem()` are really run asynchronously anyway.
Source:
public void clientCallback(ClientResponse response) throws Exception { m_responses[m_index] = new ClientResponseWithPartitionKey(m_partitionKey, response); m_partitionCounter.decrementAndGet(); if (m_partitionCounter.get() == 0) { m_cb.clientCallback(m_responses); } }

Target:
Could combine this line with the next one.
Source:
public synchronized IResource getResource( IReferencePoint referencePoint, IPath referencePointRelativePath) { if (referencePoint == null) throw new NullPointerException("Reference point is null"); if (referencePointRelativePath == null) throw new NullPointerException("Path is null"); org.eclipse.core.resources.IProject project = get(referencePoint); if (project == null) throw new NullPointerException( "For reference point " + referencePoint + " does'nt exist a project."); return project.findMember(referencePointRelativePath); }

Target:
I would prefer IllegalArgumentException