auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>static public Expectation<List<OperationResult>> multiOp( final OvsdbClient client, DatabaseSchema dbs, final List<Table.OvsdbOperation> ops) { final Expectation<List<OperationResult>> result = new Expectation<>(); TransactionBuilder transaction = client.transactBuilder(dbs); for (Table.OvsdbOperation op: ops) { transaction.add(op.op); } FutureCallback<List<OperationResult>> cb = new FutureCallback<List<OperationResult>>() { @Override public void onSuccess(List<OperationResult> rlist) { OvsdbOpException exc = null; Integer idx = 0; for (OperationResult r: rlist) { if <START> (exc == null &&r.getError() != null && !r.getError().trim().isEmpty()) { <END> exc = new OvsdbOpException(client, idx, (idx >= ops.size())? null: ops.get(idx).op, r); } idx++; } if (exc != null) result.failure(exc); else result.success(rlist); } @Override public void onFailure(@Nonnull Throwable exc) { result.failure(new OvsdbException(client, exc)); } }; Futures.addCallback(transaction.execute(), cb, callingThreadExecutor); return result; }</code><technical_language>worth factoring this out a hasError function</technical_language>

Target:
static public Expectation<List<OperationResult>> multiOp( final OvsdbClient client, DatabaseSchema dbs, final List<Table.OvsdbOperation> ops) { final Expectation<List<OperationResult>> result = new Expectation<>(); TransactionBuilder transaction = client.transactBuilder(dbs); for (Table.OvsdbOperation op: ops) { transaction.add(op.op); } FutureCallback<List<OperationResult>> cb = new FutureCallback<List<OperationResult>>() { @Override public void onSuccess(List<OperationResult> rlist) { OvsdbOpException exc = null; Integer idx = 0; for (OperationResult r: rlist) { if (exc == null && opResultHasError(r)) { exc = new OvsdbOpException(client, ops, idx, r); } idx++; } if (exc != null) result.failure(exc); else result.success(rlist); } @Override public void onFailure(@Nonnull Throwable exc) { result.failure(new OvsdbException(client, exc)); } }; Futures.addCallback(transaction.execute(), cb, callingThreadExecutor); return result; }
Source:
<code>public void run() { connectionTimeout = config.getConnectionTimeout(); poolElf.setValidationTimeout(config.getValidationTimeout()); leakTask.updateLeakDetectionThreshold(config.getLeakDetectionThreshold()); final long now = clockSource.currentTime(); final long idleTimeout = config.getIdleTimeout(); if (now < previous || now > clockSource.plusMillis(previous, (2 * HOUSEKEEPING_PERIOD_MS))) { LOGGER.warn("{} - Unusual system clock change detected, soft-evicting connections from pool.", poolName); previous = now; softEvictConnections(); fillPool(); return; } previous = now; if (idleTimeout > 0L) { logPoolState("Before cleanup\t"); final List<PoolBagEntry> bag = connectionBag.values(STATE_NOT_IN_USE); <START> final int bagSize = bag.size(); <END> int removable = bagSize - config.getMinimumIdle(); for (int i = 0; i < bagSize; i++) { if (removable <= 0) { break; } final PoolBagEntry bagEntry = bag.get(i); if (clockSource.elapsedMillis(bagEntry.lastAccess, now) > idleTimeout) { if (connectionBag.reserve(bagEntry)) { closeConnection(bagEntry, "(connection passed idleTimeout)"); removable--; } } } logPoolState("After cleanup\t"); } fillPool(); }</code><technical_language>of JIT optimizations, iterator form of for is [faster](<LINK_0></technical_language>

Target:
public void run() { connectionTimeout = config.getConnectionTimeout(); leakTask.updateLeakDetectionThreshold(config.getLeakDetectionThreshold()); final long now = clockSource.currentTime(); final long idleTimeout = config.getIdleTimeout(); if (now < previous || now > clockSource.plusMillis(previous, (2 * HOUSEKEEPING_PERIOD_MS))) { LOGGER.warn("{} - Unusual system clock change detected, soft-evicting connections from pool.", poolName); previous = now; softEvictConnections(); fillPool(); return; } previous = now; if (idleTimeout > 0L) { logPoolState("Before cleanup\t"); final List<PoolEntry> notInUseList = connectionBag.values(STATE_NOT_IN_USE); int removable = notInUseList.size() - config.getMinimumIdle(); for (PoolEntry poolEntry : notInUseList) { if (removable <= 0) { break; } if (clockSource.elapsedMillis(poolEntry.lastAccess, now) > idleTimeout) { if (connectionBag.reserve(poolEntry)) { closeConnection(poolEntry, "(connection passed idleTimeout)"); removable--; } } } logPoolState("After cleanup\t"); } fillPool(); }
Source:
<code>@Override public void run() { ExecutorService heartbeat = null; try { setStopped( false ); setFinished( false ); setInitialized( true ); variables.initializeVariablesFrom( parentJob ); setInternalKettleVariables( variables ); copyParametersFrom( jobMeta ); activateParameters(); fireJobStartListeners(); heartbeat = startHeartbeat( getHeartbeatIntervalInSeconds() ); result = execute(); } catch ( Throwable je ) { log.logError( BaseMessages.getString( PKG, "Job.Log.ErrorExecJob", je.getMessage() ), je ); result = new Result(); result.setNrErrors( 1L ); result.setResult( false ); addErrors( 1 ); emergencyWriteJobTracker( result ); setActive( false ); setFinished( true ); setStopped( false ); } finally { try { shutdownHeartbeat( heartbeat ); ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.JobFinish.id, this ); jobMeta.disposeEmbeddedMetastoreProvider(); <START> log.logDebug( "EmbeddedMetastore objects has been disposed." ); <END> fireJobFinishListeners(); KettleVFS.freeUnusedResources(); } catch ( KettleException e ) { result.setNrErrors( 1 ); result.setResult( false ); log.logError( BaseMessages.getString( PKG, "Job.Log.ErrorExecJob", e.getMessage() ), e ); emergencyWriteJobTracker( result ); } } }</code><technical_language>Typo in log message. _have been_. place this message in a resources file? UX sign this message</technical_language>

Target:
@Override public void run() { ExecutorService heartbeat = null; try { setStopped( false ); setFinished( false ); setInitialized( true ); variables.initializeVariablesFrom( parentJob ); setInternalKettleVariables( variables ); copyParametersFrom( jobMeta ); activateParameters(); fireJobStartListeners(); heartbeat = startHeartbeat( getHeartbeatIntervalInSeconds() ); result = execute(); } catch ( Throwable je ) { log.logError( BaseMessages.getString( PKG, "Job.Log.ErrorExecJob", je.getMessage() ), je ); result = new Result(); result.setNrErrors( 1L ); result.setResult( false ); addErrors( 1 ); emergencyWriteJobTracker( result ); setActive( false ); setFinished( true ); setStopped( false ); } finally { try { shutdownHeartbeat( heartbeat ); ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.JobFinish.id, this ); jobMeta.disposeEmbeddedMetastoreProvider(); log.logDebug( BaseMessages.getString( PKG, "Job.Log.DisposeEmbeddedMetastore" ) ); fireJobFinishListeners(); KettleVFS.freeUnusedResources(); } catch ( KettleException e ) { result.setNrErrors( 1 ); result.setResult( false ); log.logError( BaseMessages.getString( PKG, "Job.Log.ErrorExecJob", e.getMessage() ), e ); emergencyWriteJobTracker( result ); } } }
Source:
<code>public FieldPose(XYPair point, ContiguousHeading heading) { m = degreesToSlope(heading.getValue()); this.fieldPosition = point; this.heading = heading; <START> if ((point.x == 0) || (Math.abs(m) < 0.01)) { <END> b = point.y; } else { b = point.y / (point.x * m); } }</code><technical_language>benefit of storing this a line w/ slope instead of angle? "robot pose" is a line notion of a heading added on... is a simpler of this, I understand this logic is doing</technical_language>

Target:
public FieldPose(XYPair point, ContiguousHeading heading) { m = degreesToSlope(heading.getValue()); this.fieldPosition = point.clone(); this.heading = heading.clone(); if ((point.x == 0) || (Math.abs(m) < 0.01)) { b = point.y; } else { b = point.y - (point.x * m); } }
Source:
<code>public void setup() { factory = ResteasyProviderFactory.newInstance(); <START> ResteasyProviderFactory.setInstance(factory); <END> }</code><technical_language>I _RegisterBuiltin.register(factory);_ executed, in order a provider factory behaves expected way. WDYT? (this applies similar code blocks in this PR)</technical_language>

Target:
public void setup() { factory = ResteasyProviderFactory.newInstance(); ResteasyProviderFactory.setInstance(factory); RegisterBuiltin.register(factory); }
Source:
<code>protected void performWorkload(BaseSubscriber<CosmosAsyncItemResponse> baseSubscriber, long i) throws InterruptedException { String partitionKey = uuid + i; Mono<CosmosAsyncItemResponse<PojoizedJson>> obs; if (configuration.isDisablePassingPartitionKeyAsOptionOnWrite()) { obs = cosmosAsyncContainer.createItem(generateDocument(partitionKey, dataFieldValue)); } else { <START> obs = cosmosAsyncContainer.createItem(generateDocument(partitionKey, dataFieldValue), new CosmosItemRequestOptions()); <END> } concurrencyControlSemaphore.acquire(); if (configuration.getOperationType() == Configuration.Operation.WriteThroughput) { obs.subscribeOn(Schedulers.parallel()).subscribe(baseSubscriber); } else { LatencySubscriber<CosmosAsyncItemResponse> latencySubscriber = new LatencySubscriber<>(baseSubscriber); latencySubscriber.context = latency.time(); obs.subscribeOn(Schedulers.parallel()).subscribe(latencySubscriber); } }</code><technical_language>pass partition key CosmosItemRequestOption here. intention of this benchmark is measure perf pk is passed request options</technical_language>

Target:
protected void performWorkload(BaseSubscriber<CosmosAsyncItemResponse> baseSubscriber, long i) throws InterruptedException { String partitionKey = uuid + i; Mono<CosmosAsyncItemResponse<PojoizedJson>> obs; if (configuration.isDisablePassingPartitionKeyAsOptionOnWrite()) { obs = cosmosAsyncContainer.createItem(generateDocument(partitionKey, dataFieldValue)); } else { obs = cosmosAsyncContainer.createItem(generateDocument(partitionKey, dataFieldValue), new PartitionKey(partitionKey), new CosmosItemRequestOptions()); } concurrencyControlSemaphore.acquire(); if (configuration.getOperationType() == Configuration.Operation.WriteThroughput) { obs.subscribeOn(Schedulers.parallel()).subscribe(baseSubscriber); } else { LatencySubscriber<CosmosAsyncItemResponse> latencySubscriber = new LatencySubscriber<>(baseSubscriber); latencySubscriber.context = latency.time(); obs.subscribeOn(Schedulers.parallel()).subscribe(latencySubscriber); } }
Source:
<code>static DownloadType fromString(final String type) { if (type.equalsIgnoreCase(MAP_SKIN.name())) { return MAP_SKIN; } else if (type.equalsIgnoreCase(MAP_TOOL.name())) { return MAP_TOOL; } else { return MAP; <START> } <END> }</code><technical_language>of construct? java try { return DownloadType.valueOf(type); } catch (final IllegalArgumentException e) { return MAP; } current code (case-sensitive), a bit cleaner a lot of if-else cases chained</technical_language>

Target:
private static DownloadType fromString(final String type) { if (type.equalsIgnoreCase(MAP_SKIN.name())) { return MAP_SKIN; } else if (type.equalsIgnoreCase(MAP_TOOL.name())) { return MAP_TOOL; } else { return MAP; } }
Source:
<code>protected List<QuestionDto> parseQuestions(String response) throws Exception { final ObjectMapper JSON_RESPONSE_PARSER = new ObjectMapper(); List<QuestionDto> dtoList = new ArrayList<QuestionDto>(); final JsonNode questionListNode = JSON_RESPONSE_PARSER.readTree(response).get("dtoList"); final List<QuestionDto> qList = JSON_RESPONSE_PARSER.readValue( questionListNode, new TypeReference<List<QuestionDto>>() { }); <START> dtoList.addAll(qList); END> return dtoList; }</code><technical_language>Returning qListhere enough, qList is null</technical_language>

Target:
protected List<QuestionDto> parseQuestions(String response) throws Exception { final ObjectMapper JSON_RESPONSE_PARSER = new ObjectMapper(); final JsonNode questionListNode = JSON_RESPONSE_PARSER.readTree(response).get("dtoList"); final List<QuestionDto> qList = JSON_RESPONSE_PARSER.readValue( questionListNode, new TypeReference<List<QuestionDto>>() { }); return qList; }
Source:
<code>public CompletableFuture<CacheEntry<K, V>> getCacheEntryAsync(Object key) { <START> return asyncGet(key); <END> }</code><technical_language>inline</technical_language>

Target:
public CompletableFuture<CacheEntry<K, V>> getCacheEntryAsync(Object key) { int segment = keyPartitioner.getSegment(key); InternalCacheEntry<K, V> ice = internalPeekCacheEntry(key, segment); if (ice == null) { return CompletableFutures.completedNull(); } if (ice.canExpire()) { CompletionStage<Boolean> stage = expirationManager.handlePossibleExpiration(ice, segment, false); if (CompletionStages.isCompletedSuccessfully(stage)) { if (CompletionStages.join(stage)) { return CompletableFutures.completedNull(); } return CompletableFuture.completedFuture(ice); } else { return stage.thenApply(expired -> { if (expired == Boolean.TRUE) { return null; } return (CacheEntry<K, V>) ice; }).toCompletableFuture(); } } return CompletableFuture.completedFuture(ice); }
Source:
<code>public HmRqTextBody(final String expected) { <START> this(Matchers.containsString(expected)); <END> }</code><technical_language>@t-izbassar I clear, default matcher in Hamcrest library is Matchers.equalTo(), a user of HmRqTextBody expect body is equal constructor parameter string</technical_language>

Target:
public HmRqTextBody(final String expected) { this(Matchers.equalTo(expected)); }
Source:
<code>public VisualEditorPageObject selectInfoboxTemplate(int i) { WebElement element = infoboxTemplatesList.get(i); wait.forElementClickable(element); <START> element.click(); <END> return this; }</code><technical_language>add more descriptive name instead of element? templateName, templateElement template</technical_language>

Target:
public VisualEditorPageObject selectInfoboxTemplate(int i) { WebElement template = infoboxTemplatesList.get(i); wait.forElementClickable(template); template.click(); return this; }
Source:
<code>public void join() { Assert.assertEquals("foo,bar,baz", StringHelper.join(",", new String[]{"foo", "bar", "baz"})); Assert.assertEquals("foobarbaz", StringHelper.join(null, new String[]{"foo", "bar", "baz"})); Assert.assertEquals("foo,,bar", StringHelper.join(",", new String[]{"foo", null, "bar"})); <START> Assert.assertNull(StringHelper.join(null, null)); <END> }</code><technical_language>change static import</technical_language>

Target:
public void join() { assertEquals("foo,bar,baz", StringHelper.join(",", new String[]{"foo", "bar", "baz"})); assertEquals("foobarbaz", StringHelper.join(null, new String[]{"foo", "bar", "baz"})); assertEquals("foo,,bar", StringHelper.join(",", new String[]{"foo", null, "bar"})); assertNull(StringHelper.join(null, null)); }
Source:
<code>public void setUp() { when(model.listHosts()).thenReturn(hosts); final HostStatus.Builder statusBuilder = HostStatus.newBuilder() .setStatus(HostStatus.Status.UP) .setJobs(emptyMap()) .setStatuses(emptyMap()); int i = 1; for (final String host : hosts) { final Map<String, String> labels = new HashMap<>(); labels.put("site", "foo"); labels.put("index", String.valueOf(i++)); final HostStatus hostStatus = statusBuilder .setLabels(labels) .build(); <START> when(model.getHostStatus(host)).thenReturn(hostStatus); <END> when(model.getHostLabels(host)).thenReturn(labels); } }</code><technical_language>getHostStatus(host) called anymore, do need when()? removing this catches case is called unexpectedly</technical_language>

Target:
public void setUp() { when(model.listHosts()).thenReturn(hosts); final HostStatus.Builder statusBuilder = HostStatus.newBuilder() .setStatus(HostStatus.Status.UP) .setJobs(emptyMap()) .setStatuses(emptyMap()); int i = 1; for (final String host : hosts) { final Map<String, String> labels = new HashMap<>(); labels.put("site", "foo"); labels.put("index", String.valueOf(i++)); final HostStatus hostStatus = statusBuilder .setLabels(labels) .build(); when(model.getHostLabels(host)).thenReturn(labels); } }
Source:
<code>public void globalVerify() throws Exception { <START> IList<MapReduceCounter> results = targetInstance.getList(basename); <END> MapReduceCounter total = new MapReduceCounter(); for (MapReduceCounter i : results) { total.add(i); } log.info(basename + ": " + total + " from " + results.size() + " worker Threads"); }</code><technical_language>run a problem if basename; imagine multiple map reduce tests running in parallel. I suggest pulling out results lists setup method, getList is done there. list is needed, access results list directly</technical_language>

Target:
public void globalVerify() throws Exception { IList<Counter> results = targetInstance.getList(baseName); Counter total = new Counter(); for (Counter i : results) { total.add(i); } log.info(baseName + ": " + total + " from " + results.size() + " worker Threads"); }
Source:
<code>private String getInstanceClass( final Tuple resultset, final int i, final Loadable persister, final Serializable id, final SessionImplementor session) throws HibernateException { <START> if ( persister.hasSubclasses() ) { <END> final String result = getInstanceClassFromDiscriminator( resultset, persister ); if ( result == null ) { throw new WrongClassException( "Discriminator: " + discriminatorValue( resultset, persister ), id, persister.getEntityName() ); } return result; } return persister.getEntityName(); }</code><technical_language>hasSubclasses is true in SINGLE_TABLE case? I understand this commit is related "table class hierarchies" fix for them. explain me</technical_language>

Target:
private String getInstanceClass( final Tuple resultset, final int i, final Loadable persister, final Serializable id, final SessionImplementor session) throws HibernateException { String discriminatorColumnName = persister.getDiscriminatorColumnName(); if ( discriminatorColumnName == null ) { return persister.getEntityName(); } else { Object value = resultset.get( discriminatorColumnName ); return persister.getSubclassForDiscriminatorValue( value ); } }
Source:
<code>public Artifact adapt(Attribute<?> attribute, Id identity) throws OseeCoreException { Artifact resultArtifact = AtsClientService.get().getArtifact(identity.getId()); if (resultArtifact == null) { int uuid = identity.getId() <= 0 ? 0 : identity.getId().intValue(); <START> if (uuid > 0) { <END> resultArtifact = ArtifactQuery.getArtifactFromId(uuid, AtsClientService.get().getAtsBranch()); } } return resultArtifact; }</code><technical_language>update this if statement identity.isValid()</technical_language>

Target:
public Artifact adapt(Attribute<?> attribute, Id identity) throws OseeCoreException { Artifact resultArtifact = AtsClientService.get().getArtifact(identity.getId()); if (resultArtifact == null) { if (identity.isValid()) { resultArtifact = ArtifactQuery.getArtifactFromId(identity.getId(), AtsClientService.get().getAtsBranch()); } } return resultArtifact; }
Source:
<code>public void stop() { if (!eventReceived) { log.warn("Events did not received."); } try { thriftDataReceiver.stop(); log.info("Test Server Stopped."); <START> } catch (Throwable t) { <END> t.printStackTrace(); } }</code><technical_language>also, exceptions thrown, handle bottom of call stack</technical_language>

Target:
public void stop() { if (!eventReceived) { log.warn("Events did not received."); } thriftDataReceiver.stop(); log.info("Test Server Stopped."); }
Source:
<code>private Object lookUp(Class<?> type) { if (type==Jenkins.class || type==Hudson.class) return Jenkins.getInstance(); Jenkins j = Jenkins.getInstance(); <START> if (j!=null) { <END> Injector i = j.getInjector(); if (i!=null) return i.getInstance(type); } throw new IllegalArgumentException("Unable to inject "+type); }</code><technical_language>invocation replaced, checking for null. presence in init package I suspect getInstanceOrNull is correct in invocations</technical_language>

Target:
private Object lookUp(Class<?> type) { Jenkins j = Jenkins.getInstance(); assert j != null : "This method is only invoked after the Jenkins singleton instance has been set"; if (type==Jenkins.class || type==Hudson.class) return j; Injector i = j.getInjector(); if (i!=null) return i.getInstance(type); throw new IllegalArgumentException("Unable to inject "+type); }
Source:
<code>public void putIfAbsent(BufferNode bufferNode) { <START> if (pendingBufferNode.putIfAbsent(bufferNode, bufferNode) == null) { <END> bufferNode.setTimeout(EnvironmentEdgeManager.currentTime() + operationDelay); queue.add(bufferNode); } }</code><technical_language>If want add object key value, ConcurrentHashMap instead of Sets.newConcurrentHashSet()</technical_language>

Target:
private void putIfAbsent(BufferNode bufferNode) { if (pendingBufferNode.putIfAbsent(bufferNode, bufferNode) == null) { bufferNode.setTimeout(EnvironmentEdgeManager.currentTime() + operationDelay); queue.add(bufferNode); } }
Source:
<code>public void setUp() { try { RedisServer redisServer = new RedisServer(PORT); redisServer.start(); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(10); pool = new JedisPool(jedisPoolConfig, HOST, PORT); makeData(); <START> System.out.println("The redis server is start! host:" + HOST + " port:" + PORT); <END> } catch (Exception e) { assertNotNull(e.getMessage()); } }</code><technical_language>redis server is started host:</technical_language>

Target:
public void setUp() { try { RedisServer redisServer = new RedisServer(PORT); redisServer.start(); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(10); pool = new JedisPool(jedisPoolConfig, HOST, PORT); makeData(); System.out.println("The redis server is started at host: " + HOST + " port: " + PORT); } catch (Exception e) { assertNotNull(e.getMessage()); } }
Source:
<code>public void setParams(Object[] params) { if (params.length != 1) { throw new IllegalArgumentException("expecting one parameter"); } <START> setParams((Map<Object, Number>) params[0]); <END> }</code><technical_language>Please Map<?,?></technical_language>

Target:
public void setParams(Object[] params) { if (params.length != 1) { throw new IllegalArgumentException("expecting one parameter"); } setParams((Map<?, ?>) params[0]); }
Source:
<code>public void testRcAndTextFormats() throws IOException { try { <START> getQueryRunner().execute("CREATE TABLE IF NOT EXISTS lineitem_partition WITH (format='ORC', partitioned_by=ARRAY['ds']) AS " + <END> "SELECT linenumber, orderkey, partkey, suppkey, quantity, extendedprice, tax, shipinstruct, shipmode, ship_by_air, " + "is_returned, ship_day, ship_month, ship_timestamp, commit_timestamp, discount_real, discount, tax_real, ship_day_month, " + "discount_long_decimal, tax_short_decimal, long_decimals, keys, doubles, nested_keys, flags, reals, info, dates, timestamps, " + "comment, uppercase_comment, fixed_comment, char_array, varchar_array,'2019-11-01' AS ds FROM lineitem_ex"); for (HiveStorageFormat format : ImmutableList.of(RCBINARY, RCTEXT, TEXTFILE)) { assertFileFormat(format); } } finally { assertUpdate("DROP TABLE lineitem_partition"); } }</code><technical_language>remove IF EXISTS - move this statement of try block; otherwise, if CREATE TABLE fails, DROP TABLE in finally block fail</technical_language>

Target:
public void testRcAndTextFormats() throws IOException { getQueryRunner().execute("CREATE TABLE lineitem_ex_partitioned WITH (format = 'ORC', partitioned_by = ARRAY['ds']) AS\n" + "SELECT\n" + " linenumber,\n" + " orderkey,\n" + " partkey,\n" + " suppkey,\n" + " quantity,\n" + " extendedprice,\n" + " tax,\n" + " shipinstruct,\n" + " shipmode,\n" + " ship_by_air,\n" + " is_returned,\n" + " ship_day,\n" + " ship_month,\n" + " ship_timestamp,\n" + " commit_timestamp,\n" + " discount_real,\n" + " discount,\n" + " tax_real,\n" + " ship_day_month,\n" + " discount_long_decimal,\n" + " tax_short_decimal,\n" + " long_decimals,\n" + " keys,\n" + " doubles,\n" + " nested_keys,\n" + " flags,\n" + " reals,\n" + " info,\n" + " dates,\n" + " timestamps,\n" + " comment,\n" + " uppercase_comment,\n" + " fixed_comment,\n" + " char_array,\n" + " varchar_array,\n" + " '2019-11-01' AS ds\n" + "FROM lineitem_ex"); try { for (HiveStorageFormat format : ImmutableList.of(RCBINARY, RCTEXT, TEXTFILE)) { assertFileFormat(format); } } finally { assertUpdate("DROP TABLE lineitem_ex_partitioned"); } }
Source:
<code>public Intent getIntentForBrokerActivity(final AuthenticationRequest request) { Intent intent = null; AccountManagerFuture<Bundle> result = null; try { Bundle addAccountOptions = getBrokerOptions(request); result = mAcctManager.addAccount(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE, AuthenticationConstants.Broker.AUTHTOKEN_TYPE, null, addAccountOptions, null, null, mHandler); Bundle bundleResult = result.getResult(); intent = bundleResult.getParcelable(AccountManager.KEY_INTENT); if (intent != null) { intent.putExtra(AuthenticationConstants.Broker.BROKER_REQUEST, AuthenticationConstants.Broker.BROKER_REQUEST); } } catch (OperationCanceledException e) { Logger.e(TAG, "Authenticator cancels the request", "", ADALError.AUTH_FAILED_CANCELLED, e); } catch (AuthenticatorException e) { <START> Logger.e(TAG, "Authenticator cancels the request", "", ADALError.BROKER_AUTHENTICATOR_NOT_RESPONDING); <END> } catch (IOException e) { Logger.e(TAG, "Authenticator cancels the request", "", ADALError.BROKER_AUTHENTICATOR_IO_EXCEPTION); } return intent; }</code><technical_language>log exception</technical_language>

Target:
public Intent getIntentForBrokerActivity(final AuthenticationRequest request) { Intent intent = null; AccountManagerFuture<Bundle> result = null; try { Bundle addAccountOptions = getBrokerOptions(request); result = mAcctManager.addAccount(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE, AuthenticationConstants.Broker.AUTHTOKEN_TYPE, null, addAccountOptions, null, null, mHandler); Bundle bundleResult = result.getResult(); intent = bundleResult.getParcelable(AccountManager.KEY_INTENT); if (intent != null) { intent.putExtra(AuthenticationConstants.Broker.BROKER_REQUEST, AuthenticationConstants.Broker.BROKER_REQUEST); } } catch (OperationCanceledException e) { Logger.e(TAG, "Authenticator cancels the request", "", ADALError.AUTH_FAILED_CANCELLED, e); } catch (AuthenticatorException e) { Logger.e(TAG, "Authenticator cancels the request", "", ADALError.BROKER_AUTHENTICATOR_NOT_RESPONDING, e); } catch (IOException e) { Logger.e(TAG, "Authenticator cancels the request", "", ADALError.BROKER_AUTHENTICATOR_IO_EXCEPTION, e); } return intent; }
Source:
<code>public void run() { if (isDisposing) { return; } if (validationIcon == null || validationIcon.isDisposed()) { return; } if (getVElement().getDiagnostic() == null) { return; } final VTableDomainModelReference tableDMR = (VTableDomainModelReference) getVElement() .getDomainModelReference(); Optional<Setting> setting; if (tableDMR.getDomainModelReference() != null) { setting = getSettingFromObservable(tableDMR.getDomainModelReference(), getViewModelContext().getDomainModel()); } else { setting = getSettingFromObservable(tableDMR, getViewModelContext().getDomainModel()); } validationIcon.setImage(getValidationIcon(getVElement().getDiagnostic().getHighestSeverity())); showValidationSummaryTooltip(showValidationSummaryTooltip); <START> final Collection<?> collection = (Collection<?>) setting.get().get(true); <END> if (!collection.isEmpty()) { for (final Object object : collection) { getTableViewer().update(object, null); } } }</code><technical_language>if optional is empty</technical_language>

Target:
public void run() { if (isDisposing) { return; } if (validationIcon == null || validationIcon.isDisposed()) { return; } if (getVElement().getDiagnostic() == null) { return; } final VTableDomainModelReference tableDMR = (VTableDomainModelReference) getVElement() .getDomainModelReference(); Optional<Setting> setting; if (tableDMR.getDomainModelReference() != null) { setting = getSettingFromObservable(tableDMR.getDomainModelReference(), getViewModelContext().getDomainModel()); } else { setting = getSettingFromObservable(tableDMR, getViewModelContext().getDomainModel()); } if (setting.isPresent()) { return; } validationIcon.setImage(getValidationIcon(getVElement().getDiagnostic().getHighestSeverity())); showValidationSummaryTooltip(showValidationSummaryTooltip); final Collection<?> collection = (Collection<?>) setting.get().get(true); if (!collection.isEmpty()) { for (final Object object : collection) { getTableViewer().update(object, null); } } }
Source:
<code>void updateTokenCacheUsingCommonCache(final AuthenticationRequest request, final AuthenticationResult result) throws MalformedURLException { AzureActiveDirectory ad = new AzureActiveDirectory(); AzureActiveDirectoryTokenResponse tokenResponse = CoreAdapter.asAadTokenResponse(result); AzureActiveDirectoryOAuth2Configuration config = new AzureActiveDirectoryOAuth2Configuration(); config.setAuthorityHostValidationEnabled(this.isValidateAuthorityHost()); AzureActiveDirectoryOAuth2Strategy strategy = ad.createOAuth2Strategy(config); AzureActiveDirectoryAuthorizationRequest aadAuthRequest = new AzureActiveDirectoryAuthorizationRequest.Builder( <START> request.getClientId(), <END> request.getRedirectUri(), new URL(mAuthority), request.getResource()) .build(); mCommonCache.save(strategy, aadAuthRequest, tokenResponse); }</code><technical_language>#1307</technical_language>

Target:
void updateTokenCacheUsingCommonCache(final AuthenticationRequest request, final AuthenticationResult result) throws MalformedURLException { AzureActiveDirectory ad = new AzureActiveDirectory(); AzureActiveDirectoryTokenResponse tokenResponse = CoreAdapter.asAadTokenResponse(result); AzureActiveDirectoryOAuth2Configuration config = new AzureActiveDirectoryOAuth2Configuration(); config.setAuthorityHostValidationEnabled(this.isValidateAuthorityHost()); AzureActiveDirectoryOAuth2Strategy strategy = ad.createOAuth2Strategy(config); AzureActiveDirectoryAuthorizationRequest aadAuthRequest = new AzureActiveDirectoryAuthorizationRequest.Builder() .setClientId(request.getClientId()) .setResource(request.getResource()) .setScope(request.getResource()) .setAuthority(new URL(mAuthority)) .setRedirectUri(request.getRedirectUri()) .setLoginHint(request.getLoginHint()) .setCorrelationId(request.getCorrelationId()) .build(); mCommonCache.save(strategy, aadAuthRequest, tokenResponse); }
Source:
<code>public Map<Integer,Error> commit() { Map<Integer,Error> results=new HashMap<>(); if(!batch.isEmpty()) { BulkWriteResult writeResult; LOGGER.debug("attemptToUpdate={}",batch.size()); try { if(writeConcern==null) { writeResult=bwo.execute(); } else { writeResult=bwo.execute(writeConcern); } LOGGER.debug("writeResult={}",writeResult); if(batch.size()==writeResult.getMatchedCount()) { LOGGER.debug("Successful update"); } else { LOGGER.debug("notUpdated={}",batch.size()-writeResult.getMatchedCount()); findConcurrentModifications(results); } } catch (BulkWriteException e) { List<BulkWriteError> writeErrors=e.getWriteErrors(); if(writeErrors!=null) { for(BulkWriteError we:writeErrors) { if (MongoCrudConstants.isDuplicate(we.getCode())) { results.put(we.getIndex(), Error.get("update", MongoCrudConstants.ERR_DUPLICATE, we.getMessage())); } else { results.put(we.getIndex(), Error.get("update", MongoCrudConstants.ERR_SAVE_ERROR, we.getMessage())); } } } findConcurrentModifications(results); } } <START> retry(results); <END> reset(); return results; }</code><technical_language>minor, I call this method "retryIfNeeded" "retryIfConcurrentUpdate"</technical_language>

Target:
public Map<Integer,Error> commit() { Map<Integer,Error> results=new HashMap<>(); if(!batch.isEmpty()) { BulkWriteResult writeResult; LOGGER.debug("attemptToUpdate={}",batch.size()); try { if(writeConcern==null) { writeResult=bwo.execute(); } else { writeResult=bwo.execute(writeConcern); } LOGGER.debug("writeResult={}",writeResult); if(batch.size()==writeResult.getMatchedCount()) { LOGGER.debug("Successful update"); } else { LOGGER.warn("notUpdated={}",batch.size()-writeResult.getMatchedCount()); findConcurrentModifications(results); } } catch (BulkWriteException e) { List<BulkWriteError> writeErrors=e.getWriteErrors(); if(writeErrors!=null) { for(BulkWriteError we:writeErrors) { if (MongoCrudConstants.isDuplicate(we.getCode())) { results.put(we.getIndex(), Error.get("update", MongoCrudConstants.ERR_DUPLICATE, we.getMessage())); } else { results.put(we.getIndex(), Error.get("update", MongoCrudConstants.ERR_SAVE_ERROR, we.getMessage())); } } } findConcurrentModifications(results); } } retryConcurrentUpdateErrorsIfNeeded(results); reset(); return results; }
Source:
<code>public void testSubstrSetScanKey() throws Exception { String query = "SELECT inst FROM ptsdb WHERE substr(inst, 0, 3) = 'abc'"; List<Object> binds = Collections.emptyList(); Scan scan = new Scan(); compileQuery(query, binds, scan); assertTrue(Bytes.compareTo(Bytes.toBytes("abc"), scan.getStartRow()) == 0); <START> assertTrue(Bytes.compareTo(Bytes.toBytes("abc\1"), scan.getStopRow()) == 0); <END> assertTrue(scan.getFilter() != null); }</code><technical_language>\1 byte end here? abd, no</technical_language>

Target:
public void testSubstrSetScanKey() throws Exception { String query = "SELECT inst FROM ptsdb WHERE substr(inst, 0, 3) = 'abc'"; List<Object> binds = Collections.emptyList(); Scan scan = new Scan(); compileQuery(query, binds, scan); assertTrue(Bytes.compareTo(Bytes.toBytes("abc"), scan.getStartRow()) == 0); assertTrue(Bytes.compareTo(Bytes.toBytes("abd"), scan.getStopRow()) == 0); assertTrue(scan.getFilter() == null); }
Source:
<code>public StorageQosMetricParametersModel(ConfigurationValues maxTotal, ConfigurationValues maxRead, ConfigurationValues maxWrite) { this.maxTotal = maxTotal; this.maxRead = maxRead; this.maxWrite = maxWrite; setTotal(new EntityModel<Integer>()); setRead(new EntityModel<Integer>()); setWrite(new EntityModel<Integer>()); setChoiceGroupNone(new EntityModel<Boolean>()); setChoiceGroupTotal(new EntityModel<Boolean>()); setChoiceGroupReadWrite(new EntityModel<Boolean>()); getChoiceGroupNone().getEntityChangedEvent().addListener(this); getChoiceGroupTotal().getEntityChangedEvent().addListener(this); getChoiceGroupReadWrite().getEntityChangedEvent().addListener(this); <START> getPropertyChangedEvent().addListener(this); <END> }</code><technical_language>needed, registered 3 events</technical_language>

Target:
public StorageQosMetricParametersModel(ConfigurationValues maxTotal, ConfigurationValues maxRead, ConfigurationValues maxWrite) { this.maxTotal = maxTotal; this.maxRead = maxRead; this.maxWrite = maxWrite; setTotal(new EntityModel<Integer>()); setRead(new EntityModel<Integer>()); setWrite(new EntityModel<Integer>()); setChoiceGroupNone(new EntityModel<Boolean>()); setChoiceGroupTotal(new EntityModel<Boolean>()); setChoiceGroupReadWrite(new EntityModel<Boolean>()); getChoiceGroupNone().getEntityChangedEvent().addListener(this); getChoiceGroupTotal().getEntityChangedEvent().addListener(this); getChoiceGroupReadWrite().getEntityChangedEvent().addListener(this); }
Source:
<code>private void addHintText() { String s = null; try { s = mPrompt.getHintText(); } catch (XPathException e) { UserfacingErrorHandling.createErrorDialog((CommCareActivity)getContext(), e.getLocalizedMessage(), true); <START> } catch (Exception e) { <END> Logger.exception(TAG + ".addHintText", e); e.printStackTrace(); } if (s != null && !s.equals("")) { mHintText = new ShrinkingTextView(getContext(), this.getMaxHintHeight()); mHintText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontSize - 3); mHintText.setPadding(0, -5, 0, 7); mHintText.setHorizontallyScrolling(false); mHintText.setText(s); mHintText.setTypeface(null, Typeface.ITALIC); addView(mHintText, mLayout); } }</code><technical_language>remove</technical_language>

Target:
private void addHintText() { String s = null; try { s = mPrompt.getHintText(); } catch (XPathException e) { UserfacingErrorHandling.createErrorDialog((CommCareActivity)getContext(), e.getLocalizedMessage(), true); } if (s != null && !s.equals("")) { mHintText = new ShrinkingTextView(getContext(), this.getMaxHintHeight()); mHintText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontSize - 3); mHintText.setPadding(0, -5, 0, 7); mHintText.setHorizontallyScrolling(false); mHintText.setText(s); mHintText.setTypeface(null, Typeface.ITALIC); addView(mHintText, mLayout); } }
Source:
<code>public void migrate( File storeDir, File migrationDir, MigrationProgressMonitor.Section progressMonitor, String versionToMigrateFrom, String versionToMigrateTo ) throws IOException { if ( countStoreRebuildRequired( versionToMigrateFrom ) ) { StoreFile.fileOperation( DELETE, fileSystem, migrationDir, migrationDir, COUNTS_STORE_FILES, true, null, StoreFileType.STORE ); File neoStore = new File( storeDir, DEFAULT_NAME ); long lastTxId = MetaDataStore.getRecord( pageCache, neoStore, Position.LAST_TRANSACTION_ID ); try { rebuildCountsFromScratch( migrationDir, migrationDir, lastTxId, progressMonitor, versionToMigrateTo, pageCache, NullLogProvider.getInstance() ); } catch ( StoreFailureException e ) { rebuildCountsFromScratch( storeDir, migrationDir, lastTxId, progressMonitor, versionToMigrateFrom, <START> pageCache, logService.getInternalLogProvider() ); <END> } } }</code><technical_language>do pass real log provider here. For example situation: migration 3.2 3.3 need do count store migration. result, do do store copy invocation rebuildCountsFromScratch fail store is try migrate count store user format exceptions still</technical_language>

Target:
public void migrate( File storeDir, File migrationDir, MigrationProgressMonitor.Section progressMonitor, String versionToMigrateFrom, String versionToMigrateTo ) throws IOException { if ( countStoreRebuildRequired( versionToMigrateFrom ) ) { StoreFile.fileOperation( DELETE, fileSystem, migrationDir, migrationDir, COUNTS_STORE_FILES, true, null, StoreFileType.STORE ); File neoStore = new File( storeDir, DEFAULT_NAME ); long lastTxId = MetaDataStore.getRecord( pageCache, neoStore, Position.LAST_TRANSACTION_ID ); try { rebuildCountsFromScratch( migrationDir, migrationDir, lastTxId, progressMonitor, versionToMigrateTo, pageCache, NullLogProvider.getInstance() ); } catch ( StoreFailureException e ) { rebuildCountsFromScratch( storeDir, migrationDir, lastTxId, progressMonitor, versionToMigrateFrom, pageCache, NullLogProvider.getInstance() ); } } }
Source:
<code>public GCSAvroOutputFormatProvider(GCSAvroSinkConfig config, BatchSinkContext context) { <START> conf = Maps.newHashMap(); <END> conf.put(JobContext.OUTPUT_KEY_CLASS, AvroKey.class.getName()); conf.put("avro.schema.output.key", config.schema); conf.put(FileOutputFormat.OUTDIR, String.format("gs://%s/%s", config.bucketKey, config.path)); }</code><technical_language>new HashMap<>();</technical_language>

Target:
public GCSAvroOutputFormatProvider(GCSAvroSinkConfig config, BatchSinkContext context) { conf = new HashMap<>(); conf.put(JobContext.OUTPUT_KEY_CLASS, AvroKey.class.getName()); conf.put("avro.schema.output.key", config.schema); conf.put(FileOutputFormat.OUTDIR, String.format("gs://%s/%s", config.bucketKey, config.path)); }
Source:
<code>private void replaceAntiCsrfTokenValueIfRequired(HttpMessage requestMessage, User user) throws IOException { if(extAntiCsrf == null) { extAntiCsrf = Control.getSingleton().getExtensionLoader().getExtension(ExtensionAntiCSRF.class); } List<AntiCsrfToken> antiCsrfTokensOfFirstLoginMsg = null; if(extAntiCsrf != null) { antiCsrfTokensOfFirstLoginMsg = extAntiCsrf.getTokens(requestMessage); } AntiCsrfToken antiCsrfTokenOfFirstLoginMsg = null; if(antiCsrfTokensOfFirstLoginMsg != null && antiCsrfTokensOfFirstLoginMsg.size() > 0) { antiCsrfTokenOfFirstLoginMsg = antiCsrfTokensOfFirstLoginMsg.get(0); } if (antiCsrfTokenOfFirstLoginMsg != null) { <START> HttpMessage loginMsgToRegenerateAntiCsrfToken = antiCsrfTokenOfFirstLoginMsg.getMsg().cloneAll(); <END> loginMsgToRegenerateAntiCsrfToken.setRequestingUser(user); getHttpSender().sendAndReceive(loginMsgToRegenerateAntiCsrfToken); AuthenticationHelper.addAuthMessageToHistory(loginMsgToRegenerateAntiCsrfToken); String regeneratedAntiCsrfTokenValue = extAntiCsrf.getTokenValue(loginMsgToRegenerateAntiCsrfToken, antiCsrfTokenOfFirstLoginMsg.getName()); String requestBody = requestMessage.getRequestBody().toString(); if (regeneratedAntiCsrfTokenValue != null) { requestBody = requestBody.replace( antiCsrfTokenOfFirstLoginMsg.getValue(), paramEncoder.apply(regeneratedAntiCsrfTokenValue)); requestMessage.getRequestBody().setBody(requestBody); } } }</code><technical_language>remove cookies sending loginMsgToRegenerateAntiCsrfToken, session correctly updated</technical_language>

Target:
private void replaceAntiCsrfTokenValueIfRequired(HttpMessage requestMessage, User user) throws IOException { if(extAntiCsrf == null) { extAntiCsrf = Control.getSingleton().getExtensionLoader().getExtension(ExtensionAntiCSRF.class); } List<AntiCsrfToken> antiCsrfTokensOfFirstLoginMsg = null; if(extAntiCsrf != null) { antiCsrfTokensOfFirstLoginMsg = extAntiCsrf.getTokens(requestMessage); } AntiCsrfToken antiCsrfTokenOfFirstLoginMsg = null; if(antiCsrfTokensOfFirstLoginMsg != null && antiCsrfTokensOfFirstLoginMsg.size() > 0) { antiCsrfTokenOfFirstLoginMsg = antiCsrfTokensOfFirstLoginMsg.get(0); } if (antiCsrfTokenOfFirstLoginMsg != null) { HttpMessage loginMsgToRegenerateAntiCsrfToken = antiCsrfTokenOfFirstLoginMsg.getMsg().cloneAll(); loginMsgToRegenerateAntiCsrfToken.setRequestingUser(user); loginMsgToRegenerateAntiCsrfToken.getRequestHeader().setHeader(HttpRequestHeader.COOKIE, null); getHttpSender().sendAndReceive(loginMsgToRegenerateAntiCsrfToken); AuthenticationHelper.addAuthMessageToHistory(loginMsgToRegenerateAntiCsrfToken); String regeneratedAntiCsrfTokenValue = extAntiCsrf.getTokenValue(loginMsgToRegenerateAntiCsrfToken, antiCsrfTokenOfFirstLoginMsg.getName()); String requestBody = requestMessage.getRequestBody().toString(); if (regeneratedAntiCsrfTokenValue != null) { requestBody = requestBody.replace( antiCsrfTokenOfFirstLoginMsg.getValue(), paramEncoder.apply(regeneratedAntiCsrfTokenValue)); requestMessage.getRequestBody().setBody(requestBody); } } }
Source:
<code>private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { out = new PrintStream((OutputStream)in.readObject(), AUTO_FLUSH); String name = (String)in.readObject(); charset = name==null ? null : Charset.forName(name); <START> LOGGER.log(Level.FINE, null, new Throwable("deserializing here with AUTO_FLUSH=" + AUTO_FLUSH)); <END> }</code><technical_language>nit: nice gate this if (LOGGER.isVisible(Level.FINE)) { ... } Throwable.fillInStackTrace called unnecessarily</technical_language>

Target:
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { out = new PrintStream((OutputStream)in.readObject(), AUTO_FLUSH); String name = (String)in.readObject(); charset = name==null ? null : Charset.forName(name); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, null, new Throwable("deserializing here with AUTO_FLUSH=" + AUTO_FLUSH)); } }
Source:
<code>public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { Preferences prefs = Preferences.getPreferences(getContext()); <START> if(prefs.getWifiOnlySync()){ <END> ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); @SuppressWarnings("deprecation") NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); boolean isWifiConn = networkInfo.isConnected(); if(!isWifiConn){ new NetworkReceiver().setWifiReceiverComponent(true, getContext()); return; } } Log.d(Constants.TAG, "Performing a keyserver sync!"); PowerManager pm = (PowerManager) KeyserverSyncAdapterService.this .getSystemService(Context.POWER_SERVICE); @SuppressWarnings("deprecation") boolean isScreenOn = pm.isScreenOn(); if (!isScreenOn) { startServiceWithUpdateAll(); } else { postponeSync(); } }</code><technical_language>code style. helpful highlight code written do a Ctrl+Alt+L (Reformat code)</technical_language>

Target:
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { Preferences prefs = Preferences.getPreferences(getContext()); if (prefs.getWifiOnlySync()) { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); boolean isNotOnWifi = !(networkInfo.getType() == ConnectivityManager.TYPE_WIFI); boolean isNotConnected = !(networkInfo.isConnected()); if (isNotOnWifi && isNotConnected) { new NetworkReceiver().setWifiReceiverComponent(true, getContext()); return; } } Log.d(Constants.TAG, "Performing a keyserver sync!"); PowerManager pm = (PowerManager) KeyserverSyncAdapterService.this .getSystemService(Context.POWER_SERVICE); @SuppressWarnings("deprecation") boolean isScreenOn = pm.isScreenOn(); if (!isScreenOn) { startServiceWithUpdateAll(); } else { postponeSync(); } }
Source:
<code><START> public RangeSet<String> getDimensionRangeSet(String dimension) <END> { return null; }</code><technical_language>This method supported. do work new OrDimFilter(boundDimFilters).getDimensionRangeSet(dimension)</technical_language>

Target:
public RangeSet<String> getDimensionRangeSet(String dimension) { return convertedFilter.getDimensionRangeSet(dimension); }
Source:
<code>private Matrix backPropagateMaxPooling(final Matrix input, final Matrix nextError) { if (layerError == null || !layerError.hasSameSize(input)) { layerError = matrixFactory.create(input.getRows(), input.getColumns()); } <START> layerError.fill(0); <END> final int outputSize = outputHeight * outputWidth; for (int n = 0; n < input.getColumns(); ++n) { for (int c = 0; c < inputChannel; ++c) { for (int oh = 0; oh < outputHeight; ++oh) { for (int ow = 0; ow < outputWidth; ++ow) { final int outputIndex = c * outputSize + oh * outputWidth + ow; final int maxIndex = (int) indexMatrix.get(outputIndex, n); final float newError = nextError.get(outputIndex, n) + layerError.get(maxIndex, n); layerError.put(maxIndex, n, newError); } } } } return layerError; }</code><technical_language>create fill(0)? zeros is enough</technical_language>

Target:
private Matrix backPropagateMaxPooling(final Matrix input, final Matrix nextError) { final Matrix error = matrixFactory.zeros(input.getRows(), input.getColumns()); final int outputSize = outputHeight * outputWidth; for (int n = 0; n < input.getColumns(); ++n) { for (int c = 0; c < inputChannel; ++c) { for (int oh = 0; oh < outputHeight; ++oh) { for (int ow = 0; ow < outputWidth; ++ow) { final int outputIndex = c * outputSize + oh * outputWidth + ow; final int maxIndex = (int) indexMatrix.get(outputIndex, n); final float newError = nextError.get(outputIndex, n) + error.get(maxIndex, n); error.put(maxIndex, n, newError); } } } } return error; }