auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void updateColumns() { ProjectId id = createId(42); TestProcessManagerRepository repository = repository(); TestProcessManager pm = new TestProcessManager(id); repository.store(pm); TargetFilters targetFilters = targetFilters(Project.Column.idString(), id.toString()); Iterator<TestProcessManager> found = repository.find(targetFilters, ResponseFormat.getDefaultInstance()); assertThat(found.hasNext()).isFalse(); repository.applyMigration(id, new UpdatePmColumns<>()); Iterator<TestProcessManager> afterMigration = repository.find(targetFilters, ResponseFormat.getDefaultInstance()); assertThat(afterMigration.hasNext()).isTrue(); TestProcessManager entityWithColumns = afterMigration.next(); <START> assertThat(entityWithColumns.state() <END> .getIdString()).isEqualTo(id.toString()); }</code><technical_language>please expected state well</technical_language>

Target:
void updateColumns() { ProjectId id = createId(42); TestProcessManagerRepository repository = repository(); TestProcessManager pm = new TestProcessManager(id); repository.store(pm); TargetFilters targetFilters = targetFilters(Project.Column.idString(), id.toString()); Iterator<TestProcessManager> found = repository.find(targetFilters, ResponseFormat.getDefaultInstance()); assertThat(found.hasNext()).isFalse(); repository.applyMigration(id, new UpdatePmColumns<>()); Iterator<TestProcessManager> afterMigration = repository.find(targetFilters, ResponseFormat.getDefaultInstance()); assertThat(afterMigration.hasNext()).isTrue(); TestProcessManager entityWithColumns = afterMigration.next(); Project expectedState = pm .state() .toBuilder() .setIdString(pm.getIdString()) .build(); assertThat(entityWithColumns.state()).isEqualTo(expectedState); }
Source:
<code>public void testExecute_invalidRecommendedLength_shouldThrowException() { InstructorAttributes instructor1ofCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); FeedbackSessionAttributes session = typicalBundle.feedbackSessions.get("session1InCourse1"); FeedbackQuestionAttributes typicalQuestion = logic.getFeedbackQuestion(session.getFeedbackSessionName(), session.getCourseId(), 1); loginAsInstructor(instructor1ofCourse1.getGoogleId()); String[] param = new String[] { Const.ParamsNames.FEEDBACK_QUESTION_ID, typicalQuestion.getFeedbackQuestionId(), }; FeedbackQuestionSaveRequest saveRequest = getTypicalTextQuestionSaveRequest(); FeedbackTextQuestionDetails textQuestionDetails = new FeedbackTextQuestionDetails(); textQuestionDetails.setRecommendedLength(-1); saveRequest.setQuestionDetails(textQuestionDetails); SaveFeedbackQuestionAction a = getAction(saveRequest, param); assertThrows(InvalidHttpRequestBodyException.class, () -> { getJsonResult(a); }); assertEquals(typicalQuestion.getQuestionDescription(), <START> logic.getFeedbackQuestion(typicalQuestion.getId()).getQuestionDescription()); <END> }</code><technical_language>This ascertains description is updated, concerned question recommended answer length</technical_language>

Target:
public void testExecute_invalidRecommendedLength_shouldThrowException() { InstructorAttributes instructor1ofCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); FeedbackSessionAttributes session = typicalBundle.feedbackSessions.get("session1InCourse1"); FeedbackQuestionAttributes typicalQuestion = logic.getFeedbackQuestion(session.getFeedbackSessionName(), session.getCourseId(), 1); loginAsInstructor(instructor1ofCourse1.getGoogleId()); String[] param = new String[] { Const.ParamsNames.FEEDBACK_QUESTION_ID, typicalQuestion.getFeedbackQuestionId(), }; FeedbackQuestionSaveRequest saveRequest = getTypicalTextQuestionSaveRequest(); FeedbackTextQuestionDetails textQuestionDetails = new FeedbackTextQuestionDetails(); textQuestionDetails.setRecommendedLength(-1); saveRequest.setQuestionDetails(textQuestionDetails); SaveFeedbackQuestionAction a = getAction(saveRequest, param); assertThrows(InvalidHttpRequestBodyException.class, () -> getJsonResult(a)); assertEquals(typicalQuestion.getQuestionDescription(), logic.getFeedbackQuestion(typicalQuestion.getId()).getQuestionDescription()); assertEquals(0, ((FeedbackTextQuestionDetails) typicalQuestion.getQuestionDetails()) .getRecommendedLength()); }
Source:
<code>public void updated(Dictionary<String, ?> properties) throws ConfigurationException { logger.debug("update start"); try { <START> setProperlyConfigured(false); <END> for (FatekPLCSlave slave : slaves.values()) { try { slave.disconnect(); } catch (FatekIOException e) { logger.warn("diconnect", e); } } slaves.clear(); refreshInterval = getLongProperty(properties, "refresh", refreshInterval); Enumeration<String> keys = properties.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); if (GLOBAL_CONFIG_NAMES.contains(key)) { continue; } String keyItems[] = key.split("\\."); if (keyItems.length != 2) { throw new ConfigurationException(key, "incorrect format, should be slave.property"); } FatekPLCSlave slave = slaves.get(keyItems[0]); if (slave == null) { slave = new FatekPLCSlave(keyItems[0], eventPublisher, itemRegistry); slaves.put(slave.getName(), slave); } slave.configure(keyItems[1], properties.get(key)); } } catch (ConfigurationException e) { logger.error("", e); throw e; } setProperlyConfigured(true); logger.info("Configuration has been updated, refresh={}", refreshInterval); }</code><technical_language>side effects toggling properlyConfigured; more changing a boolean (AbstractActiveService class). set end of method final answer</technical_language>

Target:
public void updated(Dictionary<String, ?> properties) throws ConfigurationException { logger.debug("update start"); try { for (FatekPLCSlave slave : slaves.values()) { try { slave.disconnect(); } catch (FatekIOException e) { logger.warn("diconnect", e); } } slaves.clear(); refreshInterval = getLongProperty(properties, "refresh", refreshInterval); Enumeration<String> keys = properties.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); if (GLOBAL_CONFIG_NAMES.contains(key)) { continue; } String keyItems[] = key.split("\\."); if (keyItems.length != 2) { throw new ConfigurationException(key, "incorrect format, should be slave.property"); } FatekPLCSlave slave = slaves.get(keyItems[0]); if (slave == null) { slave = new FatekPLCSlave(keyItems[0], eventPublisher); slaves.put(slave.getName(), slave); } slave.configure(keyItems[1], properties.get(key)); } } catch (ConfigurationException e) { logger.error("", e); throw e; } setProperlyConfigured(true); logger.info("Configuration has been updated, refresh={}", refreshInterval); }
Source:
<code>public void testShowColumnsFromPartitions() { String tableName = "test_show_columns_from_partitions"; @Language("SQL") String createTable = "" + "CREATE TABLE " + tableName + " " + "(" + " foo VARCHAR," + " part1 BIGINT," + " part2 VARCHAR" + ") " + "WITH (" + "partitioned_by = ARRAY[ 'part1', 'part2' ]" + ") "; assertUpdate(getSession(), createTable); assertQuery( getSession(), "SHOW COLUMNS FROM \"" + tableName + "$partitions\"", "VALUES ('part1', 'bigint', '', ''), ('part2', 'varchar', '', '')"); assertQueryFails( getSession(), "SHOW COLUMNS FROM \"$partitions\"", <START> ".*Table '.*.tpch\\.\\$partitions' does not exist"); <END> assertQueryFails( getSession(), "SHOW COLUMNS FROM \"orders$partitions\"", ".*Table '.*\\.tpch\\.orders\\$partitions' does not exist"); assertQueryFails( getSession(), "SHOW COLUMNS FROM \"blah$partitions\"", ".*Table '.*.tpch\\.blah\\$partitions' does not exist"); }</code><technical_language>escape '.' character, rest: .*\\.tpch\\. escape L1273 below, in changes</technical_language>

Target:
public void testShowColumnsFromPartitions() { String tableName = "test_show_columns_from_partitions"; @Language("SQL") String createTable = "" + "CREATE TABLE " + tableName + " " + "(" + " foo VARCHAR," + " part1 BIGINT," + " part2 VARCHAR" + ") " + "WITH (" + "partitioned_by = ARRAY[ 'part1', 'part2' ]" + ") "; assertUpdate(getSession(), createTable); assertQuery( getSession(), "SHOW COLUMNS FROM \"" + tableName + "$partitions\"", "VALUES ('part1', 'bigint', '', ''), ('part2', 'varchar', '', '')"); assertQueryFails( getSession(), "SHOW COLUMNS FROM \"$partitions\"", ".*Table '.*\\.tpch\\.\\$partitions' does not exist"); assertQueryFails( getSession(), "SHOW COLUMNS FROM \"orders$partitions\"", ".*Table '.*\\.tpch\\.orders\\$partitions' does not exist"); assertQueryFails( getSession(), "SHOW COLUMNS FROM \"blah$partitions\"", ".*Table '.*\\.tpch\\.blah\\$partitions' does not exist"); }
Source:
<code>public void processBindingConfiguration(String context, Item item, String bindingConfig) throws BindingConfigParseException { <START> super.processBindingConfiguration(context, item, bindingConfig); <END> MyqBindingConfig config = parseBindingConfig(item, bindingConfig); addBindingConfig(item, config); }</code><technical_language>move end of method in case code throws a BindingConfigParseException, in case want pollute internal openHAB data structures bad data</technical_language>

Target:
public void processBindingConfiguration(String context, Item item, String bindingConfig) throws BindingConfigParseException { MyqBindingConfig config = parseBindingConfig(item, bindingConfig); addBindingConfig(item, config); super.processBindingConfiguration(context, item, bindingConfig); }
Source:
<code>public void testNegativePositionsAreAllowed() { final GridPosition initialGridPosition = new GridPosition(-1, -1); final Orientation initialOrientation = Orientation.SOUTH; <START> final Robot robot = new Robot(initialGridPosition, Orientation.SOUTH); <END> assertEquals(robot.getOrientation(), initialOrientation); assertEquals(robot.getGridPosition(), initialGridPosition); }</code><technical_language>for this test, please initialOrientation creating robot</technical_language>

Target:
public void testNegativePositionsAreAllowed() { final GridPosition initialGridPosition = new GridPosition(-1, -1); final Orientation initialOrientation = Orientation.SOUTH; final Robot robot = new Robot(initialGridPosition, initialOrientation); assertEquals(robot.getOrientation(), initialOrientation); assertEquals(robot.getGridPosition(), initialGridPosition); }
Source:
<code>private boolean hasActualVideo() { if (mVideoTrackCount > 0) { return true; } VideoSize videoSize = mPlayer.getVideoSize(); if (videoSize.getHeight() > 0 && videoSize.getWidth() > 0) { Log.w(TAG, "video track count is zero, but it renders video. size: " + <START> videoSize.getWidth() + "/" + videoSize.getHeight()); <END> return true; } return false; }</code><technical_language>videoSize</technical_language>

Target:
private boolean hasActualVideo() { if (mVideoTrackCount > 0) { return true; } VideoSize videoSize = mPlayer.getVideoSize(); if (videoSize.getHeight() > 0 && videoSize.getWidth() > 0) { Log.w(TAG, "video track count is zero, but it renders video. size: " + videoSize); return true; } return false; }
Source:
<code>private boolean runTaskOnWorker( final HttpRemoteTaskRunnerWorkItem workItem, final String workerHost ) throws Exception { String taskId = workItem.getTaskId(); WorkerHolder workerHolder = workers.get(workerHost); if (workerHolder == null || lazyWorkers.containsKey(workerHost) || blackListedWorkers.containsKey(workerHost)) { log.info("Not assigning task[%s] to removed or marked lazy/blacklisted worker[%s]", taskId, workerHost); return false; } log.info("Asking Worker[%s] to run task[%s]", workerHost, taskId); if (workerHolder.assignTask(workItem.getTask())) { long waitMs = config.getTaskAssignmentTimeout().toStandardDuration().getMillis(); long waitStart = System.currentTimeMillis(); <START> boolean isTaskAssignmentTimedout = false; <END> synchronized (statusLock) { while (tasks.containsKey(taskId) && tasks.get(taskId).getState() == HttpRemoteTaskRunnerWorkItem.State.PENDING) { long remaining = waitMs - (System.currentTimeMillis() - waitStart); if (remaining > 0) { statusLock.wait(remaining); } else { isTaskAssignmentTimedout = true; break; } } } if (isTaskAssignmentTimedout) { log.makeAlert( "Task assignment timed out on worker [%s], never ran task [%s] in timeout[%s]!", workerHost, taskId, config.getTaskAssignmentTimeout() ).emit(); taskComplete(workItem, workerHolder, TaskStatus.failure(taskId)); } return true; } else { return false; } }</code><technical_language>nit: isTaskAssignmentTimedOut (spelling: timed out is words.)</technical_language>

Target:
private boolean runTaskOnWorker( final HttpRemoteTaskRunnerWorkItem workItem, final String workerHost ) throws Exception { String taskId = workItem.getTaskId(); WorkerHolder workerHolder = workers.get(workerHost); if (workerHolder == null || lazyWorkers.containsKey(workerHost) || blackListedWorkers.containsKey(workerHost)) { log.info("Not assigning task[%s] to removed or marked lazy/blacklisted worker[%s]", taskId, workerHost); return false; } log.info("Asking Worker[%s] to run task[%s]", workerHost, taskId); if (workerHolder.assignTask(workItem.getTask())) { long waitMs = config.getTaskAssignmentTimeout().toStandardDuration().getMillis(); long waitStart = System.currentTimeMillis(); boolean isTaskAssignmentTimedOut = false; synchronized (statusLock) { while (tasks.containsKey(taskId) && tasks.get(taskId).getState() == HttpRemoteTaskRunnerWorkItem.State.PENDING) { long remaining = waitMs - (System.currentTimeMillis() - waitStart); if (remaining > 0) { statusLock.wait(remaining); } else { isTaskAssignmentTimedOut = true; break; } } } if (isTaskAssignmentTimedOut) { log.makeAlert( "Task assignment timed out on worker [%s], never ran task [%s] in timeout[%s]!", workerHost, taskId, config.getTaskAssignmentTimeout() ).emit(); taskComplete(workItem, workerHolder, TaskStatus.failure(taskId)); } return true; } else { return false; } }
Source:
<code>public Transcriber(String roomName, TranscriptionService service) { if(!service.supportsStreamRecognition()) { throw new IllegalArgumentException("Currently only services which" + " support streaming recognition are supported"); } this.transcriptionService = service; <START> addTranscriptionListener(this.transcript); <END> }</code><technical_language>handle roomName</technical_language>

Target:
public Transcriber(String roomName, TranscriptionService service) { if(!service.supportsStreamRecognition()) { throw new IllegalArgumentException("Currently only services which" + " support streaming recognition are supported"); } this.transcriptionService = service; addTranscriptionListener(this.transcript); this.roomName = roomName; }
Source:
<code>public double calculateArea() { <START> return getBounds().calculateArea() * envelope.getArea() / polygon.getGeometry().getArea(); <END> }</code><technical_language>Do remove this method, definition Shape? generically in code, easily avoid giving "approximate" fudged implementation here</technical_language>

Target:
public double calculateArea() { return getBounds().calculateArea() * envelope.getArea() / prepPolygon.getGeometry().getArea(); }
Source:
<code>private boolean layerGroupContainmentCheckRequired() { Request request = Dispatcher.REQUEST.get(); if(request == null) { return false; } final String service = request.getService(); boolean isMapService = "WMS".equalsIgnoreCase(service) || "gwc".equalsIgnoreCase(service); if(!isMapService) { return false; } <START> return true; <END> }</code><technical_language>lines squashed into: return "WMS".equalsIgnoreCase(service) || "gwc".equalsIgnoreCase(service);</technical_language>

Target:
private boolean layerGroupContainmentCheckRequired() { Request request = Dispatcher.REQUEST.get(); if(request == null) { return false; } final String service = request.getService(); return "WMS".equalsIgnoreCase(service) || "gwc".equalsIgnoreCase(service); }
Source:
<code><START> public FileServiceClientBuilder credential(SASTokenCredential credential) { <END> this.sasTokenCredential = Objects.requireNonNull(credential); return this; }</code><technical_language>Need add support for SharedKeyCredential</technical_language>

Target:
public FileServiceClientBuilder credential(SASTokenCredential credential) { this.sasTokenCredential = Objects.requireNonNull(credential); this.sharedKeyCredential = null; return this; }
Source:
<code>private boolean processConfigurationDetails(Document document) { <START> boolean not_compatible = true; <END> Node rootNode = document.getElementsByTagName(PARAMETER_FILE_ROOT).item(0); for (int j = 0; j < rootNode.getAttributes().getLength(); j++) { Node propertyNode = rootNode.getAttributes().item(j); switch (propertyNode.getNodeName()) { case RUN_TIME_PROPERTIES: String runTimePropertyString = propertyNode.getNodeValue(); if (!EMPTY_STRING.equals(runTimePropertyString)) { String[] properties = runTimePropertyString.split(PROPERTY_SEPERATOR); int currentIndex = 0; while (currentIndex < properties.length) { runTimeProperties.put(properties[currentIndex], properties[currentIndex + 1]); currentIndex += 2; } } break; case NOT_XSLT_COMPATIBLE: if (propertyNode.getNodeValue().equals(XSLT_COMPATIBLE_DEFAULT)) { not_compatible = false; } else { return not_compatible; } break; case FIRST_ELEMENT_OF_THE_INPUT: this.name = propertyNode.getNodeValue(); break; } } if (this.name == null) { return true; } return not_compatible; }</code><technical_language>I suppose instead of not_compatible = true, compatible = false. easy interpret. WDYT</technical_language>

Target:
private boolean processConfigurationDetails(Document document) { boolean compatible = false; Node rootNode = document.getElementsByTagName(PARAMETER_FILE_ROOT).item(0); for (int j = 0; j < rootNode.getAttributes().getLength(); j++) { Node propertyNode = rootNode.getAttributes().item(j); switch (propertyNode.getNodeName()) { case RUN_TIME_PROPERTIES: String runTimePropertyString = propertyNode.getNodeValue(); if (!EMPTY_STRING.equals(runTimePropertyString)) { String[] properties = runTimePropertyString.split(PROPERTY_SEPERATOR); int currentIndex = 0; while (currentIndex < properties.length) { runTimeProperties.put(properties[currentIndex], properties[currentIndex + 1]); currentIndex += 2; } } break; case NOT_XSLT_COMPATIBLE: if (propertyNode.getNodeValue().equals(XSLT_COMPATIBLE_DEFAULT)) { compatible = true; } else { return compatible; } break; case FIRST_ELEMENT_OF_THE_INPUT: this.name = propertyNode.getNodeValue(); break; } } if (this.name == null) { return false; } return compatible; }
Source:
<code>private GeoHashLocation acquireGeohash() { provider = determineProviderRuntime(checker); if (provider == null) { return location; } try { <START> if (!manager.isProviderEnabled(provider)) { <END> return location; } Location fresh = manager.getLastKnownLocation(provider); if (fresh == null) { return location; } if (location == null || location.isDifferent(fresh)) { return new GeoHashLocation(fresh); } } catch (SecurityException ex) { Logger.log.logError("Missing permission for "+provider+" provider", ex); } catch (IllegalArgumentException ex) { Logger.log.logError("Provider "+provider+" is missing on this device", ex); } return location; }</code><technical_language>suggestion change. discuss slack Java List<Location> locations = new ArrayList<>(3); List<String> providers = manager.getProviders(true); for (int i = 0, size = providers.size(); i < size; i++) { String provider = providers.get(i); Location location = manager.getLastKnownLocation(provider); if(isAccurateAndFreshAndNotNull(location)){ locations.add(location); } } Location freshest = null; if (locations.size() > 1) { Collections.sort(locations, timeComparator); } if (locations.size() > 0) { freshest = locations.get(0); }</technical_language>

Target:
private GeoHashLocation acquireGeohash() { List<Location> locations = new ArrayList<>(3); if (isAccurateAndFreshAndNotNull(location)) { locations.add(location); } List<String> providers = manager.getProviders(true); for (int i = 0, size = providers.size(); i < size; i++) { String provider = providers.get(i); try { Location location = manager.getLastKnownLocation(provider); if (isAccurateAndFreshAndNotNull(location)) { locations.add(location); } } catch (SecurityException ex) { Logger.log.logError("Missing permission for " + provider + " provider", ex); } } Location freshest = null; if (locations.size() > 1) { Collections.sort(locations, timeComparator); } if (locations.size() > 0) { freshest = locations.get(0); } if (freshest instanceof GeoHashLocation) { return (GeoHashLocation) freshest; } else { return freshest == null ? null : new GeoHashLocation(freshest); } }
Source:
<code>BufferableHandle[] formatAll(AbstractWriteHandle[] value) { <START> BufferableHandle[] bufferableHandle = new BufferableHandle[value.length]; <END> for (int i=0; i<value.length; i++) { if(!(value[i] instanceof BufferableHandle)) throw new IllegalArgumentException("BufferableHandle array cannot be created."); NodeConverter.withFormat(value[i], getFormat()); bufferableHandle[i] = (BufferableHandle) value[i]; } return bufferableHandle; }</code><technical_language>singular, is bufferableHandle name easy misread a single instead of multiple values</technical_language>

Target:
BufferableHandle[] formatAll(AbstractWriteHandle[] value) { BufferableHandle[] bufferableHandles = new BufferableHandle[value.length]; for (int i=0; i<value.length; i++) { if(!(value[i] instanceof BufferableHandle)) throw new IllegalArgumentException("AbstractWriteHandle value is not an instance of BufferableHandle."); NodeConverter.withFormat(value[i], getFormat()); bufferableHandles[i] = (BufferableHandle) value[i]; } return bufferableHandles; }
Source:
<code>public Response cleanInfinispanCache( @ApiParam( "The name of cache to clean" ) @PathParam( "name" ) final String name ) { <START> return Response.status( FORBIDDEN ).build(); <END> }</code><technical_language>Some of caches disposable though...I if want a ban list, a whitelist? willing talked out of position, inclined able clear caches...things koji metadata cache, for example</technical_language>

Target:
public Response cleanInfinispanCache( @ApiParam( "The name of cache to clean" ) @PathParam( "name" ) final String name ) { Response response; try { ispnCacheController.clean( name ); response = Response.ok().build(); } catch ( IndyWorkflowException e ) { logger.error( String.format( "Failed to clean: %s. Reason: %s", name, e.getMessage() ), e ); response = responseHelper.formatResponse( e ); } return response; }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { <START> try (Closeable ignored = populateTraceContext(request)) { <END> chain.doFilter(request, response); } }</code><technical_language>ignored, right</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Closeable traceContext = populateTraceContext(request); try { chain.doFilter(request, response); } finally { traceContext.close(); } }
Source:
<code>public void activate() { try { logger.debug("Activating CarbonCoreComponent"); ConfigProvider configProvider = DataHolder.getInstance().getOptConfigProvider().get(); <START> CarbonRuntime carbonRuntime = CarbonRuntimeFactory.createCarbonRuntime(configProvider); <END> DataHolder.getInstance().getBundleContext() .registerService(CarbonRuntime.class.getName(), carbonRuntime, null); } catch (Throwable throwable) { logger.error("Error while activating CarbonCoreComponent"); } }</code><technical_language>This formatted is additional space added in front</technical_language>

Target:
public void activate() { try { logger.debug("Activating CarbonCoreComponent"); ConfigProvider configProvider = DataHolder.getInstance().getConfigProvider(); CarbonRuntime carbonRuntime = CarbonRuntimeFactory.createCarbonRuntime(configProvider); DataHolder.getInstance().getBundleContext() .registerService(CarbonRuntime.class.getName(), carbonRuntime, null); } catch (Throwable throwable) { logger.error("Error while activating CarbonCoreComponent"); } }
Source:
<code>public LoggingPreferences getLoggingPreferences() throws JSONException { LoggingPreferences ret = null; Object o = getCapability(CapabilityType.LOGGING_PREFS); if (o != null) { ret = new LoggingPreferences(); if (o instanceof JSONObject){ JSONObject json = (JSONObject) o; Iterator<String> iter = json.keys(); <START> while (iter.hasNext()) { <END> String key = iter.next(); Level level = Level.parse((String) json.get(key)); ret.enable(key, level); } } } return ret; }</code><technical_language>Replaced for loop: <LINK_0></technical_language>

Target:
public LoggingPreferences getLoggingPreferences() throws JSONException { LoggingPreferences loggingPrefs = null; Object loggingPrefsJson = getCapability(CapabilityType.LOGGING_PREFS); if (loggingPrefsJson != null) { loggingPrefs = new LoggingPreferences(); JSONObject json = (JSONObject) loggingPrefsJson; Iterator<String> iter = json.keys(); while(iter.hasNext()) { String logType = iter.next(); Level level = Level.parse((String) json.get(logType)); loggingPrefs.enable(logType, level); } } if (loggingPrefs == null) { return new LoggingPreferences(); } return loggingPrefs; }
Source:
<code>public void addContents(@NonNull Container container) { <START> Jenkins j = Jenkins.getActiveInstance(); <END> addUnixContents(container, j); for (Node node : j.getNodes()) { addUnixContents(container, node); } }</code><technical_language>NIT: part of a PR (I assume safe get rid of helper version in Jenkins class</technical_language>

Target:
public void addContents(@NonNull Container container) { Jenkins j = Jenkins.getInstance(); addUnixContents(container, j); for (Node node : j.getNodes()) { addUnixContents(container, node); } }
Source:
<code>public void testLaunchpadStressByCreatingLotsOfFrameworksInDifferentThreads() throws Exception { List<Launchpad> l = new CopyOnWriteArrayList<>(); List<Throwable> e = new CopyOnWriteArrayList<>(); Random r = new Random(); Semaphore semaphore = new Semaphore(0); builder.bundles("org.apache.felix.log, org.apache.felix.scr") .runfw("org.apache.felix.framework"); int n = 20; for (int i = 0; i < n; i++) { Launchpad fw = builder.create("foo", "bar"); l.add(fw); Processor.getExecutor() .execute(() -> { try { Bundle bundle = fw.component(ExternalRefComp.class); int sleep = Math.abs(r.nextInt() % 100) + 30; System.out.println( fw.runspec.properties.get(org.osgi.framework.Constants.FRAMEWORK_STORAGE) + " " + sleep); Thread.sleep(sleep); softly.assertThat(fw.getService(ExternalRefComp.class)) .isNotNull(); bundle.stop(); } catch (Throwable ee) { softly.fail(ee.toString(), ee); } finally { semaphore.release(); } }); } System.out.println("Waiting for the threads to finish"); boolean success = semaphore.tryAcquire(n, 60, TimeUnit.SECONDS); <START> assertTrue(success); <END> System.out.println("Closing " + n + " frameworks"); l.forEach(IO::close); }</code><technical_language>I want softly assert this close frameworks</technical_language>

Target:
public void testLaunchpadStressByCreatingLotsOfFrameworksInDifferentThreads() throws Exception { List<Launchpad> l = new CopyOnWriteArrayList<>(); List<Throwable> e = new CopyOnWriteArrayList<>(); Random r = new Random(); Semaphore semaphore = new Semaphore(0); builder.bundles("org.apache.felix.log, org.apache.felix.scr") .runfw("org.apache.felix.framework"); int n = 20; for (int i = 0; i < n; i++) { Launchpad fw = builder.create("foo", "bar"); l.add(fw); Processor.getExecutor() .execute(() -> { try { Bundle bundle = fw.component(ExternalRefComp.class); int sleep = Math.abs(r.nextInt() % 100) + 30; System.out.println( fw.runspec.properties.get(org.osgi.framework.Constants.FRAMEWORK_STORAGE) + " " + sleep); Thread.sleep(sleep); softly.assertThat(fw.getService(ExternalRefComp.class)) .isNotNull(); bundle.stop(); } catch (Throwable ee) { softly.fail(ee.toString(), ee); } finally { semaphore.release(); } }); } System.out.println("Waiting for the threads to finish"); boolean success = semaphore.tryAcquire(n, 60, TimeUnit.SECONDS); softly.assertThat(success) .isTrue(); System.out.println("Closing " + n + " frameworks"); l.forEach(IO::close); }
Source:
<code>private Block filterAndSend(InboundMessageQueuer p1, List<Block> blocks, BloomFilter filter) { Block exhaustionPoint = null; for (int i = 0; i < blocks.size(); i++) { Block block = blocks.get(i); FilteredBlock fb = filter.applyAndUpdate(block); inbound(p1, fb); for (Transaction tx : fb.getAssociatedTransactions().values()) inbound(p1, tx); <START> if (i == 3) END> exhaustionPoint = block; } return exhaustionPoint; }</code><technical_language>caller in a position block is exhaustion point? this method return void</technical_language>

Target:
private void filterAndSend(InboundMessageQueuer p1, List<Block> blocks, BloomFilter filter) { for (Block block : blocks) { FilteredBlock fb = filter.applyAndUpdate(block); inbound(p1, fb); for (Transaction tx : fb.getAssociatedTransactions().values()) inbound(p1, tx); } }
Source:
<code>private boolean singleMatchRune(int r) { int r0 = runes[0]; if (r == r0) { return true; } if ((arg & RE2.FOLD_CASE) != 0) { int[] folds = Unicode.optimizedFoldOrbit(r0); if (folds == null) { <START> return (r == Unicode.optimizedFoldNonOrbit(r0)); <END> } else { for(int i = 0; i < folds.length; i++) { if (folds[i] == r) return true; } } } return false; }</code><technical_language>benchmarked this implementation based Character.toLowerCase(r) == r? Ideally a changes that, throw Unicode tables built java.lang. int (code point) char (UTF-16 code) variants of functions</technical_language>

Target:
private boolean singleMatchRune(int r) { int r0 = runes[0]; if (r == r0) { return true; } if ((arg & RE2.FOLD_CASE) != 0) { int[] folds = Unicode.optimizedFoldOrbit(r0); if (folds == null) { return Unicode.areEqualsCaseInsensitive(r, r0); } else { for(int i = 0; i < folds.length; i++) { if (folds[i] == r) return true; } } } return false; }
Source:
<code>static void visitObject(JsonParser parser, String name, Set<String> result) throws IOException { if (!parser.isExpectedStartObjectToken()) { throw new IOException("Expecting object start, got " + parser.currentToken()); } JsonToken value; while ((value = parser.nextValue()) != JsonToken.END_OBJECT) { if (value == null) { <START> throw new IOException("End of input while parsing object."); <END> } if (parser.getCurrentName().equals(name)) { result.add(parser.getText()); } else { visitNextOrSkip(parser, name, result); } } }</code><technical_language>I IOExceptions turned null returns possibly log.fine guarded if important. Starting throw break things</technical_language>

Target:
static void visitObject(JsonParser parser, String name, Set<String> result) throws IOException { if (!parser.isExpectedStartObjectToken()) { throw new IOException("Expecting object start, got " + parser.currentToken()); } JsonToken value; while ((value = parser.nextValue()) != JsonToken.END_OBJECT) { if (value == null) { return; } if (parser.getCurrentName().equals(name)) { result.add(parser.getText()); } else { visitNextOrSkip(parser, name, result); } } }
Source:
<code>private Collection<IInstallableUnit> findUpdates(IInstallableUnit iu, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); Collection<IInstallableUnit> availableUpdates = new HashSet<>(); IQueryResult<IInstallableUnit> updatesAvailable = planner.updatesFor(iu, provisioningContext, subMonitor.split(1)); for (IInstallableUnit <START> iInstallableUnit : <END> updatesAvailable) { availableUpdates.add(iInstallableUnit); } return availableUpdates; }</code><technical_language>rename iu</technical_language>

Target:
private Collection<IInstallableUnit> findUpdates(IInstallableUnit iu, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); Collection<IInstallableUnit> availableUpdates = new HashSet<>(); IQueryResult<IInstallableUnit> updatesAvailable = planner.updatesFor(iu, provisioningContext, subMonitor.split(1)); for (IInstallableUnit iuu : updatesAvailable) { availableUpdates.add(iuu); } return availableUpdates; }
Source:
<code>private ServerTemplate loadServerTemplate(String serverTemplateId) { <START> ServerTemplate template = getTemplateStorage().load(serverTemplateId); <END> if (template == null) { throw new RuntimeException("No server template found for id " + serverTemplateId); } return template; }</code><technical_language>(final)</technical_language>

Target:
private ServerTemplate loadServerTemplate(String serverTemplateId) { final ServerTemplate template = getTemplateStorage().load(serverTemplateId); if (template == null) { throw new RuntimeException("No server template found for id " + serverTemplateId); } return template; }
Source:
<code>public CalcState(final JSONObject json) { format = Settings.CoordInputFormatEnum.values()[json.optInt("format", 2)]; plainLat = json.optString("plainLat"); plainLon = json.optString("plainLon"); latHemisphere = (char) json.optInt("latHemisphere", ERROR_CHAR); lonHemisphere = (char) json.optInt("lonHemisphere", ERROR_CHAR); <START> { <END> final JSONArray array = json.optJSONArray("buttons"); final int arrayLength = array != null ? array.length() : 0; buttons = new ArrayList<>(arrayLength); for (int i = 0; i < arrayLength; i++) { buttons.add(new CalculateButton.ButtonData(array.optJSONObject(i))); } } { final JSONArray array = json.optJSONArray("equations"); final int arrayLength = array != null ? array.length() : 0; equations = new ArrayList<>(arrayLength); for (int i = 0; i < arrayLength; i++) { equations.add(new CalculatorVariable.VariableData(array.optJSONObject(i))); } } { final JSONArray array = json.optJSONArray("freeVariables"); final int arrayLength = array != null ? array.length() : 0; freeVariables = new ArrayList<>(arrayLength); for (int i = 0; i < arrayLength; i++) { freeVariables.add(new CalculatorVariable.VariableData(array.optJSONObject(i))); } } notes = json.optString("notes"); }</code><technical_language>Is missing here? A lot of groups control structure</technical_language>

Target:
private CalcState(final JSONObject json) { format = CoordInputFormatEnum.values()[json.optInt("format", 2)]; plainLat = json.optString("plainLat"); plainLon = json.optString("plainLon"); latHemisphere = (char) json.optInt("latHemisphere", ERROR_CHAR); lonHemisphere = (char) json.optInt("lonHemisphere", ERROR_CHAR); buttons = createJSONAbleList(json.optJSONArray("buttons"), new CalculateButton.ButtonDataFactory()); equations = createJSONAbleList(json.optJSONArray("equations"), new CalculatorVariable.VariableDataFactory()); freeVariables = createJSONAbleList(json.optJSONArray("freeVariables"), new CalculatorVariable.VariableDataFactory()); variableBank = new ArrayList<>(); notes = json.optString("notes"); }
Source:
<code>public void refreshHeavyWeightData() { log.debug("Refreshing Gluster Data [heavyweight]"); for (VDSGroup cluster : getClusterDao().getAll()) { <START> if (cluster.getcompatibility_version().compareTo(Version.v3_2) >= 0 && cluster.supportsGlusterService()) { <END> try { refreshClusterHeavyWeightData(cluster); } catch (Exception e) { log.errorFormat("Error while refreshing Gluster heavyweight data of cluster {0}!", cluster.getname(), e); } } } }</code><technical_language>configuration infrastructure for compatibility checks, hard-coding, please check out examples in FeatureSupported class</technical_language>

Target:
public void refreshHeavyWeightData() { log.debug("Refreshing Gluster Data [heavyweight]"); for (VDSGroup cluster : getClusterDao().getAll()) { if (GlusterFeatureSupported.refreshHeavyWeight(cluster.getcompatibility_version()) && cluster.supportsGlusterService()) { try { refreshClusterHeavyWeightData(cluster); } catch (Exception e) { log.errorFormat("Error while refreshing Gluster heavyweight data of cluster {0}!", cluster.getname(), e); } } } }
Source:
<code>public void testUpdate() throws InterruptedException { server.enqueue( new MockResponse().setBody(stringFromResource("/publicip/get.json")) ); PublicIp response = publicIpApi().update("publicipId", PublicIp.UpdatePublicIp.create("reverseDns")); assertNotNull(response); assertEquals(server.getRequestCount(), 1); <START> assertSent(server, "PUT", "/public_ips/publicipId"); <END> }</code><technical_language>verify payload of request</technical_language>

Target:
public void testUpdate() throws InterruptedException { server.enqueue( new MockResponse().setBody(stringFromResource("/publicip/get.json")) ); PublicIp response = publicIpApi().update("publicipId", PublicIp.UpdatePublicIp.create("reverseDns")); assertNotNull(response); assertEquals(server.getRequestCount(), 1); assertSent(server, "PUT", "/public_ips/publicipId", "{\"reverse_dns\":\"reverseDns\"}"); }
Source:
<code>public void synchronouslyInitializedManagerIsInitializedEvenIfKvsIsNot() { SerializableTransactionManager theManager = SerializableTransactionManager.create( mockKvs, mockTimelockService, null, null, () -> null, null, null, mockCleaner, mockInitializer, false, () -> 1L, 1, false); <START> when(mockKvs.isInitialized()).thenReturn(false); <END> assertTrue(theManager.isInitialized()); }</code><technical_language>set mocks return false</technical_language>

Target:
public void synchronouslyInitializedManagerIsInitializedEvenIfKvsIsNot() { SerializableTransactionManager theManager = SerializableTransactionManager.create( mockKvs, mockTimelockService, null, null, () -> null, null, null, mockCleaner, mockInitializer, false, () -> 1L, 1, false); when(mockKvs.isInitialized()).thenReturn(false); when(mockTimelockService.isInitialized()).thenReturn(false); when(mockCleaner.isInitialized()).thenReturn(false); when(mockInitializer.isInitialized()).thenReturn(false); assertTrue(theManager.isInitialized()); }
Source:
<code>private void saveImageToMediaStore() { if (galleryItem == null) { return; } parentActivity.getFunnel().logGallerySave(pageTitle, galleryItem.getName()); new SaneAsyncTask<String>(SaneAsyncTask.SINGLE_THREAD) { @Override public String performTask() throws Throwable { return MediaStore.Images.Media.insertImage(parentActivity.getContentResolver(), ((BitmapDrawable) mainImage.getDrawable()).getBitmap(), <START> pageTitle.getDisplayText(), galleryItem.getName()); <END> } @Override public void onFinish(String result) { if (!isAdded()) { return; } if (result != null) { Toast.makeText(parentActivity, getString(R.string.gallery_save_success), Toast.LENGTH_SHORT).show(); } else { parentActivity.showError(getString(R.string.gallery_save_error_unknown)); } } @Override public void onCatch(Throwable caught) { if (!isAdded()) { return; } parentActivity.showError(String.format(getString(R.string.gallery_save_error), caught.getLocalizedMessage())); } }.execute(); }</code><technical_language>This simplified follows: task (returning Void), return insertImage(), if return is null, throw a RuntimeException new error message string. exception caught onCatch block below, displayed automatically. (no need handle in onFinish)</technical_language>

Target:
private void saveImageToMediaStore() { if (galleryItem == null) { return; } parentActivity.getFunnel().logGallerySave(pageTitle, galleryItem.getName()); new SaneAsyncTask<Void>(SaneAsyncTask.SINGLE_THREAD) { @Override public Void performTask() throws Throwable { String url = MediaStore.Images.Media.insertImage(parentActivity.getContentResolver(), ((BitmapDrawable) mainImage.getDrawable()).getBitmap(), pageTitle.getDisplayText(), galleryItem.getName()); if (url == null) throw new RuntimeException(getString(R.string.gallery_save_error_unknown)); return null; } @Override public void onFinish(Void result) { if (!isAdded()) { return; } Toast.makeText(parentActivity, getString(R.string.gallery_save_success), Toast.LENGTH_SHORT).show(); } @Override public void onCatch(Throwable caught) { if (!isAdded()) { return; } parentActivity.showError(String.format(getString(R.string.gallery_save_error), caught.getLocalizedMessage())); } }.execute(); }
Source:
<code>protected void analyze() { if (isVmStoppedBeingReported()) { proceedDisappearedVm(); return; } if (isExternalOrUnmanagedHostedEngineVm()) { processUnmanagedVm(); return; } if (isVmDown()) { proceedDownVm(); return; } <START> if (isVmRebooting()) { <END> proceedRebootingVm(); } if (!isVmRunningInDatabaseOnMonitoredHost()) { proceedVmReportedOnOtherHost(); return; } proceedVmReportedOnExpectedHost(); }</code><technical_language>Please move this call proceedVmReportedOnExpectedHost() method. method contains multiple similar statements, check VM state add audit log line</technical_language>

Target:
protected void analyze() { if (isVmStoppedBeingReported()) { proceedDisappearedVm(); return; } if (isExternalOrUnmanagedHostedEngineVm()) { processUnmanagedVm(); return; } if (isVmDown()) { proceedDownVm(); return; } if (!isVmRunningInDatabaseOnMonitoredHost()) { proceedVmReportedOnOtherHost(); return; } proceedVmReportedOnExpectedHost(); }
Source:
<code>private SymbolToken intern(final String text) { if (text == null) return null; SymbolToken token = lst.intern(text); <START> newSymbols |= token.getSid() > maxSysId; <END> return token; }</code><technical_language>newSymbols more accurately named hasLocalSymbols</technical_language>

Target:
private SymbolToken intern(final String text) { if (text == null) return null; SymbolToken token = lst.intern(text); hasUnflushedLocalSymbols |= token.getSid() > maxSysId; return token; }
Source:
<code>private void deleteQuestion() { String questionId = getRequestParamValue(Const.ParamsNames.FEEDBACK_QUESTION_ID); <START> Assumption.assertPostParamNotNull(Const.ParamsNames.FEEDBACK_QUESTION_ID, questionId); <END> String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertPostParamNotNull(Const.ParamsNames.COURSE_ID, courseId); String feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); Assumption.assertPostParamNotNull(Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackSessionName); String questionNumber = getRequestParamValue(Const.ParamsNames.FEEDBACK_QUESTION_NUMBER); Assumption.assertPostParamNotNull(Const.ParamsNames.FEEDBACK_QUESTION_NUMBER, questionNumber); logic.deleteFeedbackQuestion(questionId); statusToUser.add(new StatusMessage(Const.StatusMessages.FEEDBACK_QUESTION_DELETED, StatusMessageColor.SUCCESS)); statusToAdmin = "Feedback Question " + questionNumber + " for session:<span class=\"bold\">(" + feedbackSessionName + ")</span> for Course <span class=\"bold\">[" + courseId + "]</span> deleted.<br>"; }</code><technical_language>getNonNullRequestParamValue instead</technical_language>

Target:
private void deleteQuestion() { String questionId = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_QUESTION_ID); String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); String questionNumber = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_QUESTION_NUMBER); logic.deleteFeedbackQuestion(questionId); statusToUser.add(new StatusMessage(Const.StatusMessages.FEEDBACK_QUESTION_DELETED, StatusMessageColor.SUCCESS)); statusToAdmin = "Feedback Question " + questionNumber + " for session:<span class=\"bold\">(" + feedbackSessionName + ")</span> for Course <span class=\"bold\">[" + courseId + "]</span> deleted.<br>"; }
Source:
<code>public Map<K, V> getNextTrainingData() { final List<K> nextTrainingDataKeyList; synchronized (this) { if (trainingDataKeys.isEmpty()) { LOG.log(Level.INFO, "no more training data for current epoch"); return Collections.emptyMap(); } nextTrainingDataKeyList = new ArrayList<>( trainingDataKeys.subList(0, Math.min(miniBatchSize, trainingDataKeys.size()))); trainingDataKeys = trainingDataKeys <START> .subList(Math.min(miniBatchSize, trainingDataKeys.size()), trainingDataKeys.size()); <END> } final Map<K, V> nextTrainingData = new HashMap<>(); for (final K key : nextTrainingDataKeyList) { final Pair<K, V> keyValuePair = memoryStore.get(key); if (keyValuePair == null) { continue; } nextTrainingData.put(keyValuePair.getFirst(), keyValuePair.getSecond()); } LOG.log(Level.INFO, "Size of training data for next mini-batch: {0}", nextTrainingData.size()); if (nextTrainingDataKeyList.size() != nextTrainingData.size()) { LOG.log(Level.INFO, "The number of assigned data keys for next mini-batch is {0}," + " but ths size of actually prepared training data is {1}", new Object[]{nextTrainingDataKeyList.size(), nextTrainingData.size()}); } return nextTrainingData; }</code><technical_language>nit: result of trainingDataKeys.size() result of Math.min() avoid redundant method invocation</technical_language>

Target:
public Map<K, V> getNextTrainingData() { final List<K> nextTrainingDataKeyList; synchronized (this) { if (trainingDataKeys.isEmpty()) { LOG.log(Level.INFO, "no more training data for current epoch"); return Collections.emptyMap(); } final int numRemainingKeys = trainingDataKeys.size(); final int nextBatchSize = Math.min(miniBatchSize, numRemainingKeys); nextTrainingDataKeyList = new ArrayList<>(trainingDataKeys.subList(0, nextBatchSize)); trainingDataKeys = trainingDataKeys.subList(nextBatchSize, numRemainingKeys); } final Map<K, V> nextTrainingData = new HashMap<>(); for (final K key : nextTrainingDataKeyList) { final Pair<K, V> keyValuePair = memoryStore.get(key); if (keyValuePair == null) { continue; } nextTrainingData.put(keyValuePair.getFirst(), keyValuePair.getSecond()); } LOG.log(Level.INFO, "Size of training data for next mini-batch: {0}", nextTrainingData.size()); if (nextTrainingDataKeyList.size() != nextTrainingData.size()) { LOG.log(Level.INFO, "The number of assigned data keys for next mini-batch is {0}," + " but ths size of actually prepared training data is {1}", new Object[]{nextTrainingDataKeyList.size(), nextTrainingData.size()}); } return nextTrainingData; }
Source:
<code>private void checkHeadBranchExist(PullRequestStory pullRequestStory) { RepoInfo headRepoInfo = pullRequestStory.item.head.repo.toInfo(); GetRepoClient getRepoClient = new GetRepoClient(headRepoInfo); GetReferenceClient referenceClient = new GetReferenceClient(headRepoInfo, pullRequestStory.item.head.ref); getRepoClient .observable() .flatMap((repo) -> { <START> hasPushPermissionsToHead = repo.permissions.push; <END> return referenceClient.observable() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<GitReference>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { notifyHeadOfAdapter(false); } @Override public void onNext(GitReference reference) { notifyHeadOfAdapter(true); } }); }</code><technical_language>check if permissions is null, i get null</technical_language>

Target:
private void checkHeadBranchExist(PullRequestStory pullRequestStory) { RepoInfo headRepoInfo = pullRequestStory.item.head.repo.toInfo(); GetRepoClient getRepoClient = new GetRepoClient(headRepoInfo); GetReferenceClient referenceClient = new GetReferenceClient(headRepoInfo, pullRequestStory.item.head.ref); getRepoClient .observable() .flatMap((repo) -> { if (repo.permissions != null) { hasPushPermissionsToHead = repo.permissions.push; } return referenceClient.observable() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<GitReference>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { notifyHeadOfAdapter(false); } @Override public void onNext(GitReference reference) { notifyHeadOfAdapter(true); } }); }
Source:
<code>public void setStackInSlot(int slot, ItemStack stack) { <START> ItemStack[] stacks = this.stacks; <END> validateSlotIndex(slot, stacks); if (ItemStack.areItemStacksEqual(stacks[slot], stack)) return; stacks[slot] = stack; onContentsChanged(slot); }</code><technical_language>minor, a bit redundant</technical_language>

Target:
public void setStackInSlot(int slot, ItemStack stack) { validateSlotIndex(slot); if (ItemStack.areItemStacksEqual(this.stacks[slot], stack)) return; this.stacks[slot] = stack; onContentsChanged(slot); }