auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public OfflinePlayer getOfflinePlayer(String name) { try { return getOfflinePlayerAsync(name).get(5, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException ex) { <START> Logger.getLogger(GlowServer.class.getName()).log(Level.SEVERE, "UUID lookup interrupted: ", ex); <END> } catch (TimeoutException ex) { Logger.getLogger(GlowServer.class.getName()).log(Level.WARNING, "UUID lookup timeout: ", ex); } return getOfflinePlayerFallback(name); }</code><technical_language>GlowServer.logger.log(Level.X, "message", exception)</technical_language>

Target:
public OfflinePlayer getOfflinePlayer(String name) { try { if (getProfileLookupTimeout() <= 0) { return getOfflinePlayerAsync(name).get(); } else { return getOfflinePlayerAsync(name).get(getProfileLookupTimeout(), TimeUnit.SECONDS); } } catch (InterruptedException | ExecutionException ex) { GlowServer.logger.log(Level.SEVERE, "UUID lookup interrupted: ", ex); } catch (TimeoutException ex) { GlowServer.logger.log(Level.WARNING, "UUID lookup timeout: ", ex); } return getOfflinePlayerFallback(name); }
Source:
<code>protected void onLoad() { super.onLoad(); Iterator<MatrixChildParametersAction> i = this.getActions(MatrixChildParametersAction.class).iterator(); <START> while(i.hasNext()) { <END> MatrixChildParametersAction a = i.next(); a.onLoad(this); } }</code><technical_language>iterator for loop</technical_language>

Target:
protected void onLoad() { super.onLoad(); for (MatrixChildParametersAction action : this.getActions(MatrixChildParametersAction.class)){ action.onLoad(this); } }
Source:
<code>public Response getAccountBundles(@PathParam("accountId") final String accountId, @QueryParam(QUERY_EXTERNAL_KEY) final String externalKey, @QueryParam(QUERY_BUNDLES_FILTER) final String bundlesFilter, @javax.ws.rs.core.Context final HttpServletRequest request) throws AccountApiException, SubscriptionApiException { final TenantContext tenantContext = context.createContext(request); final UUID uuid = UUID.fromString(accountId); final Account account = accountUserApi.getAccountById(uuid, tenantContext); boolean filter = (null != bundlesFilter && !bundlesFilter.isEmpty()); final List<SubscriptionBundle> bundles = (externalKey != null) ? ((filter) ? filterBundles(subscriptionApi.getSubscriptionBundlesForAccountIdAndExternalKey(uuid, externalKey, tenantContext), Arrays.asList(bundlesFilter.split(","))) : subscriptionApi.getSubscriptionBundlesForAccountIdAndExternalKey(uuid, externalKey, tenantContext)): ((filter) ? filterBundles(subscriptionApi.getSubscriptionBundlesForAccountId(uuid, tenantContext), Arrays.asList(bundlesFilter.split(","))) : <START> subscriptionApi.getSubscriptionBundlesForAccountId(uuid, tenantContext)); <END> final Collection<BundleJson> result = Collections2.transform(bundles, new Function<SubscriptionBundle, BundleJson>() { @Override public BundleJson apply(final SubscriptionBundle input) { try { return new BundleJson(input, account.getCurrency(), null); } catch (final CatalogApiException e) { throw new RuntimeException(e); } } }); return Response.status(Status.OK).entity(result).build(); }</code><technical_language>more readable fetch bundles (what before) apply filtering if needed</technical_language>

Target:
public Response getAccountBundles(@PathParam("accountId") final String accountId, @QueryParam(QUERY_EXTERNAL_KEY) final String externalKey, @QueryParam(QUERY_BUNDLES_FILTER) final String bundlesFilter, @javax.ws.rs.core.Context final HttpServletRequest request) throws AccountApiException, SubscriptionApiException { final TenantContext tenantContext = context.createContext(request); final UUID uuid = UUID.fromString(accountId); final Account account = accountUserApi.getAccountById(uuid, tenantContext); final List<SubscriptionBundle> bundles = (externalKey != null) ? subscriptionApi.getSubscriptionBundlesForAccountIdAndExternalKey(uuid, externalKey, tenantContext) : subscriptionApi.getSubscriptionBundlesForAccountId(uuid, tenantContext); boolean filter = (null != bundlesFilter && !bundlesFilter.isEmpty()); final Collection<BundleJson> result = Collections2.transform( (filter) ? filterBundles(bundles, Arrays.asList(bundlesFilter.split(","))) : bundles, new Function<SubscriptionBundle, BundleJson>() { @Override public BundleJson apply(final SubscriptionBundle input) { try { return new BundleJson(input, account.getCurrency(), null); } catch (final CatalogApiException e) { throw new RuntimeException(e); } } }); return Response.status(Status.OK).entity(result).build(); }
Source:
<code>private boolean computeNext() { if (next == null) { try { while (fileStatusIterator.hasNext()) { LocatedFileStatus status = fileStatusIterator.next(); <START> if (pathFilter.isPresent()) { <END> if (pathFilter.get().accept(status.getPath())) { next = status; return true; } } else { next = status; return true; } } return false; } catch (IOException e) { throw processException(e); } } return true; }</code><technical_language>merge this if statement be: if (!pathFilter.isPresent() || pathFilter.get().accept(status.getPath())) { next = status; return true; }</technical_language>

Target:
private void computeNext() { if (next != null) { return; } try { while (fileStatusIterator.hasNext()) { HiveFileInfo hiveFileInfo = fileStatusIterator.next(); if (!pathFilter.isPresent() || pathFilter.get().accept(hiveFileInfo.getPath())) { next = hiveFileInfo; return; } } } catch (IOException e) { throw processException(e); } }
Source:
<code>protected String addReferenceData() { <START> final boolean caseSensitive = (_caseSensitive != null && _caseSensitive.equals("on")); <END> final Dictionary dictionary = new TextFileDictionary(_name, _filePath, _encoding, caseSensitive); getReferenceDataDao().addDictionary(getWizardContext().getTenantContext(), dictionary); return _name; }</code><technical_language>removed usages of org.w3c.com.Element class, import removed</technical_language>

Target:
protected String addReferenceData() { copyUploadedFileToReferenceDataDirectory(); final boolean caseSensitive = (_caseSensitive != null && _caseSensitive.equals("on")); final Dictionary dictionary = new TextFileDictionary(_name, _filePath, _encoding, caseSensitive); getReferenceDataDao().addDictionary(getWizardContext().getTenantContext(), dictionary); return _name; }
Source:
<code>private void rejoinModifies(ProgressMonitor pm) { HashMap<String, DiffEntry> nameMap = new HashMap<String, DiffEntry>(); ArrayList<DiffEntry> newAdded = new ArrayList<DiffEntry>(added.size()); pm.beginTask(JGitText.get().renamesRejoiningModifies, added.size() + deleted.size()); for (DiffEntry src : deleted) { nameMap.put(src.oldName, src); pm.update(1); } for (DiffEntry dst : added) { <START> DiffEntry src = nameMap.get(dst.newName); <END> if (src != null && sameType(src.oldMode, dst.newMode)) { entries.add(DiffEntry.pair(ChangeType.MODIFY, src, dst, src.score)); nameMap.remove(src.oldName); } else { newAdded.add(dst); } pm.update(1); } added = newAdded; deleted = new ArrayList<DiffEntry>(nameMap.values()); }</code><technical_language>remove here. faster remove-and-get in step is get do a remove of key</technical_language>

Target:
private void rejoinModifies(ProgressMonitor pm) { HashMap<String, DiffEntry> nameMap = new HashMap<String, DiffEntry>(); ArrayList<DiffEntry> newAdded = new ArrayList<DiffEntry>(added.size()); pm.beginTask(JGitText.get().renamesRejoiningModifies, added.size() + deleted.size()); for (DiffEntry src : deleted) { nameMap.put(src.oldName, src); pm.update(1); } for (DiffEntry dst : added) { DiffEntry src = nameMap.remove(dst.newName); if (src != null) { if (sameType(src.oldMode, dst.newMode)) { entries.add(DiffEntry.pair(ChangeType.MODIFY, src, dst, src.score)); } else { nameMap.put(src.oldName, src); newAdded.add(dst); } } else { newAdded.add(dst); } pm.update(1); } added = newAdded; deleted = new ArrayList<DiffEntry>(nameMap.values()); }
Source:
<code>public boolean onToolRightClick(GlowPlayer player, ItemStack holding, GlowBlock target, BlockFace face, Vector clickedLoc) { if (target.getType() == Material.OBSIDIAN) { fireNetherPortal(); } if (target.getType() == Material.TNT) { fireTnt(target); } <START> if (target.isFlammable()) { <END> setBlockOnFire(player, target, face, holding, clickedLoc); } return true; }</code><technical_language>indent left this line? (so lines other if statements.)</technical_language>

Target:
public boolean onToolRightClick(GlowPlayer player, ItemStack holding, GlowBlock target, BlockFace face, Vector clickedLoc) { if (target.getType() == Material.OBSIDIAN) { fireNetherPortal(); return true; } if (target.getType() == Material.TNT) { fireTnt(target); return true; } if (target.isFlammable() || target.getType().isOccluding()) { setBlockOnFire(player, target, face, holding, clickedLoc); return true; } return false; }
Source:
<code>void commit(final boolean startNewTransaction, final Map<TopicPartition, Long> partitionTimes) { final long startNs = time.nanoseconds(); log.debug("Committing"); flushState(); if (!eosEnabled) { stateMgr.checkpoint(activeTaskCheckpointableOffsets()); } final Map<TopicPartition, OffsetAndMetadata> consumedOffsetsAndMetadata = new HashMap<>(consumedOffsets.size()); for (final Map.Entry<TopicPartition, Long> entry : consumedOffsets.entrySet()) { final TopicPartition partition = entry.getKey(); final long offset = entry.getValue() + 1; final long partitionTime = partitionTimes.get(partition); consumedOffsetsAndMetadata.put(partition, new OffsetAndMetadata(offset, encodeTimestamp(partitionTime))); } try { if (eosEnabled) { producer.sendOffsetsToTransaction(consumedOffsetsAndMetadata, applicationId); producer.commitTransaction(); transactionInFlight = false; if (startNewTransaction) { producer.beginTransaction(); transactionInFlight = true; } } else { consumer.commitSync(consumedOffsetsAndMetadata); } } catch (final CommitFailedException | ProducerFencedException error) { throw new TaskMigratedException(this, error); <START> } catch (final RetriableCommitFailedException error) { <END> log.info("Committing failed with a non-fatal error, we can ignore this since commit may succeed still"); } commitNeeded = false; commitRequested = false; commitSensor.record(time.nanoseconds() - startNs); }</code><technical_language>Ok. extra clear, block commits happening a rebalance eos is used, yes? guessing sense, if thoughts a alternative fix for eos a ticket for now. I guess long return data a rebalance 429 is useful for active throughput of eos.</technical_language>

Target:
void commit(final boolean startNewTransaction, final Map<TopicPartition, Long> partitionTimes) { final long startNs = time.nanoseconds(); log.debug("Committing"); flushState(); if (!eosEnabled) { stateMgr.checkpoint(activeTaskCheckpointableOffsets()); } final Map<TopicPartition, OffsetAndMetadata> consumedOffsetsAndMetadata = new HashMap<>(consumedOffsets.size()); for (final Map.Entry<TopicPartition, Long> entry : consumedOffsets.entrySet()) { final TopicPartition partition = entry.getKey(); final long offset = entry.getValue() + 1; final long partitionTime = partitionTimes.get(partition); consumedOffsetsAndMetadata.put(partition, new OffsetAndMetadata(offset, encodeTimestamp(partitionTime))); } try { if (eosEnabled) { producer.sendOffsetsToTransaction(consumedOffsetsAndMetadata, applicationId); producer.commitTransaction(); transactionInFlight = false; if (startNewTransaction) { producer.beginTransaction(); transactionInFlight = true; } } else { consumer.commitSync(consumedOffsetsAndMetadata); } } catch (final CommitFailedException | ProducerFencedException | UnknownProducerIdException error) { throw new TaskMigratedException(this, error); } catch (final RebalanceInProgressException error) { log.info("Committing failed with a non-fatal error: {}, " + "we can ignore this since commit may succeed still", error.toString()); } commitNeeded = false; commitRequested = false; commitSensor.record(time.nanoseconds() - startNs); }
Source:
<code>public void run() { String workspaceId = workspace.getId(); try { runtime.start(options); try (Unlocker ignored = lockService.writeLock(workspaceId)) { statuses.replace(workspaceId, RUNNING); } LOG.info( "Workspace '{}:{}' with id '{}' started by user '{}'", workspace.getNamespace(), workspace.getName(), workspaceId, sessionUserNameOr("undefined")); publishWorkspaceStatusEvent(workspaceId, RUNNING, STARTING, null, true); } catch (InfrastructureException e) { try (Unlocker ignored = lockService.writeLock(workspaceId)) { runtimes.remove(workspaceId); statuses.remove(workspaceId); } probeScheduler.cancel(workspaceId); String failureCause = "failed"; boolean isWorkspaceStartInterrupted = e instanceof RuntimeStartInterruptedException; if (isWorkspaceStartInterrupted) { failureCause = "interrupted"; } LOG.info( "Workspace '{}:{}' with id '{}' start {}", workspace.getNamespace(), workspace.getName(), workspaceId, failureCause); if (e instanceof InternalInfrastructureException) { LOG.error(e.getLocalizedMessage(), e); } publishWorkspaceStatusEvent( workspaceId, STOPPED, STARTING, e.getMessage(), isWorkspaceStartInterrupted, <START> Collections.emptyMap()); <END> throw new RuntimeException(e); } }</code><technical_language>I need pass emptyMap() explicitly overloaded method is for</technical_language>

Target:
public void run() { String workspaceId = workspace.getId(); try { runtime.start(options); try (Unlocker ignored = lockService.writeLock(workspaceId)) { statuses.replace(workspaceId, RUNNING); } LOG.info( "Workspace '{}:{}' with id '{}' started by user '{}'", workspace.getNamespace(), workspace.getName(), workspaceId, sessionUserNameOr("undefined")); publishWorkspaceStatusEvent(workspaceId, RUNNING, STARTING, null, true); } catch (InfrastructureException e) { try (Unlocker ignored = lockService.writeLock(workspaceId)) { runtimes.remove(workspaceId); statuses.remove(workspaceId); } probeScheduler.cancel(workspaceId); String failureCause = "failed"; boolean isWorkspaceStartInterrupted = e instanceof RuntimeStartInterruptedException; if (isWorkspaceStartInterrupted) { failureCause = "interrupted"; } LOG.info( "Workspace '{}:{}' with id '{}' start {}", workspace.getNamespace(), workspace.getName(), workspaceId, failureCause); if (e instanceof InternalInfrastructureException) { LOG.error(e.getLocalizedMessage(), e); } publishWorkspaceStatusEvent( workspaceId, STOPPED, STARTING, e.getMessage(), isWorkspaceStartInterrupted); throw new RuntimeException(e); } }
Source:
<code>XmlComponentConfigurations loadEncryptedSnapshotFileContent(long snapshotID) throws KuraException { File fSnapshot = getSnapshotFile(snapshotID); if (fSnapshot == null || !fSnapshot.exists()) { throw new KuraException(KuraErrorCode.CONFIGURATION_SNAPSHOT_NOT_FOUND, fSnapshot.getAbsolutePath()); } FileReader fr = null; BufferedReader br = null; StringBuilder entireFile = new StringBuilder(); try { fr = new FileReader(fSnapshot); br = new BufferedReader(fr); String line = ""; while ((line = br.readLine()) != null) { entireFile.append(line); } } catch (IOException e) { s_logger.error("Error loading file from disk", e); return null; } finally { try { if (br != null) { br.close(); } } catch (IOException e) { } try { if (fr != null) { fr.close(); } } catch (IOException e) { } } char[] decryptAes = this.m_cryptoService.decryptAes(entireFile.toString().toCharArray()); <START> if (decryptAes == null) { <END> throw new KuraException(KuraErrorCode.DECODER_ERROR); } String decryptedContent = new String(decryptAes); XmlComponentConfigurations xmlConfigs = null; try { xmlConfigs = XmlUtil.unmarshal(decryptedContent, XmlComponentConfigurations.class); } catch (XMLStreamException e) { s_logger.warn("Error parsing xml", e); } catch (FactoryConfigurationError e) { s_logger.warn("Error parsing xml", e); } return ConfigurationUpgrade.upgrade(xmlConfigs); }</code><technical_language>I agree @markoer Kura is full of assumptions turn NPEs then. checking for NULL hurt, Kura adopt proper null pointer analysis</technical_language>

Target:
XmlComponentConfigurations loadEncryptedSnapshotFileContent(long snapshotID) throws KuraException { File fSnapshot = getSnapshotFile(snapshotID); if (fSnapshot == null || !fSnapshot.exists()) { throw new KuraException(KuraErrorCode.CONFIGURATION_SNAPSHOT_NOT_FOUND, fSnapshot.getAbsolutePath()); } FileReader fr = null; BufferedReader br = null; StringBuilder entireFile = new StringBuilder(); try { fr = new FileReader(fSnapshot); br = new BufferedReader(fr); String line = ""; while ((line = br.readLine()) != null) { entireFile.append(line); } } catch (IOException e) { logger.error("Error loading file from disk", e); return null; } finally { try { if (br != null) { br.close(); } } catch (IOException e) { } try { if (fr != null) { fr.close(); } } catch (IOException e) { } } char[] decryptAes = this.cryptoService.decryptAes(entireFile.toString().toCharArray()); if (decryptAes == null) { throw new KuraException(KuraErrorCode.DECODER_ERROR); } String decryptedContent = new String(decryptAes); XmlComponentConfigurations xmlConfigs = null; try { xmlConfigs = XmlUtil.unmarshal(decryptedContent, XmlComponentConfigurations.class); } catch (XMLStreamException e) { logger.warn("Error parsing xml", e); } catch (FactoryConfigurationError e) { logger.warn("Error parsing xml", e); } return ConfigurationUpgrade.upgrade(xmlConfigs); }
Source:
<code>private void invokeNoMoreSplitsIfNecessary() { taskExecutionLock.readLock().lock(); try { if (!partitions.isEmpty() || !fileIterators.isEmpty()) { return; } } catch (Exception e) { hiveSplitSource.fail(e); checkState(stopped); return; <START> } <END> finally { taskExecutionLock.readLock().unlock(); } taskExecutionLock.writeLock().lock(); try { if (partitions.isEmpty() && fileIterators.isEmpty()) { hiveSplitSource.noMoreSplits(); } } catch (Exception e) { hiveSplitSource.fail(e); checkState(stopped); } finally { taskExecutionLock.writeLock().unlock(); } }</code><technical_language>Is this catch needed? kind of exception happen here</technical_language>

Target:
private void invokeNoMoreSplitsIfNecessary() { taskExecutionLock.readLock().lock(); try { if (!partitions.isEmpty() || !fileIterators.isEmpty()) { return; } } catch (Exception e) { hiveSplitSource.fail(e); checkState(stopped, "Task is not marked as stopped even though it failed"); return; } finally { taskExecutionLock.readLock().unlock(); } taskExecutionLock.writeLock().lock(); try { if (partitions.isEmpty() && fileIterators.isEmpty()) { hiveSplitSource.noMoreSplits(); } } catch (Exception e) { hiveSplitSource.fail(e); checkState(stopped, "Task is not marked as stopped even though it failed"); } finally { taskExecutionLock.writeLock().unlock(); } }
Source:
<code>protected void cleanup() throws Exception { <START> delete(item); <END> }</code><technical_language>workspaceitem needs deleted</technical_language>

Target:
protected void cleanup() throws Exception { delete(workspaceItem); }
Source:
<code>public static void testGetAllActivities() throws MambuApiException { System.out.println("\nIn testGetAllActivities"); ActivitiesService activitiesService = MambuAPIFactory.getActivitiesService(); Date toDate = new Date(); long timeNow = toDate.getTime(); int forNumberOfDays = 5; long activiTiesForMsecInterval = 1000 * 60 * 60 * 24 * forNumberOfDays; long timeBefore = timeNow - activiTiesForMsecInterval; Date fromDate = new Date(timeBefore); List<JSONActivity> jsonActivities = activitiesService.getActivities(fromDate, toDate); if (jsonActivities == null) { System.out.println("Error - API returned NULL for" + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); return; } System.out.println("Total activities returned=" + jsonActivities.size() + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); for (JSONActivity jsonActivity : jsonActivities) { Activity activity = jsonActivity.getActivity(); System.out.println(activity.getType() + "\tID =" + activity.getTransactionId() + " Client Key=" + activity.getClientKey() + "\tLoanAccount Key=" + activity.getLoanAccountKey() + "\tSavingsAccount Key=" + activity.getSavingsAccountKey()); } <START> return; <END> }</code><technical_language>return a line for "void" methods is uncommon confusing</technical_language>

Target:
public static void testGetAllActivities() throws MambuApiException { System.out.println("\nIn testGetAllActivities"); ActivitiesService activitiesService = MambuAPIFactory.getActivitiesService(); Date toDate = new Date(); long timeNow = toDate.getTime(); int forNumberOfDays = 5; long activiTiesForMsecInterval = 1000 * 60 * 60 * 24 * forNumberOfDays; long timeBefore = timeNow - activiTiesForMsecInterval; Date fromDate = new Date(timeBefore); List<JSONActivity> jsonActivities = activitiesService.getActivities(fromDate, toDate); if (jsonActivities == null) { System.out.println("Error - API returned NULL for" + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); return; } System.out.println("Total activities returned=" + jsonActivities.size() + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); for (JSONActivity jsonActivity : jsonActivities) { Activity activity = jsonActivity.getActivity(); ActivityType activityType = activity.getType(); System.out.println(activityType + "\tID =" + activity.getTransactionId() + " Client Key=" + activity.getClientKey() + "\tLoanAccount Key=" + activity.getLoanAccountKey() + "\tSavingsAccount Key=" + activity.getSavingsAccountKey()); final String activityTypePrefix = "CLIENT_"; if (clientKeyWithActivities == null && activityType != null && activityType.name().startsWith(activityTypePrefix)) { clientKeyWithActivities = activity.getClientKey(); } } }
Source:
<code>public ExprEval eval(ObjectBinding bindings) { ExprEval leftVal = left.eval(bindings); ExprEval rightVal = right.eval(bindings); <START> if (NullHandling.sqlCompatible() && (leftVal.value() == null || rightVal.value() == null)) { <END> return ExprEval.of(null); } if (leftVal.type() == ExprType.STRING && rightVal.type() == ExprType.STRING) { return evalString(leftVal.asString(), rightVal.asString()); } else if (leftVal.type() == ExprType.LONG && rightVal.type() == ExprType.LONG) { if (NullHandling.sqlCompatible() && (leftVal.isNull() || rightVal.isNull())) { return ExprEval.of(null); } return ExprEval.of(evalLong(leftVal.asLong(), rightVal.asLong())); } else { if (NullHandling.sqlCompatible() && (leftVal.isNull() || rightVal.isNull())) { return ExprEval.of(null); } return ExprEval.of(evalDouble(leftVal.asDouble(), rightVal.asDouble())); } }</code><technical_language>this change</technical_language>

Target:
public ExprEval eval(ObjectBinding bindings) { ExprEval leftVal = left.eval(bindings); ExprEval rightVal = right.eval(bindings); if (NullHandling.sqlCompatible() && (leftVal.value() == null || rightVal.value() == null)) { return ExprEval.of(null); } if (leftVal.type() == ExprType.STRING && rightVal.type() == ExprType.STRING) { return evalString(leftVal.asString(), rightVal.asString()); } else if (leftVal.type() == ExprType.LONG && rightVal.type() == ExprType.LONG) { if (NullHandling.sqlCompatible() && (leftVal.isNumericNull() || rightVal.isNumericNull())) { return ExprEval.of(null); } return ExprEval.of(evalLong(leftVal.asLong(), rightVal.asLong())); } else { if (NullHandling.sqlCompatible() && (leftVal.isNumericNull() || rightVal.isNumericNull())) { return ExprEval.of(null); } return ExprEval.of(evalDouble(leftVal.asDouble(), rightVal.asDouble())); } }
Source:
<code>public void testFindAllIterationOperation() throws Exception { assertEquals(0, testCollection.count()); pumpDataIntoTestCollection(); int numToSkip = 0; final int limit = 100; for (int i = 0; i < 10; i++) { Map<String, Object> headers = new HashMap<String, Object>(); headers.put(MongoDbConstants.NUM_TO_SKIP, numToSkip); headers.put(MongoDbConstants.LIMIT, 100); Object result = template.requestBodyAndHeaders("direct:findAll", (Object) null, headers); <START> System.out.println(result.getClass()); <END> assertTrue("Result is not of type List", result instanceof List); @SuppressWarnings("unchecked") List<DBObject> resultList = (List<DBObject>) result; assertListSize("Result does not contain 100 elements", resultList, 100); assertEquals("Id of first record is not as expected", numToSkip + 1, Integer.parseInt((String) resultList.get(0).get("_id"))); for (DBObject dbObject : resultList) { assertNotNull("DBObject in returned list should contain all fields", dbObject.get("_id")); assertNotNull("DBObject in returned list should contain all fields", dbObject.get("scientist")); assertNotNull("DBObject in returned list should contain all fields", dbObject.get("fixedField")); } numToSkip = numToSkip + limit; } for (Exchange resultExchange : getMockEndpoint("mock:resultFindAll").getReceivedExchanges()) { assertEquals("Result page size header should equal 100", 100, resultExchange.getIn().getHeader(MongoDbConstants.RESULT_PAGE_SIZE)); } }</code><technical_language>Remove this LOG.info</technical_language>

Target:
public void testFindAllIterationOperation() throws Exception { assertEquals(0, testCollection.count()); pumpDataIntoTestCollection(); int numToSkip = 0; final int limit = 100; for (int i = 0; i < 10; i++) { Map<String, Object> headers = new HashMap<String, Object>(); headers.put(MongoDbConstants.NUM_TO_SKIP, numToSkip); headers.put(MongoDbConstants.LIMIT, 100); Object result = template.requestBodyAndHeaders("direct:findAll", (Object) null, headers); assertTrue("Result is not of type List", result instanceof List); @SuppressWarnings("unchecked") List<DBObject> resultList = (List<DBObject>) result; assertListSize("Result does not contain 100 elements", resultList, 100); assertEquals("Id of first record is not as expected", numToSkip + 1, Integer.parseInt((String) resultList.get(0).get("_id"))); for (DBObject dbObject : resultList) { assertNotNull("DBObject in returned list should contain all fields", dbObject.get("_id")); assertNotNull("DBObject in returned list should contain all fields", dbObject.get("scientist")); assertNotNull("DBObject in returned list should contain all fields", dbObject.get("fixedField")); } numToSkip = numToSkip + limit; } for (Exchange resultExchange : getMockEndpoint("mock:resultFindAll").getReceivedExchanges()) { assertEquals("Result page size header should equal 100", 100, resultExchange.getIn().getHeader(MongoDbConstants.RESULT_PAGE_SIZE)); } }
Source:
<code>public void testResynchronize_success() { <START> this.client.getApplicationDelegate().resynchronize( this.app.getName() ); <END> }</code><technical_language>A test test ? unusual</technical_language>

Target:
public void testResynchronize_success() throws ApplicationException { final Collection<Instance> rootInstances = this.app.getRootInstances(); for(Instance i : rootInstances) i.setStatus( InstanceStatus.DEPLOYED_STARTED ); this.client.getApplicationDelegate().resynchronize( this.app.getName() ); final List<Message> sentMessages = this.msgClient.sentMessages; Assert.assertEquals( rootInstances.size(), sentMessages.size() ); for (Iterator<Message> i = sentMessages.iterator(); i.hasNext();) Assert.assertTrue( i.next() instanceof MsgCmdResynchronize ); }
Source:
<code><START> public final String toString() { <END> return this.joinpoint.toString(); }</code><technical_language>@shelan need declare method final</technical_language>

Target:
public String toString() { return this.joinpoint.toString(); }
Source:
<code>public Future<Long> write(ByteBuffer src, Callback<Long> callback) { return writeInternal(() -> { ByteBuf copy = src.isDirect() ? ByteBufAllocator.DEFAULT.directBuffer(src.remaining()) : PooledByteBufAllocator.DEFAULT.heapBuffer(src.remaining()); <START> copy.writeBytes(src); <END> return copy; }, callback); }</code><technical_language>change position of src, write method below</technical_language>

Target:
public Future<Long> write(ByteBuffer src, Callback<Long> callback) { return writeInternal(() -> { ByteBuf copy = src.isDirect() ? ByteBufAllocator.DEFAULT.directBuffer(src.remaining()) : PooledByteBufAllocator.DEFAULT.heapBuffer(src.remaining()); copy.writeBytes(src); src.position(src.limit()); return copy; }, callback); }
Source:
<code>public Criterion convert(final String value) { final Criterion.Builder criterionBuilder = new Criterion.Builder(); final Matcher multiComponentMatcher = MULTI_CRITERION_PATTERN.matcher(value); final Matcher singleComponentMatcher = SINGLE_CRITERION_PATTERN.matcher(value); final Matcher matchingMatcher; if (multiComponentMatcher.matches()) { matchingMatcher = multiComponentMatcher; } else if (singleComponentMatcher.matches()) { matchingMatcher = singleComponentMatcher; } else { throw new ParameterException("Invalid criterion: " + value); } <START> final String id = matchingMatcher.group("id"); <END> final String name = matchingMatcher.group("name"); final String status = matchingMatcher.group("status"); final String tags = matchingMatcher.group("tags"); final Set<String> splitTags = tags == null ? null : Sets.newHashSet(tags.split(",")); criterionBuilder .withId(id) .withName(name) .withStatus(status) .withTags(splitTags); try { return criterionBuilder.build(); } catch (final GeniePreconditionException e) { throw new ParameterException("Invalid criterion: " + value, e); } }</code><technical_language>groups constants enum something</technical_language>

Target:
public Criterion convert(final String value) { final Criterion.Builder criterionBuilder = new Criterion.Builder(); final Matcher multiComponentMatcher = MULTI_CRITERION_PATTERN.matcher(value); final Matcher singleComponentMatcher = SINGLE_CRITERION_PATTERN.matcher(value); final Matcher matchingMatcher; if (multiComponentMatcher.matches()) { matchingMatcher = multiComponentMatcher; } else if (singleComponentMatcher.matches()) { matchingMatcher = singleComponentMatcher; } else { throw new ParameterException("Invalid criterion: " + value); } final String id = matchingMatcher.group(ID_CAPTURE_GROUP); final String name = matchingMatcher.group(NAME_CAPTURE_GROUP); final String status = matchingMatcher.group(STATUS_CAPTURE_GROUP); final String tags = matchingMatcher.group(TAGS_CAPTURE_GROUP); final Set<String> splitTags = tags == null ? null : Sets.newHashSet(tags.split(",")); criterionBuilder .withId(id) .withName(name) .withStatus(status) .withTags(splitTags); try { return criterionBuilder.build(); } catch (final GeniePreconditionException e) { throw new ParameterException("Invalid criterion: " + value, e); } }
Source:
<code>protected IFigure createNodeShape() { final EObject eObj = resolveSemanticElement(); ViewNodeContainerFigureDesc shapeFigure = null; if (eObj instanceof DDiagramElementContainer) { final DDiagramElementContainer container = (DDiagramElementContainer) eObj; ContainerStyle ownedStyle = container.getOwnedStyle(); if (ownedStyle instanceof ShapeContainerStyle) { shapeFigure = new ViewNodeContainerParallelogram(); } else if (ownedStyle instanceof WorkspaceImage) { shapeFigure = new ViewNodeContainerRectangleFigureDesc(); } } else { deactivate(); } if (shapeFigure == null) { shapeFigure = new GradientRoundedRectangle(DiagramContainerEditPartOperation.getCornerDimension(this), DiagramContainerEditPartOperation.getBackgroundStyle(this)); } <START> shapeFigure.getLabelFigure().setVisible(false); <END> return shapeFigure; }</code><technical_language>This configured label visibility status. add of name edit part call refreshVisual</technical_language>

Target:
protected IFigure createNodeShape() { final EObject eObj = resolveSemanticElement(); ViewNodeContainerFigureDesc shapeFigure = null; if (eObj instanceof DDiagramElementContainer) { final DDiagramElementContainer container = (DDiagramElementContainer) eObj; ContainerStyle ownedStyle = container.getOwnedStyle(); if (ownedStyle instanceof ShapeContainerStyle) { shapeFigure = new ViewNodeContainerParallelogram(); } else if (ownedStyle instanceof WorkspaceImage) { shapeFigure = new ViewNodeContainerRectangleFigureDesc(); } } else { deactivate(); } if (shapeFigure == null) { shapeFigure = new GradientRoundedRectangle(DiagramContainerEditPartOperation.getCornerDimension(this), DiagramContainerEditPartOperation.getBackgroundStyle(this)); } if (eObj instanceof DDiagramElement && new DDiagramElementQuery((DDiagramElement) eObj).isLabelHidden()) { shapeFigure.getLabelFigure().setVisible(false); } else { shapeFigure.getLabelFigure().setVisible(true); } return shapeFigure; }
Source:
<code>public Batch firstBatch() throws RetryableException { setUpTopicPartitions(); Map<TopicPartition, OffsetAndTimestamp> kafkaOffsets = getOffsets(); consumer.assign(kafkaOffsets.keySet()); log.info("Subscribed to topics", kafkaOffsets.size()); kafkaOffsets.forEach( (topic, offset) -> { if (offset == null) { log.info("No offset for {}, starting at the end", topic); <START> consumer.seekToEnd(Collections.singletonList(topic)); <END> return; } consumer.seek(topic, offset.offset()); log.info("Set topic to {}", topic, offset); } ); return fetch(firstStartTime); }</code><technical_language>static import more readable IMHO (feel free ignore)</technical_language>

Target:
public Batch firstBatch() throws RetryableException { setUpTopicPartitions(); Map<TopicPartition, OffsetAndTimestamp> kafkaOffsets = fetchOffsets(); consumer.assign(kafkaOffsets.keySet()); log.info("Subscribed to topics", kafkaOffsets.size()); kafkaOffsets.forEach( (topic, offset) -> { if (offset == null) { log.info("No offset for {}, starting at the end", topic); consumer.seekToEnd(Collections.singletonList(topic)); return; } consumer.seek(topic, offset.offset()); log.info("Set topic to {}", topic, offset); } ); return fetch(firstStartTime); }
Source:
<code>private void refreshLocks() { try { Set<LockToken> toRefresh = ImmutableSet.copyOf(tokensToRefresh); if (toRefresh.isEmpty()) { return; } Set<LockToken> successfullyRefreshedTokens = timelockService.refreshLockLeases(toRefresh); Set<LockToken> refreshFailures = Sets.difference(toRefresh, successfullyRefreshedTokens); tokensToRefresh.removeAll(refreshFailures); <START> if (!refreshFailures.isEmpty()) { <END> log.info("Failed to refresh lock tokens, most likely because they were lost on the server." + " The first (up to) 20 of these were {}.", SafeArg.of("successfullyRefreshed", successfullyRefreshedTokens.size()), SafeArg.of("numLockTokens", refreshFailures.size()), SafeArg.of("firstFailures", Iterables.transform(Iterables.limit(refreshFailures, 20), LockToken::getRequestId))); } } catch (Throwable error) { log.warn("Error while refreshing locks. Trying again on next iteration", error); } }</code><technical_language>Yep, does. I a log spam week, get "async unlocker refresher a race condition"</technical_language>

Target:
private void refreshLocks() { try { Set<LockToken> toRefresh = ImmutableSet.copyOf(tokensToRefresh); if (toRefresh.isEmpty()) { return; } Set<LockToken> successfullyRefreshedTokens = timelockService.refreshLockLeases(toRefresh); Set<LockToken> refreshFailures = Sets.difference(toRefresh, successfullyRefreshedTokens); tokensToRefresh.removeAll(refreshFailures); if (!refreshFailures.isEmpty()) { log.info("Successfully refreshed {}, but failed to refresh lock tokens, " + "most likely because they were lost on the server." + " The first (up to) 20 of these were {}.", SafeArg.of("successfullyRefreshed", successfullyRefreshedTokens.size()), SafeArg.of("numLockTokens", refreshFailures.size()), SafeArg.of("firstFailures", Iterables.transform(Iterables.limit(refreshFailures, 20), LockToken::getRequestId))); } } catch (Throwable error) { log.warn("Error while refreshing locks. Trying again on next iteration", error); } }
Source:
<code>public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { DocumentCursor<BaseDocument> cursor = null; try { String aqlQuery = String.format( "FOR target IN %s FILTER target._key >= @key SORT target._key ASC LIMIT %d RETURN %s ", table, recordcount, constructReturnForAQL(fields, "target")); Map<String, Object> bindVars = new MapBuilder().put("key", startkey).get(); cursor = arangoDriver.executeDocumentQuery(aqlQuery, bindVars, null, BaseDocument.class); Iterator<BaseDocument> iterator = cursor.entityIterator(); while (iterator.hasNext()) { BaseDocument aDocument = iterator.next(); HashMap<String, ByteIterator> aMap = new HashMap<String, ByteIterator>(aDocument.getProperties().size()); this.fillMap(aMap, aDocument.getProperties()); result.add(aMap); } return Status.OK; } catch (Exception e) { <START> logger.error("Exception while trying scan " + table + " " + startkey + " " + recordcount, e); <END> } finally { if (cursor != null) { try { cursor.close(); } catch (ArangoException e) { logger.error("Fail to close cursor", e); } } } return Status.ERROR; }</code><technical_language>a format placeholder instead of string concat</technical_language>

Target:
public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { DocumentCursor<BaseDocument> cursor = null; try { String aqlQuery = String.format( "FOR target IN %s FILTER target._key >= @key SORT target._key ASC LIMIT %d RETURN %s ", table, recordcount, constructReturnForAQL(fields, "target")); Map<String, Object> bindVars = new MapBuilder().put("key", startkey).get(); cursor = arangoDriver.executeDocumentQuery(aqlQuery, bindVars, null, BaseDocument.class); Iterator<BaseDocument> iterator = cursor.entityIterator(); while (iterator.hasNext()) { BaseDocument aDocument = iterator.next(); HashMap<String, ByteIterator> aMap = new HashMap<String, ByteIterator>(aDocument.getProperties().size()); if (!this.fillMap(aMap, aDocument.getProperties())) { return Status.ERROR; } result.add(aMap); } return Status.OK; } catch (Exception e) { logger.error("Exception while trying scan with ex {}", table, startkey, recordcount, e.toString()); } finally { if (cursor != null) { try { cursor.close(); } catch (ArangoException e) { logger.error("Fail to close cursor", e); } } } return Status.ERROR; }
Source:
<code>public void onTestContextInitialized() { execute( "CREATE KEYSPACE IF NOT EXISTS MapperKeyspaceTest WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", "CREATE TYPE IF NOT EXISTS MapperKeyspaceTest.address(street text)", <START> "CREATE TABLE IF NOT EXISTS MapperKeyspaceTest.user(name text PRIMARY KEY, address address)", <END> "CREATE KEYSPACE IF NOT EXISTS MapperKeyspaceTest2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", "CREATE TYPE IF NOT EXISTS MapperKeyspaceTest2.address(street text)", "CREATE TABLE IF NOT EXISTS MapperKeyspaceTest2.user(name text PRIMARY KEY, address address)" ); }</code><technical_language>good UDT frozen in tables works versions 2.1+</technical_language>

Target:
public void onTestContextInitialized() { execute( "CREATE KEYSPACE IF NOT EXISTS MapperKeyspaceTest WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", "CREATE TYPE IF NOT EXISTS MapperKeyspaceTest.address(street text)", "CREATE TABLE IF NOT EXISTS MapperKeyspaceTest.user(name text PRIMARY KEY, address frozen<address>)", "CREATE KEYSPACE IF NOT EXISTS MapperKeyspaceTest2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", "CREATE TYPE IF NOT EXISTS MapperKeyspaceTest2.address(street text)", "CREATE TABLE IF NOT EXISTS MapperKeyspaceTest2.user(name text PRIMARY KEY, address frozen<address>)" ); }
Source:
<code>public void passesValidXmlWithNetworkProblems() throws Exception { final Validator validator = Mockito.mock(Validator.class); final AtomicInteger counter = new AtomicInteger(0); Mockito.doAnswer( new Answer<Void>() { @Override public Void answer(final InvocationOnMock invocation) throws Throwable { final int attempt = counter.incrementAndGet(); if (attempt == 1 || attempt == 2) { throw new SocketException( String.format("Attempt #%s failed", attempt) ); <START> } else { <END> return null; } } }).when(validator).validate(Mockito.any(Source.class)); new StrictXML( new XMLDocument( "<root>passesValidXmlWithNetworkProblems</root>" ), validator ); }</code><technical_language>need do else here. return null</technical_language>

Target:
public void passesValidXmlWithNetworkProblems() throws Exception { final Validator validator = Mockito.mock(Validator.class); final AtomicInteger counter = new AtomicInteger(0); Mockito.doAnswer( new Answer<Void>() { @Override public Void answer(final InvocationOnMock invocation) throws Throwable { final int attempt = counter.incrementAndGet(); if (attempt == 1 || attempt == 2) { throw new SocketException( String.format("Attempt #%s failed", attempt) ); } return null; } } ).when(validator).validate(Mockito.any(Source.class)); new StrictXML( new XMLDocument( "<root>passesValidXmlWithNetworkProblems</root>" ), validator ); }
Source:
<code>private void playOutExplosion(GlowPlayer player, Iterable<Block> blocks) { Collection<Record> records = new ArrayList<>(); for (Block block : blocks) { <START> byte x = (byte) (block.getLocation().getBlockX() - (int) location.getX()); <END> byte y = (byte) (block.getLocation().getBlockY() - (int) location.getY()); byte z = (byte) (block.getLocation().getBlockZ() - (int) location.getZ()); records.add(new Record(x, y, z)); } Vector velocity = player.getVelocity(); ExplosionMessage message = new ExplosionMessage((float) location.getX(), (float) location.getY(), (float) location.getZ(), power, (float) velocity.getX(), (float) velocity.getY(), (float) velocity.getZ(), records); player.getSession().send(message); }</code><technical_language>Is a reason (int) location.getX() instead of location.getBlockX()? Also, please cache block.getLocation() object method creates new Location instances time</technical_language>

Target:
private void playOutExplosion(GlowPlayer player, Iterable<Block> blocks) { Collection<Record> records = new ArrayList<>(); for (Block block : blocks) { Location blockLocation = block.getLocation(); byte x = (byte) (blockLocation.getBlockX() - (int) this.location.getX()); byte y = (byte) (blockLocation.getBlockY() - (int) this.location.getY()); byte z = (byte) (blockLocation.getBlockZ() - (int) this.location.getZ()); records.add(new Record(x, y, z)); } Vector velocity = player.getVelocity(); ExplosionMessage message = new ExplosionMessage((float) location.getX(), (float) location.getY(), (float) location.getZ(), power, (float) velocity.getX(), (float) velocity.getY(), (float) velocity.getZ(), records); player.getSession().send(message); }
Source:
<code>public void testWindowDataManager() throws Exception { LocalMode lma = LocalMode.newInstance(); DAG dag = lma.getDAG(); KinesisStringInputOperator inputOperator = dag.addOperator("KinesisInput", new KinesisStringInputOperator() { @Override public void deactivate() { } @Override public void teardown() { } }); testMeta.operator = inputOperator; <START> Assert.assertFalse("Default behaviour of WindowDataManager changed", <END> (inputOperator.getWindowDataManager() instanceof WindowDataManager.NoopWindowDataManager)); }</code><technical_language>this condition assertTrue</technical_language>

Target:
public void testWindowDataManager() throws Exception { LocalMode lma = LocalMode.newInstance(); DAG dag = lma.getDAG(); KinesisStringInputOperator inputOperator = dag.addOperator("KinesisInput", new KinesisStringInputOperator() { @Override public void deactivate() { } @Override public void teardown() { } }); testMeta.operator = inputOperator; Assert.assertTrue("Default behaviour of WindowDataManager changed", (inputOperator.getWindowDataManager() instanceof WindowDataManager.NoopWindowDataManager)); }
Source:
<code>public void doLaunch(Context context, View v) { if (v == null) { if (togglesHandler == null) { togglesHandler = new TogglesHandler(context); } String msg = context.getResources().getString(togglesHandler.getState(togglePojo) ? R.string.toggles_off : R.string.toggles_on); togglesHandler.setState(togglePojo, !togglesHandler.getState(togglePojo)); <START> Toast.makeText(context, String.format(msg + " " + this.pojo.displayName, Locale.getDefault()), Toast.LENGTH_SHORT).show(); <END> } else { final CompoundButton toggleButton = (CompoundButton) v .findViewById(R.id.item_toggle_action_toggle); if (toggleButton.isEnabled()) { toggleButton.performClick(); } } }</code><technical_language>string templates translations too</technical_language>

Target:
public void doLaunch(Context context, View v) { if (v == null) { if (togglesHandler == null) { togglesHandler = new TogglesHandler(context); } String msg = context.getResources().getString(togglesHandler.getState(togglePojo) ? R.string.toggles_off : R.string.toggles_on); togglesHandler.setState(togglePojo, !togglesHandler.getState(togglePojo)); Toast.makeText(context, String.format(msg, " " + this.pojo.displayName), Toast.LENGTH_SHORT).show(); } else { final CompoundButton toggleButton = (CompoundButton) v .findViewById(R.id.item_toggle_action_toggle); if (toggleButton.isEnabled()) { toggleButton.performClick(); } } }
Source:
<code>public void log(RequestLogLine requestLogLine) throws IOException { <START> IOException exception = null; <END> for (RequestLogger logger : loggers) { try { logger.log(requestLogLine); } catch (IOException e) { if (exception == null) { exception = e; } else { exception.addSuppressed(e); } } } if (exception != null) { throw exception; } }</code><technical_language>catch Exception, loop, propagate if IOException, Guava's Throwables</technical_language>

Target:
public void log(RequestLogLine requestLogLine) throws IOException { Exception exception = null; for (RequestLogger logger : loggers) { try { logger.log(requestLogLine); } catch (Exception e) { if (exception == null) { exception = e; } else { exception.addSuppressed(e); } } } if (exception != null) { Throwables.propagateIfInstanceOf(exception, IOException.class); throw Throwables.propagate(exception); } }
Source:
<code>public List<IndexedVector> sendReduceData(final int iteration) { <START> final List<IndexedVector> columnsOfResultMatrix = new LinkedList<>(); <END> for (final Integer column : elementsOfLargeMatrix.keySet()) { final Vector columnVectorOfLargeMatrix = getColumnVector(elementsOfLargeMatrix.get(column)); final Vector columnVectorOfResultMatrix = getColumnOfResultMatrix(columnVectorOfLargeMatrix); columnsOfResultMatrix.add(new IndexedVector(column, columnVectorOfResultMatrix)); } return columnsOfResultMatrix; }</code><technical_language>big this list be, ArrayList<>(size)</technical_language>

Target:
public List<IndexedVector> sendReduceData(final int iteration) { return columnsOfResultMatrix; }
Source:
<code>public HMSShim(IMetaStoreClient client) { while (Proxy.isProxyClass(client.getClass())) { InvocationHandler handler = Proxy.getInvocationHandler(client); if (handler.getClass().isAssignableFrom(RetryingMetaStoreClient.class)) { client = getField(handler, "base"); continue; } <START> throw new RuntimeException("Unknown InvocationHandler " + handler.getClass()); <END> } mClient = getField(client, "client"); }</code><technical_language>this message more specific? user do message</technical_language>

Target:
public HMSShim(IMetaStoreClient client) { while (Proxy.isProxyClass(client.getClass())) { InvocationHandler handler = Proxy.getInvocationHandler(client); if (handler.getClass().isAssignableFrom(RetryingMetaStoreClient.class)) { client = getField(handler, "base"); continue; } throw new RuntimeException("Unknown proxy handler for IMetaStoreClient"); } mClient = getField(client, "client"); }