auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Iterator<DataFactory<ENTITY>> iterator() { return Iterators.iterator( new DataFactory<ENTITY>() { @Override public Data<ENTITY> create( Configuration config ) { return new Data<ENTITY>() { @Override public CharReadable stream() { return last = factory.apply( config ); } @Override public Decorator<ENTITY> decorator() { return decorator; } }; } } ); }

Target:
Great place for a lambda ;) ```java return Iterators.iterator( config -> new Data<ENTITY>() { @Override public CharReadable stream() { return last = factory.apply( config ); } @Override public Decorator<ENTITY> decorator() { return decorator; } } ); ```
Source:
public void insertLocator(Locator locator) throws IOException { Session session = DatastaxIO.getSession(); // get shard this locator would belong to long shard = (long) Util.getShard(locator.toString()); // bound values and execute BoundStatement bs = putValue.bind(shard, locator.toString(), ""); Timer.Context timer = Instrumentation.getWriteTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); try { session.execute(bs); } finally { timer.stop(); } }

Target:
May be the `BoundStatement` part also should be part of the timer execution?
Source:
private Set<Type> interfacesWithSubstitution(Symbol.TypeSymbol symbol, TypeSubstitution substitution) { return symbol.interfaces().stream() .map(interfaceType -> applySubstitution(interfaceType, substitution)) .flatMap(substitutedInterfaceType -> supertypes(substitutedInterfaceType).stream()) .collect(Collectors.toSet()); }

Target:
why 2 operations ? only one flatmap is sufficient no ?
Source:
public void setAdvancedRecentChangesCheckbox() { selectTab(PreferencesPageObject.tabNames.UNDER); waitForElementClickableByElement(useAdvancedRecentChangesCheckbox); useAdvancedRecentChangesCheckbox.click(); PageObjectLogging.log("Use_advanced_recent_changes_checkbox", "Use_advanced_recent_changes_checkbox clicked", true); }

Target:
fluent chaining would be nice
Source:
protected StringUtils() { }

Target:
Just curious, why do we need to change the access qualifier to protected?
Source:
public int readBatch() throws Exception { ColumnReader<?> firstColumnStatus = readState.getFirstColumnReader(); int currBatchNumRecords = readState.batchSizerMgr().getCurrentRecordsPerBatch(); long recordsToRead = Math.min(currBatchNumRecords, readState.getRemainingValuesToRead()); int readCount = 0; if (recordsToRead > 0) { readCount = readRecords(firstColumnStatus, recordsToRead); } readState.fillNullVectors(readCount); return readCount; }

Target:
use `?`: `int readCount = recordsToRead > 0 ? ...`
Source:
public List<Project> getProjects() { List<Project> projects; try { projects = projectLoader.fetchAllActiveProjects(); for (Project proj : projects) { loadAllProjectFlows(proj); } } catch (ProjectManagerException e) { throw new RuntimeException("Could not load projects from store.", e); } return projects; }

Target:
initialize projects
Source:
public static Object encodeObject(Object dataToEncode) { Object returnValue = dataToEncode; if (dataToEncode instanceof byte[]) { returnValue = SafeEncoder.encode((byte[]) dataToEncode); } else if (dataToEncode instanceof ArrayList) { ArrayList arrayToDecode = (ArrayList)dataToEncode; ArrayList returnValueArray = new ArrayList(arrayToDecode.size()); for (Object arrayEntry : arrayToDecode) { returnValueArray.add(encodeObject(arrayEntry)); } returnValue = returnValueArray; } return returnValue; }

Target:
I would have replace ArrayList with List. ``` if (dataToEncode instanceof List) { List arrayToDecode = (List)dataToEncode; List returnValueArray = new ArrayList(arrayToDecode.size()); for (Object arrayEntry : arrayToDecode) { returnValueArray.add(encodeObject(arrayEntry)); } ```
Source:
public MongoDbMetadataStore(MongoDbFactory factory, String collectionName) { template = new MongoTemplate(factory); this.collectionName = (StringUtils.hasText(collectionName)) ? collectionName : DEFAULT_COLLECTION_NAME; }

Target:
This ctor has to invoke the other one with similar logic as I described above. DRY - in other words.
Source:
private void scheduleJobs(long regularInterval, long initialInterval) { executor.scheduleWithFixedDelay(() -> refresh(), initialInterval, regularInterval, TimeUnit.MINUTES); }

Target:
Why not this::refresh ?
Source:
public void accept(FluxSink<T> fluxSink) { FluxSinkRecorderDelegate<T> previousDelegate = this.delegate; synchronized (this) { delegate = new DirectDelegate<>(fluxSink); previousDelegate.accept(fluxSink); } }

Target:
shouldn't this be synchronized as well?
Source:
public void shutdownBlobStore(PartitionId id){ DiskManager diskManager = partitionToDiskManager.get(id); if(diskManager != null){ diskManager.shutdownBlobStore(id); } }

Target:
doc
Source:
public Class<?> getImplementationClass(CodeGenerator<?> cg) throws ClassTransformationException { try { return compileClass( cg ); } catch (CompileException | ClassNotFoundException e) { throw new ClassTransformationException(e); } catch (IOException e) { throw new ClassTransformationException(e); } }

Target:
Multi-catch?
Source:
public Meteor(ItemStack catalystStack, List<MeteorComponent> components, float explosionStrength, int radius) { this.catalystStack = catalystStack; this.components = components; this.explosionStrength = explosionStrength; this.radius = radius; int weight = 0; for (MeteorComponent component : components) weight += component.getWeight(); this.maxWeight = weight; this.cost = 1000000; }

Target:
GSON initializes classes with reflection and not the constructor. The default definition should be set at the field declaration.
Source:
private byte[] getParticipantObjectQueryForResponse(PRPAIN201306UV02 response) throws JAXBException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (response.getControlActProcess() != null && response.getControlActProcess().getQueryByParameter() != null) { getMarshaller().marshal(response.getControlActProcess().getQueryByParameter(), baos); } return baos.toByteArray(); }

Target:
Is response guaranteed to be non-null at this point?
Source:
public List<RpslObject> getByKeys(final ObjectType type, final Collection<CIString> searchKeys) { final List<RpslObject> result = new ArrayList<>(searchKeys.size()); for (final CIString searchKey : searchKeys) { try { result.add(getByKey(type, searchKey)); } catch (EmptyResultDataAccessException ignored) { LOGGER.debug("EmptyResultDataAccessException in class ", ignored.getMessage(), ignored.getClass().getName()); } } return result; }

Target:
This is an expected exception, if there is no matching row in the database, can we ignore it instead?
Source:
public void testParseCommodityCodeList() { byte[] content = commodityCodeUpdateService.getFileContent(DATA_FILE_PATH); ArrayList<CommodityCode> someCommodityCodes = (ArrayList<CommodityCode>) commodityCodeUpdateService.parseCommodityCodeList(content); assertNotEquals(content.length, 0); assertEquals(NUMBER_OF_RECORDS_IN_DATA_FILE, someCommodityCodes.size()); }

Target:
I don't think it's necessary to cast the returned collection to an ArrayList, since the assertions below are only checking the collection's total size.
Source:
public static long getLeapYearsBefore(final long prolepticYear) { long yearBefore = prolepticYear - 1; return (yearBefore / 4) - (yearBefore / 100) + (yearBefore / 400); }

Target:
`getLeapYearsBefore(...)` should not be public.
Source:
public void time() throws Exception { TimeStat stat = new TimeStat(ticker); stat.time((Callable<Void>) () -> { ticker.increment(10, TimeUnit.MILLISECONDS); return null; }); TimeDistribution allTime = stat.getAllTime(); assertEquals(allTime.getCount(), 1.0); assertEquals(allTime.getMin(), 0.010); assertEquals(allTime.getMax(), 0.010); }

Target:
Is the cast needed? There is only one `time(x)` method
Source:
public boolean hasTextMaxAngle() throws MBFormatException { return parse.isPropertyDefined(layout, "text-max-angle"); }

Target:
Maybe group this with wherever getTextMaxAngle is defined, just to make it easier to find related methods? Also, does this need to be public? Probably better if it is protected or private.
Source:
public static Logger getLogger(Class<?> key) { return LOGGERS.computeIfAbsent(key.getName(), name -> new FailsafeLogger(LOGGER_ADAPTER.getLogger(key))); }

Target:
I would suggest : ```java return LOGGERS.computeIfAbsent(key.getName(), name -> new FailsafeLogger(LOGGER_ADAPTER.getLogger(name))); ``` for a better readability. Note parameter for `getLogger` has been changed from `key` to `name`.
Source:
public boolean verifyAddVm(List<String> reasons, int nicsCount, int vmPriority, MacPool macPool) { if (!verifyMacPool(reasons, nicsCount, macPool)) { return false; } else if (!isVmPriorityValueLegal(vmPriority, reasons)) { return false; } return true; }

Target:
Why not just return else if isVmPriorityValueLegal(vmPriority, reasons); Instead of this whole else block?
Source:
public boolean isTrue(State state, String[] params) { if ((this.spaceName != null && !this.spaceName.equals("")) && !this.spaceName.equals(params[1])) { return false; } ObjectInstance space = state.getObject(params[1]); return SpaceFactory.getOnOff(space); }

Target:
!this.spaceName.equals("") -> !this.spaceName.isEmpty()
Source:
public void visitFunctionDef(FunctionDef functionDef) { FunctionSymbol functionSymbol = ((FunctionDefImpl) functionDef).functionSymbol(); ParameterList parameters = functionDef.parameters(); if (functionSymbol != null && functionSymbol.is(Symbol.Kind.FUNCTION) && parameters != null) { FunctionSymbolImpl functionSymbolImpl = (FunctionSymbolImpl) functionSymbol; functionSymbolImpl.setParametersWithType(parameters); } super.visitFunctionDef(functionDef); }

Target:
I think `functionSymbol.is(Symbol.Kind.FUNCTION)` shouldn't be necessary
Source:
public SavedStateRegistry<Bundle> getBundleSavedStateRegistry() { return mSavedStateRegistry; }

Target:
Make this final
Source:
public static ZonedDateTime parse(String dateString) { int n = 0; for (DateTimeFormatter df : DATE_TIME_FORMATTERS) { try { return toZonedDateTime(df.parse(dateString)); } catch (DateTimeParseException dte) { // we ignore wrong formats n++; continue; } } if (IS_NUMERIC_P.matcher(dateString) .matches()) { long ldate = Long.parseLong(dateString); return Instant.ofEpochMilli(ldate) .atZone(UTC_ZONE_ID); } return null; }

Target:
What does the `n` variable do here?
Source:
public Optional<RGBValues> getFillColor() { RGBValues rgbValues = null; if (style instanceof NodeStyle) { rgbValues = new NodeStyleQuery((NodeStyle) style).getBackgroundColor().get(); } else if (style instanceof FlatContainerStyle) { rgbValues = ((FlatContainerStyle) style).getBackgroundColor(); } else if (style instanceof ShapeContainerStyle) { rgbValues = ((FlatContainerStyle) style).getBackgroundColor(); } return Optional.ofNullable(rgbValues); }

Target:
Copy/Paste error: should be ShapeContainerStyle. This causes errors in tests: java.lang.ClassCastException: org.eclipse.sirius.diagram.business.internal.metamodel.spec.ShapeContainerStyleSpec cannot be cast to org.eclipse.sirius.diagram.FlatContainerStyle at org.eclipse.sirius.diagram.ui.business.internal.query.ColorStyleQuery.getFillColor(ColorStyleQuery.java:105)
Source:
public void indexMembers() throws InterruptedException { MassIndexer mi = Search.getFullTextEntityManager(em).createIndexer(Member.class); mi.startAndWait(); Search.getFullTextEntityManager(em).flushToIndexes(); }

Target:
There is no need to flush here
Source:
public void testGetPublicKeyPairNullInput1() { try{ KeyGenUtils.getPublicKeyPair(null, truePublicKeys[0]); } catch (UnsupportedTypeException e) { fail("UnsupportedTypeException thrown"); } }

Target:
Is it possible to declare the function with `throws UnsupportedTypeException` instead of the try-catch? (Other functions do similarly.) Will JUnit still fail reasonably if it does throw?
Source:
private boolean containsNullOrEmpty(List<String> values) { //return values != null && ( values.contains(null) || values.contains("") ); if(values == null) return true ; if(values.isEmpty()) return true ; for(String str : values) { if(StringUtils.isBlank(str)) return true ; } return false; }

Target:
Another minor note, any reason not to merge this into a single check? `if(values == null || values.isEmpty()) return true ;`
Source:
public static <T> Flowable<T> fromOptional(@NonNull Optional<T> optional) { ObjectHelper.requireNonNull(optional, "optional is null"); return optional.map(Flowable::just).orElseGet(Flowable::empty); }

Target:
+NonNull for return type
Source:
private static Map<AbstractProject,DependencyChange> getDependencyChanges(Run<?,?> run) { AbstractBuild<?,?> build = null; if(run instanceof AbstractBuild) return ((AbstractBuild) run).getDependencyChanges((AbstractBuild)run); //jenkins workflow plugin etc. else return Maps.newHashMap(); }

Target:
Unused
Source:
public void onRemoved(Iterable<CacheEntryEvent<? extends K, ? extends V>> events) throws CacheEntryListenerException { for (Object event1 : events) { CacheEntryEvent event = (CacheEntryEvent) event1; Assert.assertEquals(EventType.REMOVED, event.getEventType()); this.removed.incrementAndGet(); event.getKey(); if (event.isOldValueAvailable()) { event.getOldValue(); } } }

Target:
Same regarding cast
Source:
Attribute(String name, ModelType type, CapabilityReferenceRecorder reference) { this.definition = new SimpleAttributeDefinitionBuilder(name, type, true) .setCapabilityReference(reference) .setFlags(Flag.RESTART_RESOURCE_SERVICES) .build(); }

Target:
But the attribute actually is required. So we'd be reporting incorrect metadata to work around a test fixture problem?
Source:
Page<Book> getDefaultPageable(Pageable pageable) { if (pageable != null) { return new PageImpl<>(Collections.singletonList(new Book()), pageable, 1); } return new PageImpl<>(Collections.emptyList(), pageable, 0); }

Target:
I think we have to (should) stay with Java 6 syntax here.
Source:
public String getEmbedMapID(){ String mapID = mapFrame.getAttribute("data-mapid"); return mapID; }

Target:
combine the two lines and return the String
Source:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_FACILITY_ATTR_DEF); attr.setFriendlyName("accountExpirationTime"); attr.setDisplayName("Accoun expiration."); attr.setType(Integer.class.getName()); attr.setDescription("Account expiration."); return attr; }

Target:
"Account" instead of "Accoun"
Source:
private Disk clone(Disk parent) { Disk disk = new Disk(); disk.setId(parent.getId()); disk.setVm(new VM()); if (parent.isSetVm()) { disk.getVm().setId(parent.getVm().getId()); } return disk; }

Target:
disk.setVm(new VM()); should be inside of this /if/
Source:
public boolean shouldRun() { final boolean shouldRun = pendingPartitions.size() > 0; return shouldRun; }

Target:
not synchronized
Source:
public static String join(String[] array) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String s : array) { if (first) { first = false; } else { sb.append('.'); } sb.append(s); } return sb.toString(); }

Target:
What is the reason for the longer version? EDIT: ok, did no see it was from hibernate. You could use `String.join` from Java 8 though.
Source:
public synchronized void lock() { hasBeenInitialized = true; internalMap = ImmutableMap.copyOf(internalMap); }

Target:
I imagine the ```synchronized``` keyword is going to move up to init and then this will become private. Is there any situation where we want this to be locked externally?
Source:
private String findHostId(String hostName) throws DotDataException { String hostId = null; DotConnect dc = new DotConnect(); dc.setSQL(SELECT_HOSTID_BY_NAME_QUERY); dc.addParam(hostName); List<Map<String,String>> result = dc.loadResults(); if(!result.isEmpty()){ hostId = result.get(0).get("identifier").toString(); } return hostId; }

Target:
![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') "get" returns a string, there's no need to call "toString()". [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS1858)
Source:
public void notifyCameraDeviceClose() { synchronized (mExecutingCaptureConfigCallbacks) { for (CaptureConfigCaptureCallback callback : mExecutingCaptureConfigCallbacks) { callback.onRequestCancelled(); } mExecutingCaptureConfigCallbacks.clear(); } notifySurfaceDetached(); }

Target:
Should this just call the StateCallback.onClosed() method? And should the onClosed() method aslo have the request canceling?
Source:
public boolean commit() { if (os != null) { unlock(); throw new IllegalStateException(MessageFormat.format(JGitText.get().lockOnNotClosed, ref)); } saveStatInformation(); try { FileUtils.rename(lck, ref, StandardCopyOption.ATOMIC_MOVE); haveLck = false; token.close(); return true; } catch (IOException e) { unlock(); return false; } }

Target:
shouldn't we set token to null now? If a token is succesfully closed and the link has been deleted we shouldn't keep references to it.
Source:
public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription delegatingResourceDescription = new DelegatingResourceDescription(); delegatingResourceDescription.addProperty("fulfillerStatus"); delegatingResourceDescription.addProperty("fulfillerComment"); delegatingResourceDescription.addProperty("uuid"); delegatingResourceDescription.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); delegatingResourceDescription.addSelfLink(); return delegatingResourceDescription; }

Target:
You don't need these properties because they actually don't exist nor apply
Source:
public gov.hhs.fha.nhinc.common.connectionmanagerinfo.UDDIUpdateManagerForceRefreshResponseType forceRefreshFileFromUDDIServer( gov.hhs.fha.nhinc.common.connectionmanagerinfo.UDDIUpdateManagerForceRefreshRequestType uddiUpdateManagerForceRefreshRequest) { LOG.info("forceRefreshFileFromUDDIServer"); UDDIUpdateManagerHelper helper = new UDDIUpdateManagerHelper(); return helper.forceRefreshFileFromUDDIServer(uddiUpdateManagerForceRefreshRequest); }

Target:
I don't think we ever use this method again
Source:
void remove(Closeable hook) { if (closeHooks != null) { closeHooks.remove(hook); } }

Target:
synchronization issue here.
Source:
private boolean isInTimeRange(ITmfTimestamp traceStartTime, ITmfTimestamp traceEndTime) { if (traceStartTime.compareTo(fEndTimeRange) <= 0 && traceEndTime.compareTo(fStartTimeRange) >= 0) { return true; } return false; }

Target:
return the condition 's value directly?
Source:
public void testMakingAttachment() { testMakingAttachmentFile("attachment.txt","normal text file") }

Target:
missing semicolon;
Source:
@Test public void givesAllArgsAChanceToShrink() { assertThat(testResult(GivesAllArgsAChanceToShrink.class), failureCountIs(2)); assertThat(Others.shrinkAttempts, greaterThan(0)); }

Target:
shrinkAttempts should be greaterThan(1) (equal to 2), or did I misunderstand that?
Source:
private void waitForStatus(final long jobId, final Status status) throws InterruptedException, TimeoutException { CommonUtils.waitFor("Waiting for job status", () -> { try { return mJobMaster.getStatus(jobId).getStatus() == status; } catch (Exception e) { Throwables.propagate(e); } return null; }, WaitForOptions.defaults().setInterval(10).setTimeoutMs(10 * Constants.SECOND_MS)); }

Target:
why is this needed?
Source:
public Predicate<ChangeData> message(String text) { return new MessagePredicate(args.dbProvider, args.repoManager, args.index, text); }

Target:
Since the message operator is now only supported if the secondary index is enabled, we should check for this before creating the predicate (the same way as it is done for the file operator): if (args.index == ChangeIndex.DISABLED) { throw error("secondary index must be enabled for message:" + text); }
Source:
public boolean setBranchSameAsAccess(boolean branchSameAsAccess) { return this.branchSameAsAccess = branchSameAsAccess; }

Target:
Other setters in this class are void.
Source:
public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay readerWay, EncodingManager.Access access, long relationFlags) { if (readerWay.hasTag("toll", "yes")) tollEnc.setEnum(false, edgeFlags, Toll.ALL); if (readerWay.hasTag("toll:hgv", "yes")) tollEnc.setEnum(false, edgeFlags, Toll.HGV); return edgeFlags; }

Target:
For an edge with: ``` toll=yes toll:hgv=yes ``` This would result in `Toll.HGV` and not `Toll.ALL`
Source:
@Override public boolean isPlayer() { return false; }

Target:
Fix your formatter settings please or disable it :wink:
Source:
byte[] byteArrayFromInt(int val) { byte[] b = new byte[4]; b[3] = (byte) (val); b[2] = (byte) (val >>> 8); b[1] = (byte) (val >>> 16); b[0] = (byte) (val >>> 24); return b; }

Target:
It doesn't really matter, but could be: ```java return new byte[] { (byte) (val >>> 24), (byte) (val >>> 16), (byte) (val >>> 8), (byte) val }; ```
Source:
protected int getFontStyle(String fontStyleExpression, EAttribute eAttribute, FontData defaultFontData, StyledText text) { int fontStyle = defaultFontData.getStyle(); if (fontStyleExpression != null && !fontStyleExpression.isEmpty()) { Eval eval = new Eval(interpreter, variableManager); String fontStyleValue = eval.get(eAttribute, fontStyleExpression, String.class); fontStyle = getFontStyle(fontStyleValue, fontStyle, text); } return fontStyle; }

Target:
not useful, you are not using this method outside of the AbstractEEFLifecycleManager
Source:
private static HandlerDecorator buildDecorator(Class<? extends HandlerDecorator> decoratorClass) { HandlerDecorator decorator; try { decorator = decoratorClass.getConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new IllegalStateException("Decorator class " + decoratorClass + "cannot be instantiated", e); } return decorator; }

Target:
We could the variable declaration and just use `return decoratorClass.getConstructor().newInstance();`
Source:
private XML(String identifier) { this.identifier = identifier; }

Target:
Modifier 'private' is redundant for Enum constructor - needs to be removed.
Source:
public CompareToBuilder append(final boolean lhs, final boolean rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs) { comparison = +1; } else { comparison = -1; } return this; }

Target:
Why do we need `+` here?
Source:
private JavaSymbolicObject expandMacro(JavaSymbolicObject node) { JavaSymbolicObject expandedNode = (JavaSymbolicObject) node.accept(this); while (!node.equals(expandedNode)) { node = expandedNode; expandedNode = (JavaSymbolicObject) node.accept(this); } return node; }

Target:
pretty sure this was right before... This looks like it might have an impact on performance. Why was this change made?
Source:
public ExtendedSymbolKindType(int _v) { try { SymbolKind s = SymbolKind.forValue(_v); value = _v; isProtocolSymbol = true; } catch (IllegalArgumentException e) { try { CquerySymbolKind c = CquerySymbolKind.forValue(_v); value = _v; isProtocolSymbol = false; } catch (IllegalArgumentException y) { throw new IllegalArgumentException("Illegal value for SymbolKind"); } } }

Target:
The variable 's' is not used. If you're doing this for the bounds check, you can just do 'SymbolKind.forValue(_v)' and discard the return value. (Does your IDE show a warning for the unused variable? If not, you may want to turn that on. In general, please try to avoid introducing new warnings if they can be avoided. (Sometimes, it cannot be avoided; for example, Server2ClientProtocolExtension derives from LanguageClientImpl which is technically not public API, and the API tooling gives me a warning about that, but there's nothing we can do about it except suppress it.))
Source:
private boolean applyTypedFilter(Instance instance) { // Loop through all the type filters for (String type : this.typeFilters.keySet()) { if (checkType(instance.getDefinition(), type)) { // instance equals type name for (Filter innerFilter : this.typeFilters.get(type)) { if (innerFilter.match(instance)) return true; } // So, instance matches type and but does not match filter return false; } } // it reaches here that means Instance does not match any type of // type filters. Method should return true. return true; }

Target:
But returning true here will result in the OR to yield always true, meaning that when an instance's type does not match the type of a type filter it will always be included, no matter what the result of the unconditional filters would be.
Source:
public void synchronized setServiceContext(ServiceContext ctx) { setContext(ctx); }

Target:
synchronized should be before void. Seems you didn't run `mvn clean package` after making this change else the compiler would have caught it. See travis error here https://travis-ci.org/openmrs/openmrs-core/builds/320193916#L2148
Source:
public void testNoAvailabilitiesSetsActivelyPublishedToFalse() throws IOException { LoveFilmDataRow row = rowFromFile("battle-royale-no-availability.csv"); Optional<Content> extracted = extractor.extract(row); assertTrue(extracted.isPresent()); Content content = extracted.get(); Film film = (Film) content; assertFalse(film.isActivelyPublished()); }

Target:
Not strictly necessary, since the .get() will throw if there's no extracted content.
Source:
public ClusterFeatures list() { ClusterFeatures features = new ClusterFeatures(); Set<AdditionalFeature> addlFeatures = BackendClusterFeatureHelper.getClusterFeatures(this, version); addlFeatures.forEach(clusterFeature -> { org.ovirt.engine.api.model.ClusterFeature feature = addLinks(ClusterFeaturesMapper.map(clusterFeature, null)); features.getClusterFeatures().add(feature); }); return features; }

Target:
You can use just "map" here, it is defined in the base class.
Source:
public QueryInfo updateQueryInfo(Optional<StageInfo> stageInfo) { QueryInfo queryInfo = getQueryInfo(stageInfo); if (queryInfo.isFinalQueryInfo()) { session.getSessionLogger().log(() -> "Marking query finally done"); queryInfo.setSessionLogEntries(session.getSessionLogger().getEntries()); finalQueryInfo.compareAndSet(Optional.empty(), Optional.of(queryInfo)); } return queryInfo; }

Target:
nit: remove
Source:
public Object execute(ExecutionEvent event) { InputDialog dialog = new InputDialog(Display.getCurrent() .getActiveShell(), Messages.PerfSaveSession_title, Messages.PerfSaveSession_msg, "", new IInputValidator() { //$NON-NLS-1$ @Override public String isValid(String newText) { if ("".equals(newText)) { //$NON-NLS-1$ return Messages.PerfSaveSession_invalid_filename_msg; } return null; } }); if (dialog.open() == Window.OK) { saveData(dialog.getValue()); } return null; }

Target:
You would better use newText.isEmpty() here.
Source:
public void unsubscribeOthers(AmbSubscriber<T> notThis) { for (AmbSubscriber<T> other : ambSubscribers) { if (other != notThis) { other.unsubscribe(); } ambSubscribers.clear(); } }

Target:
`ambSubscribers.clear();` should be out of the loop.
Source:
protected IPageStore newPersistentStore() { StoreSettings storeSettings = application.getStoreSettings(); Bytes maxSizePerSession = storeSettings.getMaxSizePerSession(); File fileStoreFolder = storeSettings.getFileStoreFolder(); if (storeSettings.isEncrypted()) { return new SerializingPageStore(new CryptingPageStore(new DiskPageStore(application.getName(), fileStoreFolder, maxSizePerSession)), getSerializer()); } else { return new DiskPageStore(application.getName(), fileStoreFolder, maxSizePerSession, getSerializer()); } }

Target:
Maybe it would be nice to not make the chain configurable by a field in general but to have something more spring like. (Like in case of spring Filters) They implemented it with a List in which you can add filter at various places and they delegate to each other. You can add new filters in between like filters.add(0,new MyFilter(...)); WDYT?
Source:
public void onInfoWindowClick(Marker marker) { // Stop any callbacks to refresh the vehicle marker popup balloons mCustomInfoWindowAdapter.cancelUpdates(); // Show trip details screen for the vehicle associated with this marker ObaTripStatus status = mMarkerData.getStatusFromMarker(marker); String focusedStopId = mController.getFocusedStopId(); if (mController != null && mController.getFocusedStopId != null) { TripDetailsActivity.start(mActivity, status.getActiveTripId(), focusedStopId); } else { TripDetailsActivity.start(mActivity, status.getActiveTripId()); } }

Target:
@azizmb9494 It looks like the Amazon implementation is slightly different here than the Google implementation. Sometimes this can happen if the Gradle copy script doesn't execute properly when you're building the Google variant. Could you try re-building this project again using any of the Google build variants (oba, agencyx, agencyy) to re-generate the Amazon code, and then push that new version here?
Source:
public ElevationModule(ElevationGridCoverageFactory factory) { gridCoverageFactory = factory; cachedElevationsFile = null; readCachedElevations = false; writeCachedElevations = false; elevationUnitMultiplier = 1; }

Target:
Use `this(factory, null, false, false, 1)`. Then if someone add/remove a new parameter to the "main" constructor he/she needs to make a decision what to do with this one.
Source:
public int maxDepth( Envelope referenceEnvelope, Envelope range, int nbrDim, int maxLevel ) { double searchRatio = range.getArea() / referenceEnvelope.getArea(); final int i = (int) (Math.log( searchRatio ) / Math.log( Math.pow( 2, nbrDim ) )) + extraLevels; return i; }

Target:
I'm not sure, but do we need to use the natural logarithmic here or are you just after logarithmic behaviour in general? In the latter case, it would be more efficient to use `log2`, I suppose. Then you could write this as `(int) (Math.log2(searchRatio) / nbrDim) + extraLevels`
Source:
public StatementsMatcher(List<Statement> statements) { Collections.copy(statements, unmatched); }

Target:
Its the _Matcher_ that gets reused multiple times - the list probably doesn't.
Source:
public void addNewAuthorization() { if (groups.get(0).getRule() != null) { groups.add(0, new AuthorizationGroupBean()); } }

Target:
What if groups is empty at this point ?
Source:
public static boolean allUnique(List<String> argListNames) { return argListNames.stream().allMatch(new HashSet<>()::add); }

Target:
`new HashSet<>(list).size() == list.size();`
Source:
private void fixSize() { perspSwitcherToolbar.pack(); perspSwitcherToolbar.getParent().pack(); perspSwitcherToolbar.getShell().requestLayout(); }

Target:
Shouldn't requestLayout be called on the perspSwitcherToolbar Control directly, instead of the Shell?
Source:
protected final List<?> createValues() { if (withNulls == Nulls.ALL) { return NULL_VALUES; } if (withNulls == Nulls.PARTIAL) { return IntStream.range(0, ROWS).mapToObj(i -> i % 2 == 0 ? createValue() : null).collect(toList()); } return IntStream.range(0, ROWS).mapToObj(i -> createValue()).collect(toList()); }

Target:
nit: switch statement would be more natural here ``` switch (withNulls) { case ALL: return NULL_VALUES; case PARTIAL: return IntStream.range(0, ROWS).mapToObj(i -> i % 2 == 0 ? createValue() : null).collect(toList()); default: return IntStream.range(0, ROWS).mapToObj(i -> createValue()).collect(toList()); } ```
Source:
protected void setComparator(Comparator comparator) { this.comparator = comparator; Iterable items = getItems(); if (items == null) { return; } Iterable identicalItems = (comparator == null) ? new ArrayList() : new TreeSet(comparator); for (Object item : items) { setItems(identicalItems); } }

Target:
did you mean- for (Object item : items) { identicalItems.add(item); } setItems(identicalItems); - Cause now the loop is redundant and you reset the old items when you set the comparator.
Source:
public void notifySurfaceDetached() { // Release active image reader in detached listener super.notifySurfaceDetached(); // Release inactive image readers if (mImageReaderToReleaseList.size() > 0) { for (ImageReaderProxy imageReader : mImageReaderToReleaseList) { Surface surface = imageReader.getSurface(); if (surface != null) { surface.release(); } imageReader.close(); } mImageReaderToReleaseList.clear(); } }

Target:
Use isEmpty() or alternatively, don't have to check size, the for loop will not run if it is empty.
Source:
private T findUniqueResult() { if (collection.size() == 1) { return collection.iterator().next(); } return uniqueResult; }

Target:
Ternary if?
Source:
public MetadataMap getMetadata() { if (metadata == null) { metadata = new MetadataMap(); } return metadata; }

Target:
If you are going to do this do you need to @sychronize? If not indicate it is not threadsafe...
Source:
public void updateMemoryUsage(long deltaUserMemoryInBytes, long deltaTotalMemoryInBytes) { long currentUserMemoryValue = currentUserMemory.addAndGet(deltaUserMemoryInBytes); long currentTotalMemoryValue = currentTotalMemory.addAndGet(deltaTotalMemoryInBytes); peakUserMemory.updateAndGet(currentPeakValue -> Math.max(currentUserMemoryValue, currentPeakValue)); peakTotalMemory.updateAndGet(currentPeakValue -> Math.max(currentTotalMemoryValue, currentPeakValue)); }

Target:
`currentXXMemoryValue` is a weird name; maybe we can just inline these two variables. Or use `currentUserMemory.get()` below.
Source:
public final Date getExtendedExpiresOn() { return this.mExtendedExpiresOn; }

Target:
> this [](start = 15, length = 4) no this. please
Source:
public FileInfo(FileSystem srcFs, Path sourcePath, String subDir) { this.srcFs = srcFs; this.sourcePath = sourcePath; this.cmPath = null; this.checkSum = null; this.useSourcePath = true; this.subDir = subDir; }

Target:
this constructor can directly call the below one
Source:
public boolean isAuthorized() { if (session.isVoAdmin(voId)) { return true; } else { return group != null && session.isGroupAdmin(groupId); } }

Target:
Hi, since existing object ids start with 1 and you define voId/groupId=0 by default, then you can safely use something like: `session.isVoAdmin(voId) || session.isGroupAdmin(groupId)` in the first IF.
Source:
public String propertyForUserName(Criteria criteria, boolean creator) { criteria.createAlias("creator", "creator"); criteria.createAlias("lastModifier", "lastModifier"); return creator ? "creator.loginName" : "lastModifier.loginName"; }

Target:
`"creator"` and `"lastModifier"` should be added to `STANDARD_ALIASES` instead of creating the aliases here
Source:
public List<RadiologyReport> getRadiologyReportsByRadiologyOrderAndRadiologyReportStatus(RadiologyOrder radiologyOrder, RadiologyReportStatus radiologyReportStatus) { List<RadiologyReport> result = sessionFactory.getCurrentSession() .createCriteria(RadiologyReport.class) .add(Restrictions.eq("radiologyOrder", radiologyOrder)) .add(Restrictions.eq("reportStatus", radiologyReportStatus)) .list(); return result == null ? new ArrayList<RadiologyReport>() : result; }

Target:
use final
Source:
public static Boolean notExists( EvaluationContext ctx, List tests, Object target) { for (Object test : tests) { Boolean r = applyUnaryTest(ctx, test, target); if (r != null && r) return false; } return true; }

Target:
just double checking that this is really the intent? change looks odd..
Source:
public Optional<U> generate(final WebContext context, final U profile) { init(); final U linkedProfile = profileService.findByLinkedId(profile.getId()); if (linkedProfile != null) { return Optional.of(linkedProfile); } else { if (failIfLinkedUserNotFound) { throw new TechnicalException("No linked account found for: " + profile); } else { // fallback to the original account return Optional.ofNullable(profile); } } }

Target:
the ofNullable makes no sense because you called profile.getId() on it at the beginning of the method: if it was null we wouldn't have arrived here in the code. The profile parameter is meant to be non-null.
Source:
public String toString() { return "SslSession(alpn=" + (alpn == null ? "null" : alpn) + ", npn=" + (npn == null ? "null" : npn) + ", version=" + (version == null ? "null" : version) + ", cipher=" + (cipher == null ? "null" : cipher) + ", establishedTime=" + Long.toString(establishedTime) + ", peerCert=" + (peerCert == null ? "null" : peerCert.toString()) + ")"; }

Target:
There is no need to do check for null, right? I mean you could just write something like return "SslSession(alpn=" + alpn +...
Source:
/* package */void openFirstTimeWindow() { final boolean showProgress = PrefUtil.getAPIPreferenceStore().getBoolean( IWorkbenchPreferenceConstants.SHOW_PROGRESS_ON_STARTUP); if (!showProgress) { doOpenFirstTimeWindow(); } else { // We don't know how many plug-ins will be loaded, // assume we are loading a tenth of the installed plug-ins. // (The Eclipse SDK loads 7 of 86 plug-ins at startup as of // 2005-5-20) final int expectedProgressCount = Math.max(1, WorkbenchPlugin.getDefault().getBundleCount()); runStartupWithProgress(expectedProgressCount, () -> doOpenFirstTimeWindow()); } }

Target:
I would move this down to 2508 where it's used.
Source:
public String getY() { return y; }

Target:
change to package-private access
Source:
public void run() { Object selection = getStructuredSelection().getFirstElement(); if (selection instanceof IBuild) { IBuild build = (IBuild) selection; if (editor != null) { abortBuild(build, editor); } else { abortBuild(build); } } else if (selection instanceof IBuildPlan) { IBuildPlan buildPlan = (IBuildPlan) selection; abortBuild(buildPlan.getLastBuild()); } }

Target:
this just calls abortBuild with a null editor, so why not just delete the if and call abortBuild(build,editor)
Source:
private boolean hasNotAllowedTwoEmptyLinesBefore(DetailAST token) { boolean result = false; if (!allowMultipleEmptyLines) { result = hasEmptyLineBefore(token) && isPrePreviousLineEmpty(token); } return result; }

Target:
Why was this changed? The logic looks the same.
Source:
public boolean matches(String type, URI uri, String realm) { //Realm is not used as for now boolean match = true; match &= AuthScheme.NEGOTIATE.toString().equalsIgnoreCase(type); match &= getServiceUri().getScheme().equalsIgnoreCase(uri.getScheme()); match &= getServiceUri().getHost().equalsIgnoreCase(uri.getHost()); return match; }

Target:
Rewrite this as a single boolean expression: ``` java return AuthScheme.NEGOTIATE... && getServiceUri().getScheme()..... && .... ```
Source:
public static boolean isStringAssignable(TypeKind kind, boolean isPrimitive, String in) { NumberFormatValidator validator = VALIDATORS.get( kind ); return validator != null ? validator.validate( isPrimitive, in ) : false; }

Target:
How about `validator != null && validator.validate( isPrimitive, in )`
Source:
private LockManager() { locks = new Hashtable<URI, LockProvider>(); }

Target:
No point in Hashtable if you are protecting the map yourself anyway by your own synchronized methods.
Source:
public final Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable { if (!passivation) { //if we don't have passivation then it is a simple remove from DataContainer. The CDL already locks the key in //commit entries (EntryWrappingInterceptor) return invokeNextInterceptor(ctx, command); } final Object key = command.getKey(); try { cdl.lock(key, true); return invokeNextInterceptor(ctx, command); } finally { cdl.unlock(key); } }

Target:
Do we want this to throw a TimeoutException? My thinking is if you couldn't acquire the lock we just return without running next interceptor and make it a noop like method defines.
Source:
boolean hasInflightBatches(TopicPartition topicPartition) { return topicPartitionBookkeeper.contains(topicPartition) && !topicPartitionBookkeeper.getPartition(topicPartition).inflightBatchesBySequence.isEmpty(); }

Target:
Does this method need to be synchronized?
Source:
protected void executeQueryCommand() { List<GlusterServerService> serviceList = null; if(getParameters().getServiceType() == null) { serviceList = getGlusterServerServiceDao().getByClusterId(getParameters().getId()); } else { serviceList = getGlusterServerServiceDao().getByClusterIdAndServiceType(getParameters().getId(), getParameters().getServiceType()); } if(serviceList != null && serviceList.size() > 0) { getQueryReturnValue().setReturnValue(serviceList); } }

Target:
Question (matter of choise) - don't you prefer to set it anyway? if serverList is null or empty, setReurnValue will contain a null or empty list -what's the problem with that?
Source:
ViewerSorter createSorterInstance() throws CoreException { Object contributed = element.createExecutableExtension(ATT_CLASS); if (contributed instanceof ViewerSorter) { return (ViewerSorter) contributed; } if (contributed instanceof ViewerComparator) { return new WrappedViewerComparator((ViewerComparator) contributed); } throw new ClassCastException("Class contributed by " + element.getNamespaceIdentifier() + //$NON-NLS-1$ " to " + INavigatorContentExtPtConstants.TAG_NAVIGATOR_CONTENT + //$NON-NLS-1$ "/" + INavigatorContentExtPtConstants.TAG_COMMON_SORTER //$NON-NLS-1$ + " is not an instance of " + ViewerComparator.class.getName() + ": " + contributed.getClass().getName() //$NON-NLS-1$ //$NON-NLS-2$ ); }

Target:
Why package-visible?
Source:
public <X> X unwrap(Long value, Class<X> type, WrapperOptions options) { log.debug( " unwrap !" ); byte[] bytes = ByteBuffer.allocate( Long.SIZE ).putLong( value ).array(); return (X) new BsonBinary( bytes ); }

Target:
This debug message is not very useful
Source:
public final <R> R as(@NonNull CompletableConverter<? extends R> converter) { try { return ObjectHelper.requireNonNull(converter, "converter is null").apply(this); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); throw ExceptionHelper.wrapOrThrow(ex); } }

Target:
Please add `@Experimental` and `@since 2.1.7 - experimental` to all of them.
Source:
public Object instantiateItem(ViewGroup collection, int position) { int resId = PAGE_READING_LISTS; switch (position) { case PAGE_READING_LISTS: resId = R.id.list_of_lists_page; break; case PAGE_LIST_DETAIL: resId = R.id.list_detail_page; break; default: } return getView().findViewById(resId); }

Target:
Is this a find/replace artifact? Semantically it should probably still be explicitly set to 0. (I imagine you've only initialized it to please the IDE/checkstyle).
Source:
public void initialize(URI uri, Configuration configuration) throws IOException { this.dataTier.initialize(uri, configuration); }

Target:
remove `this.`
Source:
public static void main(String[] args) { int status = getConf(args); System.exit(status); }

Target:
`System.exit(getConf(args));`
Source:
public void processBean(CRResolvableBean bean, IndexWriter writer) throws CRException { System.out.println(writer.numDocs()); }

Target:
done
Source:
public List<@NonNull ITimeGraphEntry> getChildren() { return Collections.<@NonNull ITimeGraphEntry>emptyList(); }

Target:
This is changing behaviour. I'd do that separately.
Source:
public void addNewMailNotification(Account account, LocalMessage message, int previousUnreadMessageCount) { boolean hasHighPriority = false; for (String iter : message.getHeader("X-Priority")) { if (iter.contains(context.getString(R.string.x_priority))) hasHighPriority = true; } newMailNotifications.addNewMailNotification(account, message, previousUnreadMessageCount, hasHighPriority); }

Target:
this logic should be part of `Message`. it's also unnecessary to check all headers, just the first one should suffice.
Source:
public void loadTrace(ITmfTrace trace) { super.loadTrace(trace); updateContent(); clearContent(); }

Target:
I'm not sure if this change is intentional, but it shouldn't make a difference with TmfCommonXLineChartViewer because of its use of asyncExec(). However since updateContent() is abstract here, it would seem that clearContent() should be called first.
Source:
public static void killAllSpawnedHadoopJobs(String logFilePath, Logger log) { Set<String> allSpawnedJobs = findApplicationIdFromLog(logFilePath, log); log.info("applicationIds to kill: " + allSpawnedJobs); for (String appId : allSpawnedJobs) { try { killJobOnCluster(appId, log); } catch (Throwable t) { log.warn("something happened while trying to kill this job: " + appId, t); } } }

Target:
Seems like it is useful for this method to return a list of Hadoop jobs that were killed by this method and caller can print them out.
Source:
public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (!(this.getClass().equals(o.getClass()))) { return false; } SitePropertySource that = (SitePropertySource) o; return Objects.equal(mFilename, that.mFilename); }

Target:
is this because of the inheritance?
Source:
public void testFetchSkipsBlackedOutNodes() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); client.updateMetadata(initialUpdateResponseWithLeaderEpoch); Node node = initialUpdateResponse.brokers().iterator().next(); client.blackout(node, 500); assertEquals(0, fetcher.sendFetches()); time.sleep(500); assertEquals(1, fetcher.sendFetches()); }

Target:
Do we need to change some of these other tests? We're still using `initialUpdateResponse` above in `assignFromUser` and below.
Source:
public DefaultByteBufHolder(ByteBuf data) { ObjectUtil.checkNotNull(data, "data"); this.data = data; }

Target:
nit: you can merge both lines above as `checkNotNull` will return the given argument
Source:
public synchronized void removeConnection(Socket conn) { try { connections.remove(conn); conn.close(); } catch (IOException ioe) { tsLogger.i18NLogger.warn_could_not_close_transaction_listener_connection(conn, ioe); } finally { notifyAll(); } }

Target:
I think it would be clearer if the connections.remove was outside of this block as I don't think it will be throwing IOException, unless you think the notifyAll always done even with a problem on the linkedlist.remove() but if that is the case perhaps the conn.close() should be in it's own try block?
Source:
public List<CourseGroup> getLecturing() { String userId = proxy.getCurrentUser().getDisplayName(); List <CourseGroupDAO> groupDaos = dao.findLecturingCourseGroups(userId); List<CourseGroup> groups = new ArrayList<CourseGroup>(groupDaos.size()); for(CourseGroupDAO groupDao : groupDaos) { groups.add(new CourseGroupImpl(groupDao, this)); } return groups; }

Target:
You're getting the display name and using it todo a search my userId. Either there is a bug in the UserProxy or this code is wrong.
Source:
protected SLDGenerator(Item item, Item selectedItem, Integer ribbon, SLDConfig config) { this.item = item; this.ribbon = ribbon; if (config instanceof ShorelineConfig) { ShorelineConfig slc = (ShorelineConfig)config; slc.finalize(item, selectedItem); this.config = slc; } else { this.config = config; } }

Target:
Seems at this point you could just pass in the selectedItem instead of both.
Source:
public static void copy(File source, File dest) throws IOException { try (InputStream in = new FileInputStream(source)) { try (OutputStream out = new BufferedOutputStream(new FileOutputStream(dest))) { transferData(in, out); } } }

Target:
consider replacing 96-97 with just one try block (see line 455)
Source:
public XWikiAttachment setAttachment(XWikiAttachment attachment) { attachment.setDoc(this); XWikiAttachmentList list = this.attachmentList; XWikiAttachment currentAttachment = list.getByFilename(attachment.getFilename()); list.set(attachment); return currentAttachment; }

Target:
set() already take care of this so you could simply return the result of set().
Source:
public PropertyValue(MAPIProperty property, long flags, byte[] data) { this.property = property; this.flags = flags; this.data = data; this.actualType = property.usualType; }

Target:
could you call this(property, flags, data, null) ?
Source:
public boolean charTyped(char p_charTyped_1_, int p_charTyped_2_) { if (super.charTyped(p_charTyped_1_, p_charTyped_2_) || !canEdit) { return true; } else if (SharedConstants.isAllowedCharacter(p_charTyped_1_)) { this.insertTextIntoPage(Character.toString(p_charTyped_1_)); return true; } else { return false; } }

Target:
Again, parameter names
Source:
Map<String, String> getAPITypeParameters() throws BonitaHomeNotSetException, ServerAPIException { Map<String, String> parameters; try { parameters = APITypeManager.getAPITypeParameters(); } catch (IOException e) { throw new ServerAPIException(e); } return parameters; }

Target:
Could be great to return an empty map instead of null
Source:
public static Driver createDriver(DriverContext driverContext, List<Operator> operators) { Driver driver = new Driver(requireNonNull(driverContext, "driverContext is null"), requireNonNull(operators, "operators is null")); driver.initialize(); return driver; }

Target:
Move the `requireNonNull` checks to a separate line. Calling them inline looks messy.