auphong2707/dl4se-code-review-dataset huggingface dataset:
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 START public void widgetDisposed(DisposeEvent e) { END TmfSignalManager.deregister(TimeGraphScale.this); } }); } lambda?

Target:
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((e) -> { TmfSignalManager.deregister(TimeGraphScale.this); }); }
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); START return Collections.unmodifiableMap(copy); END } } 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.

Target:
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 copy; } }
Source:
START private HashMap<String, String> getParamsForQuery() { END 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; } `Map`

Target:
private Map<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; }
Source:
public String getDisplayValue() { CutoffFacetNode lastNode = this.getHighestTierNode(); if (lastNode == null) return null; START return lastNode.getSearchKey(); END } Why use getSearchKey rather than getDisplayValue?

Target:
public String getDisplayValue() { return getSearchKey(); }
Source:
public PagesSpatialIndexFactory(List<Type> types, List<Type> outputTypes) { this.types = ImmutableList.copyOf(types); START this.outputTypes = outputTypes; END } nit: `ImmutableList.copyOf(`

Target:
public PagesSpatialIndexFactory(List<Type> types, List<Type> outputTypes) { this.types = ImmutableList.copyOf(types); this.outputTypes = ImmutableList.copyOf(outputTypes); }
Source:
public boolean isStreamedTrace() { if (fSessionInfo.isSnapshotSession()) { START return fSessionInfo.getSnapshotInfo().isStreamedSnapshot(); END } return fSessionInfo.isStreamedTrace(); } these lines should be moved in the SessionInfo class instead. Otherwise each user of SessionInfo has to do the same check (see SessionConfigGenerator)

Target:
public boolean isStreamedTrace() { return fSessionInfo.isStreamedTrace(); }
Source:
public void releaseMacsOnCommit(List<String> macs) { log.debug("Non-tx, non-compensation state, immediately releasing macs {}.", START Arrays.toString(macs.toArray())); END macs.forEach(macPool::freeMac); } why not to rely on AbstractCollection..toString?

Target:
public void releaseMacsOnCommit(List<String> macs) { log.debug("Non-tx, non-compensation state, immediately releasing macs {}.", macs); macs.forEach(macPool::freeMac); }
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(); } START return details.getHtmlDescription() + "<br/><br/>" + details.getExtendedDescription(); END } ```suggestion return details.getHtmlDescription() + "<br/><br/>" + extendedDescription; ```

Target:
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/>" + extendedDescription; }
Source:
START private void verifyRunListForEnvironment(Map<String, List<String>> envRunList, String envName, END 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)); } Make this public static so you can call it from the live test too and avoid the code duplication?

Target:
public static 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)); }
Source:
private void checkStoreAvailability() { if (!enabled) return; START if (!isAvailable()) { END throw unavailableException; } } Couldn't this just check `unavailableException` if it is null or not? Seems we wouldn't need the `managerAvailable` variable as well then.

Target:
private void checkStoreAvailability() { if (!enabled) return; if (unavailableException != null) { throw unavailableException; } }
Source:
public void addTest(Class<?> testClass) { START System.out.println("Adding class without a run: " + testClass.getName()); END allTestClasses.add(testClass); } use logger

Target:
public void addTest(Class<?> testClass) { allTestClasses.add(testClass); }
Source:
START public CompatibilityModeConfiguration(boolean enabled, Marshaller marshaller) { END this.enabled = enabled; this.marshaller = marshaller; } If this constructor is to be called only by the builder, remove the public modifier

Target:
CompatibilityModeConfiguration(boolean enabled, Marshaller marshaller) { this.enabled = enabled; this.marshaller = marshaller; }
Source:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_USER_ATTR_VIRT); attr.setFriendlyName("loa"); attr.setDisplayName("Level of assurance"); START attr.setType(Integer.class.getName()); END attr.setDescription("The highest value of LoA from all user's userExtSources."); return attr; } 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.

Target:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_USER_ATTR_VIRT); attr.setFriendlyName("loa"); attr.setDisplayName("Level of assurance"); attr.setType(String.class.getName()); attr.setDescription("The highest value of LoA from all user's userExtSources."); return attr; }
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); START this.isMeanHighWater = getBooleanFromMhwAttribute(attGet.getValue(MHW_ATTR, intersectionFeature)); END this.feature = intersectionFeature; } 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.

Target:
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 = attGet.getBooleanFromMhwAttribute(attGet.getValue(MHW_ATTR, intersectionFeature)); this.feature = intersectionFeature; }
Source:
START Parent( String parentAttribute ) { END this.parentAttribute = parentAttribute; } Let's make it public.

Target:
public Parent( String parentAttribute ) { this.parentAttribute = parentAttribute; }
Source:
public static List<SchemaPath> projectList(String... names) { List<SchemaPath> selected = new ArrayList<>(); for (String name : names) { if (name.equals(SchemaPath.DYNAMIC_STAR) || START name.equals("*")) { END selected.add(SchemaPath.STAR_COLUMN); } else { selected.add(SchemaPath.parseFromString(name)); } } return selected; } As far as I understand start column is replaced with `**` in Calcite, do we need to check for `*` as well?

Target:
public static List<SchemaPath> projectList(String... names) { List<SchemaPath> selected = new ArrayList<>(); for (String name : names) { if (name.equals(SchemaPath.DYNAMIC_STAR)) { selected.add(SchemaPath.STAR_COLUMN); } else { selected.add(SchemaPath.parseFromString(name)); } } return selected; }
Source:
private static String asText(JsonNode node) { START Preconditions.checkState(node.isValueNode()); END return node.isNull() ? null : node.asText(); } static import

Target:
private static String asText(JsonNode node) { checkState(node.isValueNode()); return node.isNull() ? null : node.asText(); }
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); START assertFalse(operators.contains("in")); END assertFalse(operators.contains("not in")); assertEquals(0, operators.size()); } Are these "contains" assertions necessary? You're checking ```operators.size() == 0```

Target:
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); assertEquals(0, operators.size()); }
Source:
public static Future<?> deleteFeedMediaOfItem(final Context context, final long mediaId) { if (UserPreferences.shouldDeleteRemoveFromQueue()) { DBWriter.removeQueueItem(context, DBReader.getFeedMedia(mediaId).getItem(), false); } START return doDeleteFeedMediaOfItem(context, mediaId); END } 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.

Target:
public static Future<?> deleteFeedMediaOfItem(final Context context, final long mediaId) { Future res = doDeleteFeedMediaOfItem(context, mediaId); if (UserPreferences.shouldDeleteRemoveFromQueue()) { DBWriter.removeQueueItem(context, DBReader.getFeedMedia(mediaId).getItem(), false); } return res; }
Source:
public void clientCallback(ClientResponse response) throws Exception { m_responses[m_index] = new ClientResponseWithPartitionKey(m_partitionKey, response); START m_partitionCounter.decrementAndGet(); END if (m_partitionCounter.get() == 0) { m_cb.clientCallback(m_responses); } } Could combine this line with the next one.

Target:
public void clientCallback(ClientResponse response) throws Exception { m_responses[m_index] = new ClientResponseWithPartitionKey(m_partitionKey, response); if (m_partitionCounter.decrementAndGet() == 0) { m_cb.clientCallback(m_responses); } }
Source:
public synchronized IResource getResource( IReferencePoint referencePoint, IPath referencePointRelativePath) { if (referencePoint == null) throw new NullPointerException("Reference point is null"); START if (referencePointRelativePath == null) throw new NullPointerException("Path is null"); END 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); } I would prefer IllegalArgumentException

Target:
public IResource getResource(IReferencePoint referencePoint, IPath referencePointRelativePath) { if (referencePoint == null) throw new IllegalStateException("Reference point is null"); if (referencePointRelativePath == null) throw new IllegalStateException("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); }
Source:
protected boolean doSelect(Viewer viewer, Object parent, Object element) { if (element instanceof PackageFragmentRootContainer) { if (isApplicable() && viewer instanceof StructuredViewer) { PackageFragmentRootContainer rootContainer = (PackageFragmentRootContainer) element; START if (rootContainer.getChildren().length > 0) { return hasFilteredChildren((StructuredViewer) viewer, rootContainer); } return false; END } } return true; } convert to conditional expression (? :).

Target:
protected boolean doSelect(Viewer viewer, Object parent, Object element) { if (element instanceof PackageFragmentRootContainer) { if (isApplicable() && viewer instanceof StructuredViewer) { PackageFragmentRootContainer rootContainer= (PackageFragmentRootContainer) element; return rootContainer.getChildren().length > 0 ? hasFilteredChildren((StructuredViewer) viewer, rootContainer) : false; } } return true; }
Source:
public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); START List<String> types = new ArrayList<String>(session.getLogManager().getTypes()); END Collections.sort(types); return createResponse(types); } Definitely remove the sorting. If possible, don't convert to a List either, if JSON serialization prints a Set as a JSON array.

Target:
public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); Set<String> types = session.getLogManager().getTypes(); return createResponse(types); }
Source:
public boolean addStateTransition(final ActivationState from, final EventType event, final ActivationState to) { START Objects.requireNonNull(from, "From state cannot be null!"); END Objects.requireNonNull(event, "Event cannot be null!"); Objects.requireNonNull(to, "To state cannot be null!"); Transition transition = new Transition(from, event, to); return addStateTransition(transition); } Duplicate non-null check (also done in Transition).

Target:
public boolean addStateTransition(final ActivationState from, final EventType event, final ActivationState to) { return addStateTransition(new Transition(from, event, to)); }
Source:
Type leastUpperBound(List<Type> typeAlternatives) { START return types.leastUpperBound(typeAlternatives.toArray(new Type[typeAlternatives.size()])); END } Why convulotions between list and array ?

Target:
Type leastUpperBound(List<Type> typeAlternatives) { return types.leastUpperBound(typeAlternatives); }
Source:
public Response getOpenApiSpec(@Context HttpHeaders headers, @Context UriInfo uriInfo, @PathParam("type") String type, @Context ServletConfig config, @Context Application app) throws Exception { START setOpenApiConfiguration(oasConfig); END Response response = super.getOpenApi(headers, config, app, uriInfo, type); response.getHeaders().add("Access-Control-Allow-Origin", "*"); return response; } Still not thread safe. Needs to be done at startup / postconstruct.

Target:
public Response getOpenApiSpec( @Context HttpHeaders headers, @Context UriInfo uriInfo, @PathParam("type") String type, @Context ServletConfig config, @Context Application app) throws Exception { Response response = getOpenApi(headers, config, app, uriInfo, type); response.getHeaders().add("Access-Control-Allow-Origin", "*"); return response; }
Source:
public Optional<RestRouterConfiguration> build() { if (this.enabled) { try { validate(); } catch (Exception e) { throw logger.configurationValidationError(e); } return Optional.of(new RestRouterConfiguration(ip, port)); } START return Optional.empty(); END } I'm really used to the builders creating all their children all the time, is it really worth doing it differently here?

Target:
public RestRouterConfiguration build() { if (this.enabled) { try { validate(); } catch (Exception e) { throw logger.configurationValidationError(e); } return new RestRouterConfiguration(ip, port); } return null; }
Source:
protected void initSelectedType() { final VmInterfaceType defaultNicType = getDeafultNicTypeByProfile(); final Collection<VmInterfaceType> vnicTypes = supportedVnicTypes == null ? new ArrayList<VmInterfaceType>() : supportedVnicTypes; START if (getNicType().getItems() != vnicTypes) { END getNicType().setItems(vnicTypes, defaultNicType); } else { getNicType().setSelectedItem(defaultNicType); } } Why not getNicType().getItems() != null?

Target:
protected void initSelectedType() { final VmInterfaceType defaultNicType = getDeafultNicTypeByProfile(); final Collection<VmInterfaceType> vnicTypes = supportedVnicTypes == null ? new ArrayList<VmInterfaceType>() : supportedVnicTypes; if (getNicType().getItems() == null) { getNicType().setItems(vnicTypes, defaultNicType); } else { getNicType().setSelectedItem(defaultNicType); } }
Source:
public TestToolUtils() throws IOException { START super(); END } Why does this need a super()?

Target:
public TestToolUtils() throws IOException
Source:
private Guid getStorageDomainId(Guid poolId, StorageDomainType type, StorageDomainStatus status) { return getStorageDomains(poolId, type, START status).stream().map(StorageDomain::getId).findFirst().orElse(Guid.Empty); END } Isn't there a way to first of all get the first item and only if present return the idea? Can save the mapping of the complete list just to return the first one (IIUC)

Target:
private Guid getStorageDomainId(Guid poolId, StorageDomainType type, StorageDomainStatus status) { return getStorageDomains(poolId, type, status).stream().findFirst().map(StorageDomain::getId).orElse(Guid.Empty); }
Source:
START public static List<PostAggregator> prunePostAggregators(TopNQuery query) END { return AggregatorUtil.pruneDependentPostAgg( query.getPostAggregatorSpecs(), query.getTopNMetricSpec().getMetricName(query.getDimensionSpec()) ); } This doesn't need to be public, it's only called from within this file.

Target:
private static List<PostAggregator> prunePostAggregators(TopNQuery query) { return AggregatorUtil.pruneDependentPostAgg( query.getPostAggregatorSpecs(), query.getTopNMetricSpec().getMetricName(query.getDimensionSpec()) ); }
Source:
START private boolean isSuspiciousClassInstantiation(ExpressionTree callee) { END if (callee.is(Tree.Kind.NAMESPACE_NAME)) { NamespaceNameTree classNameTree = (NamespaceNameTree) callee; QualifiedName className = getFullyQualifiedName(classNameTree); return SUSPICIOUS_CLASS_INSTANTIATIONS.stream().anyMatch(className::equals); } return false; } I would put this method just after `isGlobalGetOptMethod()`, to group methods in logical call order.

Target:
private boolean isSuspiciousClassInstantiation(ExpressionTree callee) { if (callee.is(Tree.Kind.NAMESPACE_NAME)) { QualifiedName className = getFullyQualifiedName((NamespaceNameTree) callee); return SUSPICIOUS_CLASS_INSTANTIATIONS.stream().anyMatch(className::equals); } return false; }
Source:
private PageMode getMode() { final PageMode currentMode = PageMode.get(request); return currentMode.showLive ? currentMode : START APILocator.getHTMLPageAssetRenderedAPI().getDefaultEditPageMode(user, request, uri, response); END } why are you removing the response, some of the thing we have figured out is that the request must be always coming together with the response, even if it is not used at this time, could be in the future

Target:
private PageMode getMode() { final PageMode currentMode = PageMode.get(request); return currentMode.showLive ? currentMode : APILocator.getHTMLPageAssetRenderedAPI().getDefaultEditPageMode(user, request, uri); }
Source:
public File getDirectory() { if (tmpdir == null) { tmpdir = getTemporaryDirectory(); if (tmpdir == null) { tmpdir = createDirInsideApplication(); START } END } return tmpdir.toFile(); } I'd put this if outside the other. but :+1: anyway... no need for locks, since the temp dir won't change (or shouldn't, anyway)

Target:
public File getDirectory() { if (tmpdir == null) { tmpdir = getTemporaryDirectory(); } if (tmpdir == null) { tmpdir = createDirInsideApplication(); } return tmpdir.toFile(); }
Source:
public boolean matches(ILoggingEvent actual) { // Match only the first line to skip the validation of hex-dump format. actualMsg = actual.getMessage().split("(?s)[\\r\\n]+")[0]; if (actualMsg.matches(expected)) { // The presence of a newline implies a hex-dump was logged return actual.getMessage().contains(NEWLINE) == shouldContainNewline; START } else { END return false; } } nit: remove `else` as you return in the `if` block anyway.

Target:
public boolean matches(ILoggingEvent actual) { // Match only the first line to skip the validation of hex-dump format. actualMsg = actual.getMessage().split("(?s)[\\r\\n]+")[0]; if (actualMsg.matches(expected)) { // The presence of a newline implies a hex-dump was logged return actual.getMessage().contains(NEWLINE) == shouldContainNewline; } return false; }
Source:
START private static void addPropertyVariableToResult(Collection<Pair<Object, String>> result, String element) { END if (element.length() > 0) { List<String> list = Arrays.asList(element.split(",")); list.forEach(s1 -> { String value = s1.split(":")[0]; result.add(new Pair<>(value, value)); }); } } I think this method has no need to be `static`

Target:
private void addPropertyVariableToResult(Collection<Pair<Object, String>> result, String element) { if (element.length() > 0) { List<String> list = Arrays.asList(element.split(",")); list.forEach(s1 -> { String value = s1.split(":")[0]; result.add(new Pair<>(value, value)); }); } }
Source:
public List<String> getJobsForAnExtension(final String extensionName) throws FalconException { List<ExtensionJobsBean> extensionJobs = metaStore.getJobsForAnExtension(extensionName); List<String> extensionJobNames = new ArrayList<>(); if (null != extensionJobs && !extensionJobs.isEmpty()){ for (ExtensionJobsBean extensionJobsBean: extensionJobs) { extensionJobNames.add(extensionJobsBean.getJobName()); } return extensionJobNames; START } else { END return extensionJobNames; } } Unnecessary else. You can just return extensionJobNames outside the if statement.

Target:
public List<String> getJobsForAnExtension(final String extensionName) throws FalconException { List<ExtensionJobsBean> extensionJobs = metaStore.getJobsForAnExtension(extensionName); List<String> extensionJobNames = new ArrayList<>(); if (null != extensionJobs && !extensionJobs.isEmpty()) { for (ExtensionJobsBean extensionJobsBean : extensionJobs) { extensionJobNames.add(extensionJobsBean.getJobName()); } } return extensionJobNames; }
Source:
public void resetToDefaults() { maximumPageSize = DEFAULT_PAGESIZE; showSiteHeader = true; useFlashClipboard = true; copySelfOnEmail = false; displayPatchSetsInReverseOrder = false; START displayPersonNameInReviewCategory = true; END downloadUrl = null; downloadCommand = null; dateFormat = null; timeFormat = null; } I thought the default was false.

Target:
public void resetToDefaults() { maximumPageSize = DEFAULT_PAGESIZE; showSiteHeader = true; useFlashClipboard = true; copySelfOnEmail = false; displayPatchSetsInReverseOrder = false; displayPersonNameInReviewCategory = false; downloadUrl = null; downloadCommand = null; dateFormat = null; timeFormat = null; }
Source:
public static boolean isIpWithtInCidrRange(final String ipAddress, final String cidr) { if (!isValidIp(ipAddress)) { return false; } if (!isValidCIDR(cidr)) { return false; } // check if the gatewayip is the part of the ip range being added. // RFC 3021 - 31-Bit Prefixes on IPv4 Point-to-Point Links // GW Netmask Stat IP End IP // 192.168.24.0 - 255.255.255.254 - 192.168.24.0 - 192.168.24.1 // https://tools.ietf.org/html/rfc3021 // Added by Wilder Rodrigues final SubnetUtils subnetUtils = new SubnetUtils(cidr); subnetUtils.setInclusiveHostCount(true); final boolean isInRange = subnetUtils.getInfo().isInRange(ipAddress); START return !isInRange; END } why did you reverse this return value @kansal ? I missed it in the first itteration

Target:
public static boolean isIpWithtInCidrRange(final String ipAddress, final String cidr) { if (!isValidIp(ipAddress)) { return false; } if (!isValidCIDR(cidr)) { return false; } // check if the gatewayip is the part of the ip range being added. // RFC 3021 - 31-Bit Prefixes on IPv4 Point-to-Point Links // GW Netmask Stat IP End IP // 192.168.24.0 - 255.255.255.254 - 192.168.24.0 - 192.168.24.1 // https://tools.ietf.org/html/rfc3021 // Added by Wilder Rodrigues final SubnetUtils subnetUtils = new SubnetUtils(cidr); subnetUtils.setInclusiveHostCount(true); final boolean isInRange = subnetUtils.getInfo().isInRange(ipAddress); return isInRange; }
Source:
public void edit(final UnitVmModel object) { super.edit(object); if (object.getIsNew()) { object.getNumOfDesktops().setEntity(1); } START prestartedVmsEditor.setEnabled(true); END } isn't it true by default?

Target:
public void edit(final UnitVmModel object) { super.edit(object); if (object.getIsNew()) { object.getNumOfDesktops().setEntity(1); } }
Source:
public String[] getProtocolsMask(long noOpt) { START ctx.setOptions(noOpt); END return WolfSSL.getProtocolsMask(noOpt); } We should handle the case where "ctx" is null here. Consider either returning null or throwing a IllegalStateException similar to how other methods in WolfSSLContext.java do.

Target:
public String[] getProtocolsMask(long noOpt) { if(ctx != null) ctx.setOptions(noOpt); return WolfSSL.getProtocolsMask(noOpt); }
Source:
public synchronized boolean installSingleNodeLayoutIfAbsent() { if ((Boolean) getServerConfig().get("--single") && getCurrentLayout() == null) { setCurrentLayout(getNewSingleNodeLayout()); START log.error("HERE ====="); END return true; } return false; } remove

Target:
public synchronized boolean installSingleNodeLayoutIfAbsent() { if ((Boolean) getServerConfig().get("--single") && getCurrentLayout() == null) { setCurrentLayout(getNewSingleNodeLayout()); return true; } return false; }
Source:
public DrillFileSystem(Configuration fsConf, OperatorStats operatorStats) throws IOException { // Configuration objects are mutable, and the underlying FileSystem object may directly use a passed in Configuration. // In order to avoid scenarios where a Configuration can change after a DrillFileSystem is created, we make a copy // of the Configuration. START this.fsConf = new Configuration(fsConf); END this.underlyingFs = FileSystem.get(this.fsConf); this.codecFactory = new CompressionCodecFactory(this.fsConf); this.operatorStats = operatorStats; this.initialized = true; } We can convert `this.fsConf` to be a local variable and in `getConf()` do `return new Configuration(underlyingFs.getConf());`

Target:
public DrillFileSystem(Configuration fsConf, OperatorStats operatorStats) throws IOException { // Configuration objects are mutable, and the underlying FileSystem object may directly use a passed in Configuration. // In order to avoid scenarios where a Configuration can change after a DrillFileSystem is created, we make a copy // of the Configuration. fsConf = new Configuration(fsConf); this.underlyingFs = FileSystem.get(fsConf); this.codecFactory = new CompressionCodecFactory(fsConf); this.operatorStats = operatorStats; }
Source:
@Test public void testParse() throws NoSuchAuthorityCodeException { final URN_Parser parser = URN_Parser.buildParser("urn:ogc:def:CRS:EPSG:6.11.2:4326"); assertEquals("crs", parser.type.name); assertEquals("EPSG", parser.authority); assertEquals("6.11.2", parser.version.toString()); START assertEquals("4326", parser.code); END assertEquals("EPSG:4326", parser.getAuthorityCode()); } this is just white space changes right?

Target:
public void testParse() throws NoSuchAuthorityCodeException { final URN_Parser parser = URN_Parser.buildParser("urn:ogc:def:CRS:EPSG:6.11.2:4326"); assertEquals("crs", parser.type.name); assertEquals("EPSG", parser.authority); assertEquals("6.11.2", parser.version.toString()); assertEquals("4326", parser.code); assertEquals("EPSG:4326", parser.getAuthorityCode()); }
Source:
public void afterPropertiesSet() throws Exception { START this.sslContext = this.sslContextSupport.getSSLContext(); END Assert.notNull(this.sslContext, "SSLContext must not be null"); } Not related to this fix, but can't we get rid of this extra `InitializingBean` operation and just `getSSLContext()` directly in the ctor ?

Target:
public void afterPropertiesSet() throws Exception { }
Source:
public int hashCode() { return Objects.hash( snapshotId, clusterId, volumeId, snapshotName, status, description, START status END ); } status repeated twice. I guess it was there in the original code too.

Target:
public int hashCode() { return Objects.hash( snapshotId, clusterId, volumeId, snapshotName, description, status ); }
Source:
public Model getUPDATEModel(Representation representation) { return new ModelImpl() .property("condition", new StringProperty()) .property("patient", new StringProperty()) .property("clinicalStatus", new StringProperty()) .property("verificationStatus", new StringProperty()) .property("previousVersion", new StringProperty()) .property("onsetDate", new StringProperty()) .property("voided", new StringProperty()) START .required("condition").required("onsetDate"); END } What does the above line mean?

Target:
public Model getUPDATEModel(Representation representation) { return new ModelImpl() .property("condition", new StringProperty()) .property("clinicalStatus", new StringProperty()) .property("verificationStatus", new StringProperty()) .property("previousVersion", new StringProperty()) .property("onsetDate", new StringProperty()) .property("voided", new StringProperty()); }
Source:
public String getHostFingerprint() throws IOException { if (_client == null) { START throw new java.net.ConnectException("SSH is not connected"); END } return ((EngineSSHClient)_client).getHostFingerprint(); } please import this.

Target:
public String getHostFingerprint() throws IOException { if (_client == null) { throw new ConnectException("SSH is not connected"); } return ((EngineSSHClient)_client).getHostFingerprint(); }
Source:
public void invite(final String friend) throws IOException { try { new JdbcSession(this.sql.source()) // @checkstyle LineLength (1 line) .sql("INSERT INTO friend (bout, alias, subscription) VALUES (?, ?, ?)") .set(this.bout) .set(friend) START .set(1) END .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } @ekondrashev what `1` means here?

Target:
public void invite(final String friend) throws IOException { try { new JdbcSession(this.sql.source()) // @checkstyle LineLength (1 line) .sql("INSERT INTO friend (bout, alias, subscription) VALUES (?, ?, ?)") .set(this.bout) .set(friend) .set(true) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } }
Source:
public AddVdsVDSCommand(P parameters) { START super(parameters, false); END } false=>true (after changing to isNewHost)

Target:
public AddVdsVDSCommand(P parameters) { super(parameters, true); }
Source:
void run() { if (fused) { return; } Observer<? super Long> actual = this.actual; long e = end; for (long i = index; i != e && get() == 0; i++) { START actual.onNext((long)i); END } if (get() == 0) { lazySet(1); actual.onComplete(); } } unnecessary cast to long

Target:
void run() { if (fused) { return; } Observer<? super Long> actual = this.actual; long e = end; for (long i = index; i != e && get() == 0; i++) { actual.onNext(i); } if (get() == 0) { lazySet(1); actual.onComplete(); } }
Source:
private void fireEventsFor(OLogSequenceNumber lsn) { // may be executed by only one thread at every instant of time final ConcurrentNavigableMap<OLogSequenceNumber, Runnable> eventsToFire = events.headMap(lsn, true); for (Runnable runnable : eventsToFire.values()) runnable.run(); START eventsToFire.clear(); END } Unfortunately here we can have a situation when some events can be lost. I meant that ```eventsToFire``` map can have at the moment of call of method more elements than were processed in the loop because ```eventsToFire``` is backed by ```events``` map.

Target:
private void fireEventsFor(OLogSequenceNumber lsn) { // may be executed by only one thread at every instant of time final Iterator<Runnable> eventsToFire = events.headMap(lsn, true).values().iterator(); while (eventsToFire.hasNext()) { eventsToFire.next().run(); eventsToFire.remove(); } }
Source:
public void testPurgeDeletedVault() { api().purgeVault(LOCATION, vaultName); START Object[] args = { resourceGroupName, vaultName, false }; END checkState(deletedVaultStatus.create(resourceGroupName, true).apply(vaultName), "vault was not purged before timeout"); } Unused args?

Target:
public void testPurgeDeletedVault() { api().purgeVault(LOCATION, vaultName); checkState(deletedVaultStatus.create(resourceGroupName, true).apply(vaultName), "vault was not purged before timeout"); }
Source:
public long estimateMemorySize() { return SIZE_OF_OGC_POINT + (point != null ? point.estimateMemorySize() : 0) + START (esriSR != null ? esriSR.estimateMemorySize() : 0); END } In a good implementation, the spatial reference instance should be shared between all instances of geometry coming the same dataset, so usually the esriSR size would not contribute to OGC types, but we don't enforce that on geometry side right now.

Target:
public long estimateMemorySize() { return SIZE_OF_OGC_POINT + (point != null ? point.estimateMemorySize() : 0); }
Source:
public void auditResponseMessage(T request, K response, AssertionType assertion, NhinTargetSystemType target, String direction, String _interface, Boolean isRequesting, Properties webContextProperties, String serviceName) { LOG.trace("--- Before auditing of response message ---"); START if (getAuditLogger() != null && isAuditLoggingOn(serviceName)) { END getAuditLogger().auditResponseMessage(request, response, assertion, target, direction, _interface, isRequesting, webContextProperties, serviceName, getAuditTransforms()); } LOG.trace("--- After auditing of response message ---"); } Should these cases be reverse? (i.e., don't instantiate the logger unless audit logging is on)

Target:
public void auditResponseMessage(T request, K response, AssertionType assertion, NhinTargetSystemType target, String direction, String _interface, Boolean isRequesting, Properties webContextProperties, String serviceName) { LOG.trace("--- Before auditing of response message ---"); if (isAuditLoggingOn(serviceName) && getAuditLogger() != null) { getAuditLogger().auditResponseMessage(request, response, assertion, target, direction, _interface, isRequesting, webContextProperties, serviceName, getAuditTransforms()); } LOG.trace("--- After auditing of response message ---"); }
Source:
public GeoJsonLayer(GoogleMap map, JSONObject geoJsonFile) { if (geoJsonFile == null) { throw new IllegalArgumentException("GeoJSON file cannot be null"); } mBoundingBox = null; GeoJsonParser parser = new GeoJsonParser(geoJsonFile); // Assign GeoJSON bounding box for FeatureCollection mBoundingBox = parser.getBoundingBox(); HashMap<GeoJsonFeature, Object> geoJsonFeatures = new HashMap<>(); for (GeoJsonFeature feature : parser.getFeatures()) { geoJsonFeatures.put(feature, null); } START mRenderer = new GeoJsonRenderer(map, geoJsonFeatures); END storeRenderer(mRenderer); } I believe `mRenderer` should be converted to a local variable (instead of member variable) here? `GeoJsonLayer` extends `Layer`, and there is a reference to the `GeoJsonRenderer` superclass `Renderer` within `Layers.storeRenderer()`.

Target:
public GeoJsonLayer(GoogleMap map, JSONObject geoJsonFile) { if (geoJsonFile == null) { throw new IllegalArgumentException("GeoJSON file cannot be null"); } mBoundingBox = null; GeoJsonParser parser = new GeoJsonParser(geoJsonFile); // Assign GeoJSON bounding box for FeatureCollection mBoundingBox = parser.getBoundingBox(); HashMap<GeoJsonFeature, Object> geoJsonFeatures = new HashMap<>(); for (GeoJsonFeature feature : parser.getFeatures()) { geoJsonFeatures.put(feature, null); } GeoJsonRenderer mRenderer = new GeoJsonRenderer(map, geoJsonFeatures); storeRenderer(mRenderer); }
Source:
protected int computeNewLength(int[] dimValSelector, int numProcessed, int numToProcess) { int valid = 0; int length = 0; for (int i = numProcessed; i < dimValSelector.length; i++) { length++; if (SKIP_POSITION_VALUE != dimValSelector[i]) { valid++; } START if (valid == numToProcess) { END break; } } return length; } this condition can be incorporated into the for loop

Target:
protected int computeNewLength(int[] dimValSelector, int numProcessed, int numToProcess) { int valid = 0; int length = 0; for (int i = numProcessed; i < dimValSelector.length && valid < numToProcess; i++) { length++; if (SKIP_POSITION_VALUE != dimValSelector[i]) { valid++; } } return length; }
Source:
START protected IMemoryBlockRetrieval createMemoryBlockRetrieval(String model, ILaunchConfiguration config, DsfSession session) { END DsfMemoryBlockRetrieval memRetrieval = null; try { memRetrieval = new DsfMemoryBlockRetrieval(model, config, session); } catch (DebugException e) { DsfPlugin.getDefault().getLog().log(e.getStatus()); } return memRetrieval; } I think this should throw the DebugException and let the caller deal with it. Someone else may want to do something else than log the error.

Target:
protected IMemoryBlockRetrieval createMemoryBlockRetrieval(String model, ILaunchConfiguration config, DsfSession session) throws DebugException { return new DsfMemoryBlockRetrieval(model, config, session); }
Source:
START public PathAnnotationRoutesParser() { END } protected

Target:
protected PathAnnotationRoutesParser() { this(null); }
Source:
private int getLength(Object o, int index) { if (o instanceof InstructionList) { // we do not store the last point of an instruction Instruction instruction = ((InstructionList) o).get(index); int size; if(instruction instanceof ViaInstruction) size = 0; else START size = instruction.getPoints().size(); END // the last point of instruction (i.e. first point of next instruction) is not included return size; } if (o instanceof List) { return ((List<PathDetail>) o).get(index).getLength(); } throw new IllegalStateException("We can only handle PathDetails or InstructionList in PathSimplification"); } Here I would expect 'getPoints.size-1' for both cases

Target:
private int getLength(Object o, int index) { if (o instanceof InstructionList) { // we do not store the last point of an instruction Instruction instruction = ((InstructionList) o).get(index); return instruction.getLength(); } if (o instanceof List) { return ((List<PathDetail>) o).get(index).getLength(); } throw new IllegalStateException("We can only handle PathDetails or InstructionList in PathSimplification"); }
Source:
private DataPointAssignment marshallToDomain(DataPointAssignmentDto dto) { final DataPointAssignment dpa = new DataPointAssignment(); BeanUtils.copyProperties(dto, dpa); if (dto.getKeyId() != null) { dpa.setKey(KeyFactory.createKey("DataPointAssignment", dto.getKeyId())); } //Lists must be copied separately START dpa.setDataPointIds(dto.getDataPointIds()); END return dpa; } The `BeanUtils.copyProperties()` cant handle this?

Target:
private DataPointAssignment marshallToDomain(DataPointAssignmentDto dto) { final DataPointAssignment dpa = new DataPointAssignment(); BeanUtils.copyProperties(dto, dpa); if (dto.getKeyId() != null) { dpa.setKey(KeyFactory.createKey("DataPointAssignment", dto.getKeyId())); } return dpa; }
Source:
protected boolean equivalent(Constraint constraint) { if (constraint == this || constraint instanceof IsTreeTableConstraint) { return true; } START return false; END } only one return is possible here.

Target:
protected boolean equivalent(Constraint constraint) { return constraint == this || constraint instanceof IsTreeTableConstraint; }
Source:
private Collection<CHGraphImpl> getAllCHGraphs() { // todo: this method is only used to have a 'view' on the two collections. we could also create this only once // as long as the graph collections are only modified in the constructor (otherwise we would have to make sure // the lists are in sync). another option would be something like guava concat. List<CHGraphImpl> result = new ArrayList<>(); result.addAll(nodeBasedCHGraphs); START result.addAll(edgeBasedCHGraphs); END return result; } A minor optimization here is to create the new ArrayList with the nodeBasedCHGraphs already or at least init the size with node+edge

Target:
private Collection<CHGraphImpl> getAllCHGraphs() { // todo: this method is only used to have a 'view' on the two collections. we could also create this only once // as long as the graph collections are only modified in the constructor (otherwise we would have to make sure // the lists are in sync). another option would be something like guava concat. List<CHGraphImpl> result = new ArrayList<>(nodeBasedCHGraphs.size() + edgeBasedCHGraphs.size()); result.addAll(nodeBasedCHGraphs); result.addAll(edgeBasedCHGraphs); return result; }
Source:
@Override public boolean equals(Object other) { START return other != null && (other instanceof Module) && Objects.equals(name, ((Module)other).name); END } `other != null` is redundant with `other instanceof Module`, which already returns `false` when `other` is `null`.

Target:
@Override public boolean equals(Object other) { return (other instanceof Module) && Objects.equals(name, ((Module)other).name); }
Source:
START public static boolean textContains(String actual, String text, boolean ignoreCase) { END return ignoreCase ? StringUtils.containsIgnoreCase(actual, text) : StringUtils.contains(actual, text); } Yes, I agree that there is no "a lot of sense" and this topic is... debatable. From my point of view, "private static" is still make sense because 1) it emphasizes the fact that this method doesn't depend on other class members (doesn't use internal state) 2) JVM doesn't pass `this` as the first parameter to such the methods Here are my points. The last call, of course, in on @Hi-Fi and you :)

Target:
private boolean textContains(String actual, String text, boolean ignoreCase) { return ignoreCase ? StringUtils.containsIgnoreCase(actual, text) : StringUtils.contains(actual, text); }
Source:
public START List<String> getRepositoryDirectories() END { return new ArrayList<>(repositoryDirectories); } File

Target:
public List<File> getRepositoryDirectories() { return new ArrayList<>(repositoryDirectories); }
Source:
protected void configureDispatch() { START bindAnnotated(RpcDispatchHooks.class).to(builder.getDispatchHooks()).in(Singleton.class); END bind(RpcDispatchCallFactory.class).to(DefaultRpcDispatchCallFactory.class).in(Singleton.class); bind(DispatchAsync.class).to(RpcDispatchAsync.class).in(Singleton.class); } You do not need bindAnnotated, since there's only one implementation of RpcDispatchHooks. bindAnnotated was used to bind an interface for the RPC and REST dispatchers to different implementations

Target:
protected void configureDispatch() { bind(RpcDispatchHooks.class).to(builder.getDispatchHooks()).in(Singleton.class); bind(RpcDispatchCallFactory.class).to(DefaultRpcDispatchCallFactory.class).in(Singleton.class); bind(DispatchAsync.class).to(RpcDispatchAsync.class).in(Singleton.class); }
Source:
protected void onExportToCsv() { START GWT.log(this.toString() + "onExportToCsv"); END scenarioSimulationEditorWrapper.onExportToCsv(getExportCallBack(), new ScenarioSimulationHasBusyIndicatorDefaultErrorCallback(view), context.getStatus().getSimulation()); } Is this log necessary?

Target:
protected void onExportToCsv() { scenarioSimulationEditorWrapper.onExportToCsv(getExportCallBack(), new ScenarioSimulationHasBusyIndicatorDefaultErrorCallback(view), context.getStatus().getSimulation()); }
Source:
public QuotaProgressBar() { START super(); END tooltip = new WidgetTooltip(this); } super is implied

Target:
public QuotaProgressBar() { tooltip = new WidgetTooltip(this); }
Source:
START public TestApplicationContext() { END super(); } As I said: `TestUtils.createTestApplicationContext()` so, no changes here, please.

Target:
TestApplicationContext() { super(); }
Source:
public Cursor queryDocument(String documentId, String[] projection) throws FileNotFoundException { final long docId = Long.parseLong(documentId); updateCurrentStorageManagerIfNeeded(docId); final FileCursor result = new FileCursor(projection); START result.addFile(mCurrentStorageManager.getFileById(docId)); END return result; } Here it is been generated sometimes a NullPointer exception, because `mCurrentStorageManager` is found in the StorageManager Map with a different id of the current storage managers.

Target:
public Cursor queryDocument(String documentId, String[] projection) throws FileNotFoundException { final long docId = Long.parseLong(documentId); updateCurrentStorageManagerIfNeeded(docId); final FileCursor result = new FileCursor(projection); if (result != null) result.addFile(mCurrentStorageManager.getFileById(docId)); return result; }
Source:
public HttpRequest filter(HttpRequest request) throws HttpException { if (this.isSAS){ request = filterSAS(request, this.credential); } else { request = filterKey(request); START } END utils.logRequest(signatureLog, request, "<<"); return request; } [bit] prefer inline conditionals for this kind of stuff: ```java request = this.isSAS ? filterSAS(request, this.credential) : filterKey(request); ```

Target:
public HttpRequest filter(HttpRequest request) throws HttpException { request = this.isSAS ? filterSAS(request, this.credential) : filterKey(request); utils.logRequest(signatureLog, request, "<<"); return request; }
Source:
public void setTTL(K key, long ttl, TimeUnit timeunit) { START if (getNodeEngine().getClusterService().getClusterVersion().isLessThan(Versions.V3_11)) { END throw new UnsupportedOperationException("setTTL method is available when cluster version is 3.11 or higher"); } checkNotNull(key); setTTLInternal(key, ttl, timeunit); } If we add this version check inside `default-record-store`, client initiated operations can also be caught.

Target:
public void setTTL(K key, long ttl, TimeUnit timeunit) { checkNotNull(key); checkNotNull(timeunit); setTTLInternal(key, ttl, timeunit); }
Source:
START public MessageChannel bindDynamicPubSubProducer(String name) { END MessageChannel channel = this.directChannelProvider.lookupSharedChannel(name); if (channel == null) { channel = this.directChannelProvider.createAndRegisterChannel(name); bindPubSubProducer(name, channel); } return channel; } Why is `bindDynamicProducer` `synchronized`, but this one not? I need to know more about this `MessageBus` stuff and where it is used from, to determine which behaviour is correct for this methods, but I hope you can provide correct answer anyway

Target:
public synchronized MessageChannel bindDynamicPubSubProducer(String name) { MessageChannel channel = this.directChannelProvider.lookupSharedChannel(name); if (channel == null) { channel = this.directChannelProvider.createAndRegisterChannel(name); bindPubSubProducer(name, channel); } return channel; }