auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static <T> int countGroupByLayers(final Query<T> query, final int foundNum) { if (foundNum == MAX_MERGE_BUFFER_NUM + 1) { return foundNum; } int maxFoundFromChildren = -1; for (DataSourceWithSegmentSpec eachSpec : query.getDataSources()) { final DataSource dataSource = eachSpec.getDataSource(); if (dataSource instanceof QueryDataSource) { QueryDataSource queryDataSource = (QueryDataSource) dataSource; if (queryDataSource.getQuery() instanceof GroupByQuery) { final int tmp = countGroupByLayers(queryDataSource.getQuery(), foundNum + 1); maxFoundFromChildren = tmp > maxFoundFromChildren ? tmp : maxFoundFromChildren; } else { final int tmp = countGroupByLayers(queryDataSource.getQuery(), 0); maxFoundFromChildren = tmp > maxFoundFromChildren ? tmp : maxFoundFromChildren; } } } if (maxFoundFromChildren > -1) { return maxFoundFromChildren > foundNum ? maxFoundFromChildren : foundNum; } else { return foundNum; } }

Target:
private static <T> int countGroupByLayers(final Query<T> query, final int foundNum) { if (foundNum == MAX_MERGE_BUFFER_NUM + 1) { return foundNum; } int maxFoundFromChildren = -1; for (DataSourceWithSegmentSpec eachSpec : query.getDataSources()) { final DataSource dataSource = eachSpec.getDataSource(); if (dataSource instanceof QueryDataSource) { QueryDataSource queryDataSource = (QueryDataSource) dataSource; if (queryDataSource.getQuery() instanceof GroupByQuery) { final int foundFromChild = countGroupByLayers(queryDataSource.getQuery(), foundNum + 1); maxFoundFromChildren = Math.max(foundFromChild, maxFoundFromChildren); } else { final int foundFromChild = countGroupByLayers(queryDataSource.getQuery(), 0); maxFoundFromChildren = Math.max(foundFromChild, maxFoundFromChildren); } } } return Math.max(maxFoundFromChildren, foundNum); }
Source:
public void testResolve() throws IOException { String regexStr = "^/user/(?<username>\\w+)"; String dstPathStr = "/namenode1/testResolve/$username"; String settingsStr = null; RegexMountPoint regexMountPoint = new RegexMountPoint(inodeTree, regexStr, dstPathStr, settingsStr); regexMountPoint.initialize(); InodeTree.ResolveResult resolveResult = regexMountPoint.resolve("/user/hadoop/file1", true); Assert.assertEquals(resolveResult.kind, InodeTree.ResultKind.EXTERNAL_DIR); Assert.assertTrue( resolveResult.targetFileSystem instanceof TestRegexMountPointFileSystem); Assert.assertTrue(resolveResult.resolvedPath.equals("/user/hadoop")); Assert.assertTrue( resolveResult.targetFileSystem instanceof TestRegexMountPointFileSystem); Assert.assertTrue( ((TestRegexMountPointFileSystem) resolveResult.targetFileSystem) .getUri().toString().equals("/namenode1/testResolve/hadoop")); Assert.assertTrue(resolveResult.remainingPath.toString().equals("/file1")); }

Target:
public void testResolve() throws IOException { String regexStr = "^/user/(?<username>\\w+)"; String dstPathStr = "/namenode1/testResolve/$username"; String settingsStr = null; RegexMountPoint regexMountPoint = new RegexMountPoint(inodeTree, regexStr, dstPathStr, settingsStr); regexMountPoint.initialize(); InodeTree.ResolveResult resolveResult = regexMountPoint.resolve("/user/hadoop/file1", true); Assert.assertEquals(resolveResult.kind, InodeTree.ResultKind.EXTERNAL_DIR); Assert.assertTrue( resolveResult.targetFileSystem instanceof TestRegexMountPointFileSystem); Assert.assertEquals("/user/hadoop", resolveResult.resolvedPath); Assert.assertTrue( resolveResult.targetFileSystem instanceof TestRegexMountPointFileSystem); Assert.assertEquals("/namenode1/testResolve/hadoop", ((TestRegexMountPointFileSystem) resolveResult.targetFileSystem) .getUri().toString()); Assert.assertEquals("/file1", resolveResult.remainingPath.toString()); }
Source:
public void readItemWithEventualConsistency() throws Exception { CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); container = client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); String idAndPkValue = UUID.randomUUID().toString(); ObjectNode properties = getDocumentDefinition(idAndPkValue, idAndPkValue); CosmosItemResponse<ObjectNode> itemResponse = container.createItem(properties); CosmosItemResponse<ObjectNode> readResponse1 = container.readItem( idAndPkValue, new PartitionKey(idAndPkValue), new CosmosItemRequestOptions() .setSessionToken(StringUtils.repeat("SomeManualInvalidSessionToken", 2000)) .setConsistencyLevel(ConsistencyLevel.EVENTUAL), ObjectNode.class); System.out.println("REQUEST DIAGNOSTICS: " + readResponse1.getDiagnostics().toString()); validateIdOfItemResponse(idAndPkValue, readResponse1); }

Target:
public void readItemWithEventualConsistency() throws Exception { CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); container = client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); String idAndPkValue = UUID.randomUUID().toString(); ObjectNode properties = getDocumentDefinition(idAndPkValue, idAndPkValue); CosmosItemResponse<ObjectNode> itemResponse = container.createItem(properties); CosmosItemResponse<ObjectNode> readResponse1 = container.readItem( idAndPkValue, new PartitionKey(idAndPkValue), new CosmosItemRequestOptions() .setSessionToken(StringUtils.repeat("SomeManualInvalidSessionToken", 2000)) .setConsistencyLevel(ConsistencyLevel.EVENTUAL), ObjectNode.class); logger.info("REQUEST DIAGNOSTICS: {}", readResponse1.getDiagnostics().toString()); validateIdOfItemResponse(idAndPkValue, readResponse1); }
Source:
public PushSetupSms(final CosemObisCode logicalName, final List<CosemObjectDefinition> pushObjectList, final SendDestinationAndMethod sendDestinationAndMethod, final List<WindowElement> communicationWindow, final Integer randomisationStartInterval, final Integer numberOfRetries, final Integer repetitionDelay) { this.checkRandomisationStartInterval(randomisationStartInterval); this.checkNumberOfRetries(numberOfRetries); this.checkRepetitionDelay(repetitionDelay); this.logicalName = logicalName; if (pushObjectList == null) { this.pushObjectList = null; } else { this.pushObjectList = new ArrayList<>(pushObjectList); } this.sendDestinationAndMethod = sendDestinationAndMethod; if (communicationWindow == null) { this.communicationWindow = null; } else { this.communicationWindow = new ArrayList<>(communicationWindow); } this.randomisationStartInterval = randomisationStartInterval; this.numberOfRetries = numberOfRetries; this.repetitionDelay = repetitionDelay; }

Target:
private PushSetupSms(final CosemObisCode logicalName, final List<CosemObjectDefinition> pushObjectList, final SendDestinationAndMethod sendDestinationAndMethod, final List<WindowElement> communicationWindow, final Integer randomisationStartInterval, final Integer numberOfRetries, final Integer repetitionDelay) { this.checkRandomisationStartInterval(randomisationStartInterval); this.checkNumberOfRetries(numberOfRetries); this.checkRepetitionDelay(repetitionDelay); this.logicalName = logicalName; if (pushObjectList == null) { this.pushObjectList = null; } else { this.pushObjectList = new ArrayList<>(pushObjectList); } this.sendDestinationAndMethod = sendDestinationAndMethod; if (communicationWindow == null) { this.communicationWindow = null; } else { this.communicationWindow = new ArrayList<>(communicationWindow); } this.randomisationStartInterval = randomisationStartInterval; this.numberOfRetries = numberOfRetries; this.repetitionDelay = repetitionDelay; }
Source:
private ServiceReference<ESystemInformation> reference(BundleContext context, String section) throws InvalidSyntaxException { String filter = About.createSectionFilter(section); Optional<ServiceReference<ESystemInformation>> first = context .getServiceReferences(ESystemInformation.class, filter) .stream().findFirst(); assumeTrue("No reference found", first.isPresent()); return first.get(); }

Target:
private ServiceReference<ISystemInformation> reference(BundleContext context, String section) throws InvalidSyntaxException { String filter = AboutSections.createSectionFilter(section); Optional<ServiceReference<ISystemInformation>> first = context .getServiceReferences(ISystemInformation.class, filter) .stream().findFirst(); assumeTrue("No reference found", first.isPresent()); return first.get(); }
Source:
public static void setUp() throws Exception { server.start(50831); System.setProperty("wildfly.config.url", CredentialStoreSaslAuthenticationTest.class.getResource(CREDENTIAL_CONFIG_FILE).toExternalForm()); }

Target:
public static void setUp() throws Exception { System.setProperty("wildfly.config.url", CredentialStoreSaslAuthenticationTest.class.getResource(CREDENTIAL_CONFIG_FILE).toExternalForm()); Security.insertProviderAt(providers[1], 1); CredentialStoreBuilder.get().setKeyStoreFile(BASE_STORE_DIRECTORY + "/mycredstore.cs") .setKeyStoreType("JCEKS") .setKeyStorePassword("StorePassword") .addPassword(USERNAME, PASSWORD) .build(); Security.removeProvider(providers[1].getName()); }
Source:
public static Permission findOrCreatePermissionForRole(RealmObject container, RealmList<Permission> permissions, String roleName) { if (roleName == null) { throw new IllegalArgumentException("Non-null 'roleName' required."); } if (!container.isManaged()) { throw new IllegalStateException("'findOrCreate()' can only be called on managed objects."); } Realm realm = container.getRealm(); if (!realm.isInTransaction()) { throw new IllegalStateException("'findOrCreate()' can only be called inside a write transaction."); } Permission permission = permissions.where().equalTo("role.name", roleName).findFirst(); if (permission == null) { Role role = realm.where(Role.class).equalTo("name", roleName).findFirst(); if (role == null) { role = realm.createObject(Role.class, roleName); } permission = realm.copyToRealm(new Permission.Builder(role).noPrivileges().build()); permissions.add(permission); } return permission; }

Target:
public static Permission findOrCreatePermissionForRole(RealmObject container, RealmList<Permission> permissions, String roleName) { if (Util.isEmptyString(roleName)) { throw new IllegalArgumentException("Non-empty 'roleName' required."); } if (!container.isManaged()) { throw new IllegalStateException("'findOrCreate()' can only be called on managed objects."); } Realm realm = container.getRealm(); if (!realm.isInTransaction()) { throw new IllegalStateException("'findOrCreate()' can only be called inside a write transaction."); } Permission permission = permissions.where().equalTo("role.name", roleName).findFirst(); if (permission == null) { Role role = realm.where(Role.class).equalTo("name", roleName).findFirst(); if (role == null) { role = realm.createObject(Role.class, roleName); } permission = realm.copyToRealm(new Permission.Builder(role).noPrivileges().build()); permissions.add(permission); } return permission; }
Source:
public void queryAnd(IAttributeType attrType, Collection<String> values) { query.and(attrType, values); }

Target:
public void queryAnd(IAttributeType attrType, Collection<String> values) { getQuery().and(attrType, values); }
Source:
public Date walkDateLiteral(DateLiteral lit) { return Date.from(lit.value.toInstant()); }

Target:
public Date walkDateLiteral(DateLiteral lit) { return DateUtils.toDate(lit.value); }
Source:
public String getTrialUntil() { return trialUntil; }

Target:
public ZonedDateTime getTrialUntil() { return trialUntil; }
Source:
private boolean bootstrapRealtimeTable(String tableName, File schemaFile, File realtimeTableConfigFile) throws Exception { Quickstart.printStatus(Quickstart.Color.CYAN, String.format("***** Adding %s realtime table *****", tableName)); if (!new AddTableCommand().setSchemaFile(schemaFile.getAbsolutePath()) .setTableConfigFile(realtimeTableConfigFile.getAbsolutePath()).setControllerHost(_controllerHost) .setControllerPort(String.valueOf(_controllerPort)).setExecute(true).execute()) { throw new RuntimeException(String .format("Unable to create realtime table - %s from schema file [%s] and table conf file [%s].", tableName, schemaFile, realtimeTableConfigFile)); } return true; }

Target:
private boolean bootstrapRealtimeTable(String tableName, File schemaFile, File realtimeTableConfigFile) throws Exception { LOGGER.info("Adding realtime table {}", tableName); if (!createTable(schemaFile, realtimeTableConfigFile)) { throw new RuntimeException(String .format("Unable to create realtime table - %s from schema file [%s] and table conf file [%s].", tableName, schemaFile, realtimeTableConfigFile)); } return true; }
Source:
public String toString() { return getClass().getName(); }

Target:
public String toString() { return "Binomial(" + n + ", " + p + ")"; }
Source:
public void close() { runAll( () -> merger.ifPresent(MergingHashAggregationBuilder::close), () -> spiller.ifPresent(Spiller::close), () -> mergeHashSort.ifPresent(MergeHashSort::close) ); }

Target:
public void close() { try (Closer closer = Closer.create()) { if (hashAggregationBuilder != null) { closer.register(hashAggregationBuilder::close); } merger.ifPresent(closer::register); spiller.ifPresent(closer::register); mergeHashSort.ifPresent(closer::register); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
public void returnsNotFoundOnQueryingNonexistentClient() { RemoteLockService lockService = getLockService(NONEXISTENT_CLIENT); assertThatThrownBy(lockService::currentTimeMillis) .satisfies(PaxosTimeLockServerIntegrationTest::assertRemoteNotFoundException); }

Target:
public void returnsNotFoundOnQueryingNonexistentClient() { RemoteLockService nonExistentLockService = getLockService(NONEXISTENT_CLIENT); assertThatThrownBy(nonExistentLockService::currentTimeMillis) .satisfies(PaxosTimeLockServerIntegrationTest::assertRemoteNotFoundException); }
Source:
public ColumnValueSelector<?> makeColumnValueSelector( TimeAndDimsHolder currEntry, IncrementalIndex.DimensionDesc desc ) { final int dimIndex = desc.getIndex(); class IndexerFloatColumnSelector implements FloatColumnSelector { @Override public float getFloat() { final Object[] dims = currEntry.get().getDims(); if (dimIndex >= dims.length || dims[dimIndex] == null) { return 0.0f; } return (Float) dims[dimIndex]; } @Override public boolean isNull() { final Object[] dims = currEntry.get().getDims(); return dimIndex >= dims.length || dims[dimIndex] == null; } @SuppressWarnings("deprecation") @Nullable @Override public Float getObject() { final Object[] dims = currEntry.get().getDims(); if (dimIndex >= dims.length) { return null; } return (Float) dims[dimIndex]; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { } } return new IndexerFloatColumnSelector(); }

Target:
public ColumnValueSelector<?> makeColumnValueSelector( TimeAndDimsHolder currEntry, IncrementalIndex.DimensionDesc desc ) { final int dimIndex = desc.getIndex(); class IndexerFloatColumnSelector implements FloatColumnSelector { @Override public boolean isNull() { final Object[] dims = currEntry.get().getDims(); return dimIndex >= dims.length || dims[dimIndex] == null; } @Override public float getFloat() { final Object[] dims = currEntry.get().getDims(); if (dimIndex >= dims.length || dims[dimIndex] == null) { assert NullHandling.replaceWithDefault(); return 0.0f; } return (Float) dims[dimIndex]; } @SuppressWarnings("deprecation") @Nullable @Override public Float getObject() { final Object[] dims = currEntry.get().getDims(); if (dimIndex >= dims.length) { return null; } return (Float) dims[dimIndex]; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { } } return new IndexerFloatColumnSelector(); }
Source:
private void handleProtocolResponseMessage(final ProtocolResponseMessage message) throws FunctionalException, JMSException { if (message.getRetryHeader().shouldRetry()) { final ScheduledTask task = this.createScheduledRetryTask(message); this.scheduledTaskRepository.save(task); } else if (this.shouldRetryBasedOnMessage(message)) { LOGGER.info("Retrying: for time", message.getMessageType(), message.getRetryCount() + 1); final ProtocolRequestMessage protocolRequestMessage = this.createProtocolRequestMessage(message); this.deviceRequestMessageService.processMessage(protocolRequestMessage); } else { LOGGER.info("Sending domain response message."); this.domainResponseMessageSender.send(message); } }

Target:
private void handleProtocolResponseMessage(final ProtocolResponseMessage message) throws FunctionalException, JMSException { if (message.getRetryHeader().shouldRetry()) { LOGGER.info("Creating a scheduled retry task for message of type for device {}.", message.getMessageType(), message.getDeviceIdentification()); final ScheduledTask task = this.createScheduledRetryTask(message); this.scheduledTaskRepository.save(task); } else if (this.shouldRetryBasedOnMessage(message)) { LOGGER.info("Retrying: for device for time", message.getMessageType(), message.getDeviceIdentification(), message.getRetryCount() + 1); final ProtocolRequestMessage protocolRequestMessage = this.createProtocolRequestMessage(message); this.deviceRequestMessageService.processMessage(protocolRequestMessage); } else { LOGGER.info("Sending domain response message for message of type for device {}.", message.getMessageType(), message.getDeviceIdentification()); this.domainResponseMessageSender.send(message); } }
Source:
public synchronized void removeReferencePoint(String id) { IReferencePoint referencePoint = idToReferencePointMapping.get(id); if (referencePoint == null) { LOG.warn("could not remove referencePoint, no referencePoint is registerid with ID: " + id); return; } if (partiallySharedReferencePoints.contains(referencePoint)) partiallySharedReferencePoints.remove(referencePoint); else completelySharedReferencePoints.remove(referencePoint); idToReferencePointMapping.remove(id); referencePointToIDMapping.remove(referencePoint); partiallySharedResourceMapping.remove(referencePoint); LOG.debug("removed referencePoint " + referencePoint + " with ID " + id); }

Target:
public synchronized void removeReferencePoint(String id) { IReferencePoint referencePoint = idToReferencePointMapping.get(id); if (referencePoint == null) { LOG.warn("could not remove referencePoint, no referencePoint is registered with ID: " + id); return; } if (partiallySharedReferencePoints.contains(referencePoint)) partiallySharedReferencePoints.remove(referencePoint); else completelySharedReferencePoints.remove(referencePoint); idToReferencePointMapping.remove(id); referencePointToIDMapping.remove(referencePoint); partiallySharedResourceMapping.remove(referencePoint); LOG.debug("removed referencePoint " + referencePoint + " with ID " + id); }
Source:
public HTTPTransportListener(int bossGroupSize, int workerGroupSize, Set<ListenerConfiguration> listenerConfigurationSet) { super("ServerBootStrapper"); if (listenerConfigurationSet.size() == 0) { log.error("Cannot find registered listener configurations hence cannot start the transport listeners"); return; } listenerConfigurationMap = listenerConfigurationSet.stream() .collect(Collectors.toMap(ListenerConfiguration::getId, config -> config)); listenerConfigurationSet.forEach(config -> { String host = config.getHost(); int port = config.getPort(); String id = host + ":" + port; listenerConfigMapWithHostPort.put(id, config); if (host.equals(Constants.DEFAULT_ADDRESS) || host.equals(Constants.LOCALHOST) || host .equals(Constants.LOOP_BACK_ADDRESS)) { id = Constants.LOCALHOST + ":" + port; listenerConfigMapWithHostPort.put(id, config); id = Constants.LOOP_BACK_ADDRESS + ":" + port; listenerConfigMapWithHostPort.put(id, config); id = Constants.DEFAULT_ADDRESS + ":" + port; listenerConfigMapWithHostPort.put(id, config); } }); Iterator itr = listenerConfigurationSet.iterator(); if (itr.hasNext()) { defaultListenerConfig = (ListenerConfiguration) itr.next(); } this.bossGroupSize = bossGroupSize; this.workerGroupSize = workerGroupSize; }

Target:
public HTTPTransportListener(int bossGroupSize, int workerGroupSize, Set<ListenerConfiguration> listenerConfigurationSet) { super("ServerBootStrapper"); if (listenerConfigurationSet.isEmpty()) { log.error("Cannot find registered listener configurations hence cannot start the transport listeners"); return; } listenerConfigurationMap = listenerConfigurationSet.stream() .collect(Collectors.toMap(ListenerConfiguration::getId, config -> config)); listenerConfigurationSet.forEach(config -> { String host = config.getHost(); int port = config.getPort(); String id = host + ":" + port; listenerConfigMapWithHostPort.put(id, config); if (host.equals(Constants.DEFAULT_ADDRESS) || host.equals(Constants.LOCALHOST) || host .equals(Constants.LOOP_BACK_ADDRESS)) { id = Constants.LOCALHOST + ":" + port; listenerConfigMapWithHostPort.put(id, config); id = Constants.LOOP_BACK_ADDRESS + ":" + port; listenerConfigMapWithHostPort.put(id, config); id = Constants.DEFAULT_ADDRESS + ":" + port; listenerConfigMapWithHostPort.put(id, config); } }); Iterator itr = listenerConfigurationSet.iterator(); if (itr.hasNext()) { defaultListenerConfig = (ListenerConfiguration) itr.next(); } this.bossGroupSize = bossGroupSize; this.workerGroupSize = workerGroupSize; }
Source:
public void onCompleted(Run build, @Nonnull TaskListener listener) { logger.entering(getClass().getName(), "onCompleted"); File file = new File(build.getRootDir(), ScanLogAction.FILE_NAME); try ( FileOutputStream fos = new FileOutputStream(file, true); PrintStream bfaLog = new PrintStream(fos, true, "UTF8") ) { if (PluginImpl.isSizeInLimit(build)) { scanIfNotScanned(build, bfaLog); } else { bfaLog.println("Log exceeds limit: " + PluginImpl.getInstance().getMaxLogSize() + "MB"); } } catch (Exception e) { logger.log(Level.SEVERE, "Could not get the causes from the knowledge base", e); } }

Target:
public void onCompleted(Run build, @Nonnull TaskListener listener) { logger.entering(getClass().getName(), "onCompleted"); File file = new File(build.getRootDir(), ScanLogAction.FILE_NAME); try ( FileOutputStream fos = new FileOutputStream(file, true); PrintStream scanLog = new PrintStream(fos, true, "UTF8") ) { if (PluginImpl.isSizeInLimit(build)) { scanIfNotScanned(build, scanLog); } else { logToScanLog(scanLog, "Log exceeds limit: " + PluginImpl.getInstance().getMaxLogSize() + "MB"); } } catch (Exception e) { logger.log(Level.SEVERE, "Could not get the causes from the knowledge base", e); } }
Source:
private Boolean constrainedResize(TableView.ResizeFeatures<?> prop) { TableView<?> table = prop.getTable(); Double tableWidth = getContentWidth(table); List<? extends TableColumnBase<?, ?>> visibleLeafColumns = table.getVisibleLeafColumns(); Double requiredWidth = visibleLeafColumns.stream().mapToDouble(TableColumnBase::getWidth).sum(); Double delta = prop.getDelta(); TableColumn<?, ?> userChosenColumnToResize = prop.getColumn(); boolean columnsCanFitTable = requiredWidth + delta < tableWidth; if (columnsCanFitTable) { LOGGER.debug("User shrunk column in that way thus that window can contain all the columns"); if (requiredWidth >= tableWidth) { LOGGER.debug("Before, the content did not fit. Rearrange everything."); return rearrangeColumns(table); } LOGGER.debug("Everything already fit. We distribute the delta now."); determineNewWidth(userChosenColumnToResize, delta) .ifPresent(newWidth -> { double currentWidth = userChosenColumnToResize.getWidth(); Double deltaToApply = newWidth - currentWidth; for (TableColumnBase<?, ?> col : visibleLeafColumns) { Double share = expansionShare.get(col); Double newSize; if (col.equals(prop.getColumn())) { newSize = newWidth; } else { newSize = col.getWidth() - share * deltaToApply; } newSize = Math.min(newSize, col.getMaxWidth()); col.setPrefWidth(newSize); } }); return true; } LOGGER.debug("Window smaller than content"); determineNewWidth(userChosenColumnToResize, delta).ifPresent(newWidth -> userChosenColumnToResize.setPrefWidth(newWidth)); return true; }

Target:
private Boolean constrainedResize(TableView.ResizeFeatures<?> prop) { TableColumn<?, ?> userChosenColumnToResize = prop.getColumn(); TableView<?> table = prop.getTable(); Double tableWidth = table.getWidth(); Double currentTableContentWidth = getContentWidth(table); Double delta = prop.getDelta(); boolean columnsCanFitTable = currentTableContentWidth + delta < tableWidth; LOGGER.debug("currentTableContentWidth + delta < tableWidth = {}", currentTableContentWidth, delta, tableWidth, columnsCanFitTable); if (columnsCanFitTable) { LOGGER.debug("User changed column size in a way that window can contain all the columns"); Optional<Double> newWidthOptional; if (currentTableContentWidth >= tableWidth) { LOGGER.debug("Before, the content did not fit. Now it fits. Rearrange everything."); return rearrangeColumns(table); } LOGGER.debug("Everything already fit. We distribute the delta now."); newWidthOptional = determineNewWidth(userChosenColumnToResize, delta); newWidthOptional.ifPresent(newWidth -> { distributeDelta(table, userChosenColumnToResize, newWidth); }); return newWidthOptional.isPresent(); } LOGGER.debug("Window smaller than content"); Optional<Double> newWidth = determineNewWidth(userChosenColumnToResize, delta); newWidth.ifPresent(userChosenColumnToResize::setPrefWidth); return newWidth.isPresent(); }
Source:
protected abstract void doMatchQuery(String queryId, Query matchQuery, Map<String, String> metadata) throws IOException; private void addMatch(String queryId, String docId, T match) { MatchHolder<T> docMatches = matches.computeIfAbsent(docId, k -> new MatchHolder<>()); T found = docMatches.matches.get(queryId); if (found != null) { docMatches.matches.put(queryId, resolve(match, found)); } else { docMatches.matches.put(queryId, match); } }

Target:
protected abstract void doMatchQuery(String queryId, Query matchQuery, Map<String, String> metadata) throws IOException; private void addMatch(String queryId, String docId, T match) { MatchHolder<T> docMatches = matches.computeIfAbsent(docId, k -> new MatchHolder<>()); docMatches.matches.compute(queryId, (key, oldValue) -> { if (oldValue != null) { return resolve(match, oldValue); } return match; }); }
Source:
public LogUnitPerformanceTest() { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream input = classLoader.getResourceAsStream("PerformanceTest.properties"); try { PROPERTIES.load(input); } catch (IOException e) { e.printStackTrace(); } random = new Random(seed); metricRegistry = CorfuRuntime.getDefaultMetrics(); readTimer = metricRegistry.timer(METRIC_PREFIX + "logunit-single-read"); writeTimer = metricRegistry.timer(METRIC_PREFIX + "logunit-single-write"); }

Target:
public LogUnitPerformanceTest() { readTimer = metricRegistry.timer(METRIC_PREFIX + "logunit-read"); writeTimer = metricRegistry.timer(METRIC_PREFIX + "logunit-write"); }
Source:
public Stream<RelationshipResult> relationshipManualIndexSearch( @Name( "indexName" ) String manualIndexName, @Name( "query" ) Object query ) throws ProcedureException { try ( Statement statement = tx.acquireStatement() ) { ReadOperations readOperations = statement.readOperations(); LegacyIndexHits hits = readOperations.relationshipLegacyIndexQuery( manualIndexName, query, -1, -1 ); return toStream( hits, ( id ) -> new RelationshipResult( graphDatabaseAPI.getRelationshipById( id ) ) ); } catch ( LegacyIndexNotFoundKernelException e ) { throw new ProcedureException( Status.LegacyIndex.LegacyIndexNotFound, "Relationship index %s not found", manualIndexName ); } }

Target:
public Stream<WeightedRelationshipResult> relationshipManualIndexSearch( @Name( "indexName" ) String manualIndexName, @Name( "query" ) Object query ) throws ProcedureException { try ( Statement statement = tx.acquireStatement() ) { ReadOperations readOperations = statement.readOperations(); LegacyIndexHits hits = readOperations.relationshipLegacyIndexQuery( manualIndexName, query, -1, -1 ); return toWeightedRelationshipResultStream( hits ); } catch ( LegacyIndexNotFoundKernelException e ) { throw new ProcedureException( Status.LegacyIndex.LegacyIndexNotFound, "Relationship index %s not found", manualIndexName ); } }
Source:
private String[] getFormattedBoundaryValues(Object color) { Object[] values = colorScale.invertExtent(color); String minStr = String.valueOf(values[1]); String maxStr = String.valueOf(values[1]); double max = Double.parseDouble(maxStr); double min = Double.parseDouble(minStr); return new String[] { conf.getFormatter().apply(min), conf.getFormatter().apply(max) }; }

Target:
private String[] getFormattedBoundaryValues(Object color) { Object[] values = colorScale.invertExtent(color); String minStr = String.valueOf(values[0]); String maxStr = String.valueOf(values[1]); double max = Double.parseDouble(maxStr); double min = Double.parseDouble(minStr); return new String[] { conf.getFormatter().apply(min), conf.getFormatter().apply(max) }; }
Source:
private boolean areBricksInTheList(GlusterVolumeEntity volumeEntity, final List<GlusterBrickEntity> bricks, final List<GlusterBrickEntity> searchBricks) { boolean found = false; for (GlusterBrickEntity paramBrick : bricks) { GlusterBrickEntity paramBrickFromVolume = volumeEntity.getBrickWithId(paramBrick.getId()); if (paramBrickFromVolume == null) { paramBrickFromVolume = volumeEntity.getBrickWithQualifiedName(paramBrick.getQualifiedName()); } found = false; for (GlusterBrickEntity brick : searchBricks) { if (paramBrickFromVolume != null && paramBrickFromVolume.getId() != null && paramBrickFromVolume.getId().equals(brick.getId())) { found = true; break; } } } return found; }

Target:
private boolean areBricksInTheList(GlusterVolumeEntity volumeEntity, final List<GlusterBrickEntity> bricks, final List<GlusterBrickEntity> searchBricks) { boolean found = false; for (GlusterBrickEntity paramBrick : bricks) { GlusterBrickEntity paramBrickFromVolume = volumeEntity.getBrickWithId(paramBrick.getId()); if (paramBrickFromVolume == null) { paramBrickFromVolume = volumeEntity.getBrickWithQualifiedName(paramBrick.getQualifiedName()); } found = false; for (GlusterBrickEntity brick : searchBricks) { if (paramBrickFromVolume == null || paramBrickFromVolume.getId() == null) { return false; } if (paramBrickFromVolume.getId().equals(brick.getId())) { found = true; break; } } } return found; }
Source:
private void initAccessor(RegionShortcut regionShortcut) { @SuppressWarnings("rawtypes") PartitionAttributes attributes = new PartitionAttributesFactory<String, String>() .setTotalNumBuckets(BUCKETS) .setLocalMaxMemory(0) .create(); cacheRule.getCache().createRegionFactory(regionShortcut) .setPartitionAttributes(attributes) .create(REGION_NAME); }

Target:
private void initAccessor(RegionShortcut regionShortcut) { PartitionAttributes<String, String> attrs = new PartitionAttributesFactory<String, String>() .setTotalNumBuckets(BUCKETS) .setLocalMaxMemory(0) .create(); cacheRule.getCache().createRegionFactory(regionShortcut) .setPartitionAttributes(attrs) .create(REGION_NAME); }
Source:
public static BooleanExpression needsSharedDatabase(StateManager stateManager){ var binding = Bindings.createBooleanBinding(() -> stateManager.activeDatabaseProperty().getValue().filter(context -> context.getLocation() == DatabaseLocation.SHARED).isPresent(), stateManager.activeDatabaseProperty()); return BooleanExpression.booleanExpression(binding); }

Target:
public static BooleanExpression needsSharedDatabase(StateManager stateManager) { EasyBinding<Boolean> binding = EasyBind.map(stateManager.activeDatabaseProperty(), context -> context.filter(c -> c.getLocation() == DatabaseLocation.SHARED).isPresent()); return BooleanExpression.booleanExpression(binding); }
Source:
private void initializeChangeModeButtons() { ImageButton gridMode = (ImageButton) rootView.findViewById(R.id.av_grid_mode); ImageButton listMode = (ImageButton) rootView.findViewById(R.id.av_list_mode); gridMode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { settingsDataSource.saveMediaListMode(MediaListMode.GRID); mPresenter.onClickChangeMode(MediaListMode.GRID); } }); listMode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { settingsDataSource.saveMediaListMode(MediaListMode.LIST); mPresenter.onClickChangeMode(MediaListMode.LIST); } }); }

Target:
private void initializeChangeModeButtons() { ImageButton gridMode = (ImageButton) rootView.findViewById(R.id.av_grid_mode); ImageButton listMode = (ImageButton) rootView.findViewById(R.id.av_list_mode); gridMode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPresenter.onClickChangeMode(MediaListMode.GRID); } }); listMode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mPresenter.onClickChangeMode(MediaListMode.LIST); } }); }
Source:
public void testDayPeriodFormat() throws Exception { for (Locale locale : new Locale[] { Locale.US, Locale.FRANCE }) { assertDayPeriodFormat("HHb", "08", "08", locale); assertDayPeriodFormat("HHbb", "08", "08", locale); assertDayPeriodFormat("HHbbb", "08", "08", locale); assertDayPeriodFormat("HHbbbb", "08", "08", locale); assertDayPeriodFormat("HHbbbbb", "08", "08", locale); assertDayPeriodFormat("HHB", "08", "08", locale); assertDayPeriodFormat("HHBB", "08", "08", locale); assertDayPeriodFormat("HHBBB", "08", "08", locale); assertDayPeriodFormat("HHBBBB", "08", "08", locale); assertDayPeriodFormat("HHBBBBB", "08", "08", locale); } }

Target:
public void testDayPeriodFormat() throws Exception { SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); isoFormat.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = isoFormat.parse("2017-01-01T08:00:00"); for (Locale locale : new Locale[] { Locale.US, Locale.FRANCE }) { assertDayPeriodFormat("HHb", date, "08", locale); assertDayPeriodFormat("HHbb", date, "08", locale); assertDayPeriodFormat("HHbbb", date, "08", locale); assertDayPeriodFormat("HHbbbb", date, "08", locale); assertDayPeriodFormat("HHbbbbb", date, "08", locale); assertDayPeriodFormat("HHB", date, "08", locale); assertDayPeriodFormat("HHBB", date, "08", locale); assertDayPeriodFormat("HHBBB", date, "08", locale); assertDayPeriodFormat("HHBBBB", date, "08", locale); assertDayPeriodFormat("HHBBBBB", date, "08", locale); } }
Source:
public void onStop() { boolean volumeBtnCheckVal = checkVolumeBtn.isChecked(); SharedPreferences sPrefs = getActivity().getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = sPrefs.edit(); editor.putBoolean(getResources().getString(R.string.volumeBtnPrefs),volumeBtnCheckVal); editor.commit(); super.onStop(); }

Target:
public void onStop() { boolean volumeBtnCheckVal = checkVolumeBtn.isChecked(); SharedPreferences sPrefs = getActivity().getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = sPrefs.edit(); editor.putBoolean(getResources().getString(R.string.volume_btn_prefs),volumeBtnCheckVal); editor.commit(); super.onStop(); }
Source:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (!describe && context.getRunningMode() != RunningMode.ADMIN_ONLY) { throw UndertowLogger.ROOT_LOGGER.migrateOperationAllowedOnlyInAdminOnly(); } final ModelNode legacyModelAddOps = new ModelNode(); final Map<PathAddress, ModelNode> migrationOperations = new TreeMap<>(new Comparator<PathAddress>() { @Override public int compare(PathAddress o1, PathAddress o2) { final int compare = Integer.compare(o1.size(), o2.size()); if (compare != 0) { return compare; } return o1.toString().compareTo(o2.toString()); } }); describeLegacyWebResources(context, legacyModelAddOps); addExtension(context, migrationOperations, describe, UNDERTOW_EXTENSION); addExtension(context, migrationOperations, describe, IO_EXTENSION); context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { addDefaultResources(migrationOperations, legacyModelAddOps); createIoSubsystem(context, migrationOperations); createWelcomeContentHandler(migrationOperations); transformResources(context, legacyModelAddOps, migrationOperations); fixAddressesForDomainMode(pathAddress(operation.get(ADDRESS)), migrationOperations); removeWebSubsystem(migrationOperations); if (describe) { context.getResult().set(migrationOperations.values()); } else { migrateSubsystems(context, migrationOperations); } } }, MODEL); }

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (!describe && context.getRunningMode() != RunningMode.ADMIN_ONLY) { throw UndertowLogger.ROOT_LOGGER.migrateOperationAllowedOnlyInAdminOnly(); } final ModelNode legacyModelAddOps = new ModelNode(); final Map<PathAddress, ModelNode> migrationOperations = new TreeMap<>(new Comparator<PathAddress>() { @Override public int compare(PathAddress o1, PathAddress o2) { final int compare = Integer.compare(o1.size(), o2.size()); if (compare != 0) { return compare; } return o1.toString().compareTo(o2.toString()); } }); describeLegacyWebResources(context, legacyModelAddOps); addExtension(context, migrationOperations, describe, UNDERTOW_EXTENSION); addExtension(context, migrationOperations, describe, IO_EXTENSION); context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { addDefaultResources(migrationOperations, legacyModelAddOps); createIoSubsystem(context, migrationOperations); createWelcomeContentHandler(migrationOperations); transformResources(context, legacyModelAddOps, migrationOperations); removeWebSubsystem(migrationOperations); fixAddressesForDomainMode(pathAddress(operation.get(ADDRESS)), migrationOperations); if (describe) { context.getResult().set(migrationOperations.values()); } else { migrateSubsystems(context, migrationOperations); } } }, MODEL); }
Source:
public String getRequestorEmail(UserNotification notification) { if(notification == null) return "Unavailable"; if(notification.getRequestor() == null) return "Unavailable"; return notification.getRequestor().getEmail() != null ? notification.getRequestor().getEmail() : "Unavailable"; }

Target:
public String getRequestorEmail(UserNotification notification) { if(notification == null) return BundleUtil.getStringFromBundle("notification.email.info.unavailable");; if(notification.getRequestor() == null) return BundleUtil.getStringFromBundle("notification.email.info.unavailable");; return notification.getRequestor().getEmail() != null ? notification.getRequestor().getEmail() : BundleUtil.getStringFromBundle("notification.email.info.unavailable"); }
Source:
public void toExecute(JobExecutionContext context) throws JobExecutionException { JobDataMap map = context.getMergedJobDataMap(); String ownerKey = (String) map.get(JobStatus.TARGET_ID); ConflictOverrides overrides = new ConflictOverrides((String[]) map.get(CONFLICT_OVERRIDES)); String storedFileId = (String) map.get(STORED_FILE_ID); String uploadedFileName = (String) map.get(UPLOADED_FILE_NAME); Throwable caught = null; Owner targetOwner = null; try { targetOwner = ownerCurator.lookupByKey(ownerKey); if (targetOwner == null) { context.setResult("Nothing to do. Owner no longer exists."); return; } ImportRecord importRecord = manifestManager.importStoredManifest(targetOwner, storedFileId, overrides, uploadedFileName); context.setResult(importRecord); } catch (SyncDataFormatException e) { caught = new BadRequestException(e.getMessage(), e); } catch (ImporterException e) { caught = new IseException(e.getMessage(), e); } catch (Exception e) { caught = e; } if (caught != null) { log.error("ImportJob encountered a problem.", caught); manifestManager.recordImportFailure(targetOwner, caught, uploadedFileName); context.setResult(caught.getMessage()); manifestManager.deleteStoredManifest(storedFileId); throw new JobExecutionException(caught.getMessage(), caught, false); } }

Target:
public void toExecute(JobExecutionContext context) throws JobExecutionException { JobDataMap map = context.getMergedJobDataMap(); String ownerKey = (String) map.get(JobStatus.TARGET_ID); ConflictOverrides overrides = new ConflictOverrides((String[]) map.get(CONFLICT_OVERRIDES)); String storedFileId = (String) map.get(STORED_FILE_ID); String uploadedFileName = (String) map.get(UPLOADED_FILE_NAME); Throwable caught = null; Owner targetOwner = null; try { targetOwner = ownerCurator.lookupByKey(ownerKey); if (targetOwner == null) { throw new NotFoundException(String.format("Owner %s was not found.", ownerKey)); } ImportRecord importRecord = manifestManager.importStoredManifest(targetOwner, storedFileId, overrides, uploadedFileName); context.setResult(importRecord); } catch (SyncDataFormatException e) { caught = new BadRequestException(e.getMessage(), e); } catch (ImporterException e) { caught = new IseException(e.getMessage(), e); } catch (Exception e) { caught = e; } if (caught != null) { log.error("ImportJob encountered a problem.", caught); manifestManager.recordImportFailure(targetOwner, caught, uploadedFileName); context.setResult(caught.getMessage()); manifestManager.deleteStoredManifest(storedFileId); throw new JobExecutionException(caught.getMessage(), caught, false); } }
Source:
public RestListWrapper<Rule> getRules() { return new RestListWrapper<>( RulesDao.getRules().stream().collect(Collectors.toList()), Rule.class, this, "id", null); }

Target:
public RestListWrapper<Rule> getRules() { return new RestListWrapper<>(RulesDao.getRules(), Rule.class, this, "id", null); }
Source:
private void sendStatusChangedEvents() { for (String modifiedTagDisplayName : updatedStatusTags) { Case.getCurrentCase().notifyTagStatusChanged(modifiedTagDisplayName); } updatedStatusTags.clear(); }

Target:
private void sendStatusChangedEvents() { for (String modifiedTagDisplayName : updatedStatusTags) { if (Case.isCaseOpen()) { Case.getCurrentCase().notifyTagDefinitionChanged(modifiedTagDisplayName); } } updatedStatusTags.clear(); }
Source:
public int execute() { try { if (work.tableDataCopyIteratorsInitialized()) { initiateDataCopyTasks(); } else { Path dumpRoot = getEncodedDumpRootPath(); Path previousValidHiveDumpPath = getPreviousValidDumpMetadataPath(dumpRoot); boolean isBootstrap = (previousValidHiveDumpPath == null); if (shouldDump(previousValidHiveDumpPath)) { Path currentDumpPath = getCurrentDumpPath(dumpRoot, isBootstrap); Path hiveDumpRoot = new Path(currentDumpPath, ReplUtils.REPL_HIVE_BASE_DIR); work.setCurrentDumpPath(currentDumpPath); if (shouldDumpAuthorizationMetadata()) { initiateAuthorizationDumpTask(); } if (shouldDumpAtlasMetadata()) { LOG.info("Added task to dump atlas metadata."); addAtlasDumpTask(isBootstrap, previousValidHiveDumpPath); } DumpMetaData dmd = new DumpMetaData(hiveDumpRoot, conf); ReplChangeManager.getInstance(conf); Path cmRoot = new Path(conf.getVar(HiveConf.ConfVars.REPLCMDIR)); Long lastReplId; if (isBootstrap) { lastReplId = bootStrapDump(hiveDumpRoot, dmd, cmRoot, getHive()); } else { work.setEventFrom(getEventFromPreviousDumpMetadata(previousValidHiveDumpPath)); lastReplId = incrementalDump(hiveDumpRoot, dmd, cmRoot, getHive()); } work.setResultValues(Arrays.asList(currentDumpPath.toUri().toString(), String.valueOf(lastReplId))); initiateDataCopyTasks(); } else { LOG.info("Previous Dump is not yet loaded"); } } } catch (Exception e) { LOG.error("failed", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } return 0; }

Target:
public int execute() { try { if (work.tableDataCopyIteratorsInitialized()) { initiateDataCopyTasks(); } else { Path dumpRoot = getEncodedDumpRootPath(); Path previousValidHiveDumpPath = getPreviousValidDumpMetadataPath(dumpRoot); boolean isBootstrap = (previousValidHiveDumpPath == null); if (shouldDump(previousValidHiveDumpPath)) { Path currentDumpPath = getCurrentDumpPath(dumpRoot, isBootstrap); Path hiveDumpRoot = new Path(currentDumpPath, ReplUtils.REPL_HIVE_BASE_DIR); work.setCurrentDumpPath(currentDumpPath); if (shouldDumpAtlasMetadata()) { addAtlasDumpTask(isBootstrap, previousValidHiveDumpPath); LOG.info("Added task to dump atlas metadata."); } if (shouldDumpAuthorizationMetadata()) { initiateAuthorizationDumpTask(); } DumpMetaData dmd = new DumpMetaData(hiveDumpRoot, conf); ReplChangeManager.getInstance(conf); Path cmRoot = new Path(conf.getVar(HiveConf.ConfVars.REPLCMDIR)); Long lastReplId; if (isBootstrap) { lastReplId = bootStrapDump(hiveDumpRoot, dmd, cmRoot, getHive()); } else { work.setEventFrom(getEventFromPreviousDumpMetadata(previousValidHiveDumpPath)); lastReplId = incrementalDump(hiveDumpRoot, dmd, cmRoot, getHive()); } work.setResultValues(Arrays.asList(currentDumpPath.toUri().toString(), String.valueOf(lastReplId))); initiateDataCopyTasks(); } else { LOG.info("Previous Dump is not yet loaded"); } } } catch (Exception e) { LOG.error("failed", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } return 0; }
Source:
private BBContainer wrapRetCont(PBDSegment segment, final BBContainer retcont) { return new BBContainer(retcont.b()) { @Override public void discard() { synchronized(PersistentBinaryDeque.this) { checkDoubleFree(); retcont.discard(); assert(m_closed || m_segments.containsKey(segment.segmentId())); if (m_closed) { return; } try { PBDSegmentReader segmentReader = segment.getReader(m_cursorId); if (segment == peekLastSegment() || !segmentReader.allReadAndDiscarded()) { return; } if (canDeleteSegment(segment)) { Iterator<Map.Entry<Long, PBDSegment>> iter = m_segments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<Long, PBDSegment> entry = iter.next(); if (entry.getKey() > segment.segmentId()) { break; } PBDSegment segmentToDelete = entry.getValue(); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + segmentToDelete.file() + " has been closed and deleted after discarding last buffer"); } closeAndDeleteSegment(segmentToDelete); iter.remove(); } } } catch (IOException e) { LOG.error("Exception closing and deleting PBD segment", e); } } } }; }

Target:
private BBContainer wrapRetCont(PBDSegment segment, final BBContainer retcont) { return new BBContainer(retcont.b()) { @Override public void discard() { synchronized(PersistentBinaryDeque.this) { checkDoubleFree(); retcont.discard(); assert(m_closed || m_segments.containsKey(segment.segmentId())); if (m_closed) { return; } try { PBDSegmentReader segmentReader = segment.getReader(m_cursorId); if (segment == peekLastSegment() || !segmentReader.allReadAndDiscarded()) { return; } if (canDeleteSegment(segment)) { m_segments.remove(segment.segmentId()); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + segment.file() + " has been closed and deleted after discarding last buffer"); } closeAndDeleteSegment(segment); } } catch (IOException e) { LOG.error("Exception closing and deleting PBD segment", e); } } } }; }
Source:
public SpinnerNumberModel (int min, int max, int step, int value) { if (max < min) throw new IllegalArgumentException("The maximum cannot be smaller than the minimum"); if (value < min || value > max) throw new IllegalArgumentException("The current value must be between the minimum and the maximum (inclusive)"); this.min = min; this.max = max; if (step < 0) step *= -1; this.step = step; this.value = value; }

Target:
public SpinnerNumberModel (int min, int max, int step, int value) { if (max < min) throw new IllegalArgumentException("The maximum cannot be smaller than the minimum"); if (value < min || value > max) throw new IllegalArgumentException("The current value must be between the minimum and the maximum (inclusive)"); this.min = min; this.max = max; if (step < 0) step = -step; this.step = step; this.value = value; }