auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected OAuth10Credentials getOAuthCredentials(final WebContext context) { final Optional<String> tokenParameter = context.getRequestParameter(OAuth10Configuration.OAUTH_TOKEN); final Optional<String> verifierParameter = context.getRequestParameter(OAuth10Configuration.OAUTH_VERIFIER); <START> if (tokenParameter.isPresent() && verifierParameter.isPresent()) { <END> final OAuth1RequestToken tokenSession = (OAuth1RequestToken) context .getSessionStore().get(context, configuration.getRequestTokenSessionAttributeName(client.getName())).orElse(null); logger.debug("tokenRequest: {}", tokenSession); final String token = OAuthEncoder.decode(tokenParameter.get()); final String verifier = OAuthEncoder.decode(verifierParameter.get()); logger.debug("token: / verifier: {}", token, verifier); return new OAuth10Credentials(tokenSession, token, verifier); } else { final String message = "No credential found"; throw new OAuthCredentialsException(message); } }</code><technical_language>prefer map and/or flatMap nulls</technical_language>

Target:
protected OAuth10Credentials getOAuthCredentials(final WebContext context) { final Optional<String> tokenParameter = context.getRequestParameter(OAuth10Configuration.OAUTH_TOKEN); final Optional<String> verifierParameter = context.getRequestParameter(OAuth10Configuration.OAUTH_VERIFIER); if (tokenParameter.isPresent() && verifierParameter.isPresent()) { final Optional<OAuth1RequestToken> tokenSession = context .getSessionStore() .get(context, configuration.getRequestTokenSessionAttributeName(client.getName())); logger.debug("tokenRequest: {}", tokenSession); final String token = OAuthEncoder.decode(tokenParameter.get()); final String verifier = OAuthEncoder.decode(verifierParameter.get()); logger.debug("token: / verifier: {}", token, verifier); return new OAuth10Credentials(tokenSession.get(), token, verifier); } else { final String message = "No credential found"; throw new OAuthCredentialsException(message); } }
Source:
<code>public void testReplicateLFShouldCopyFailedBookieFragmentsToTargetBookie() throws Exception { byte[] data = "TestLedgerFragmentReplication".getBytes(); LedgerHandle lh = bkc.createLedger(3, 3, TEST_DIGEST_TYPE, TEST_PSSWD); for (int i = 0; i < 10; i++) { lh.addEntry(data); } BookieSocketAddress replicaToKill = lh.getLedgerMetadata().getAllEnsembles() .get(0L).get(0); LOG.info("Killing Bookie : {}", replicaToKill); killBookie(replicaToKill); BookieSocketAddress newBkAddr = startNewBookieAndReturnAddress(); LOG.info("New Bookie addr : {}", newBkAddr); for (int i = 0; i < 10; i++) { lh.addEntry(data); } Set<LedgerFragment> result = getFragmentsToReplicate(lh); BookKeeperAdmin admin = new BookKeeperAdmin(baseClientConf); lh.close(); for (LedgerFragment lf : result) { <START> admin.replicateLedgerFragment(lh, lf, null); <END> } SortedMap<Long, ? extends List<BookieSocketAddress>> allBookiesBeforeReplication = lh .getLedgerMetadata().getAllEnsembles(); for (Entry<Long, ? extends List<BookieSocketAddress>> entry : allBookiesBeforeReplication.entrySet()) { List<BookieSocketAddress> bookies = entry.getValue(); for (BookieSocketAddress bookie : bookies) { if (newBkAddr.equals(bookie)) { continue; } killBookie(bookie); } } verifyRecoveredLedgers(lh, 0, 9); }</code><technical_language>pass a null value? clearer flow of variable is used, prevent bugs</technical_language>

Target:
public void testReplicateLFShouldCopyFailedBookieFragmentsToTargetBookie() throws Exception { byte[] data = "TestLedgerFragmentReplication".getBytes(); LedgerHandle lh = bkc.createLedger(3, 3, TEST_DIGEST_TYPE, TEST_PSSWD); for (int i = 0; i < 10; i++) { lh.addEntry(data); } BookieSocketAddress replicaToKill = lh.getLedgerMetadata().getAllEnsembles() .get(0L).get(0); LOG.info("Killing Bookie : {}", replicaToKill); killBookie(replicaToKill); BookieSocketAddress newBkAddr = startNewBookieAndReturnAddress(); LOG.info("New Bookie addr : {}", newBkAddr); for (int i = 0; i < 10; i++) { lh.addEntry(data); } Set<LedgerFragment> result = getFragmentsToReplicate(lh); BookKeeperAdmin admin = new BookKeeperAdmin(baseClientConf); lh.close(); for (LedgerFragment lf : result) { admin.replicateLedgerFragment(lh, lf, NOOP_BICONSUMER); } SortedMap<Long, ? extends List<BookieSocketAddress>> allBookiesBeforeReplication = lh .getLedgerMetadata().getAllEnsembles(); for (Entry<Long, ? extends List<BookieSocketAddress>> entry : allBookiesBeforeReplication.entrySet()) { List<BookieSocketAddress> bookies = entry.getValue(); for (BookieSocketAddress bookie : bookies) { if (newBkAddr.equals(bookie)) { continue; } killBookie(bookie); } } verifyRecoveredLedgers(lh, 0, 9); }
Source:
<code>public void testInitBareRepository() { String directory = new File(trash, "test2").getPath(); try { InitCommand command = new InitCommand(); command.setDirectory(directory); command.setBare(true); Repository repository = command.call().getRepository(); <START> assertNotNull(repository); <END> assertTrue(repository.isBare()); } catch (Exception e) { fail(e.getMessage()); } }</code><technical_language>debug this single test case stop here, resulting file system structure git repo structure twice, this weird, I is wrong : test1291410985097_0 - .git - branches - config - HEAD - logs - objects - refs - test2 - branches - config - HEAD - logs - objects - refs</technical_language>

Target:
public void testInitBareRepository() { try { File directory = createTempDirectory("testInitBareRepository"); InitCommand command = new InitCommand(); command.setDirectory(directory); command.setBare(true); Repository repository = command.call().getRepository(); assertNotNull(repository); assertTrue(repository.isBare()); } catch (Exception e) { fail(e.getMessage()); } }
Source:
<code>public CatalogServiceImpl( CatalogFramework framework, AttachmentParser attachmentParser, AttributeRegistry attributeRegistry) { <START> LOGGER.trace("Constructing REST Endpoint"); <END> this.catalogFramework = framework; this.attachmentParser = attachmentParser; this.attributeRegistry = attributeRegistry; LOGGER.trace(("Rest Endpoint constructed successfully")); }</code><technical_language>Constructing CatalogServiceImpl</technical_language>

Target:
public CatalogServiceImpl( CatalogFramework framework, AttachmentParser attachmentParser, AttributeRegistry attributeRegistry) { LOGGER.trace("Constructing CatalogServiceImpl"); this.catalogFramework = framework; this.attachmentParser = attachmentParser; this.attributeRegistry = attributeRegistry; LOGGER.trace(("CatalogServiceImpl constructed successfully")); }
Source:
<code>protected void setPRPAINBuilder(Patient query) { PRPAIN201305UV02Builder builder = new PRPAIN201305UV02BuilderImpl(); <START> ((PRPAIN201305UV02BuilderImpl) builder).setPatient(query); <END> pdMessageDirector.setPRPAIN201305UV02Builder(builder); }</code><technical_language>is this cast needed</technical_language>

Target:
protected void setPRPAINBuilder(Patient query) { PRPAIN201305UV02BuilderImpl builder = new PRPAIN201305UV02BuilderImpl(); builder.setPatient(query); pdMessageDirector.setPRPAIN201305UV02Builder(builder); }
Source:
<code><START> public @ResponseBody Map<String, Object> findGroupsOfUser(@PathVariable Integer userId) { <END> try { Set<UserGroup> userGroupsSet = this.service.getGroupsOfUser(userId); return ResultSet.success(userGroupsSet); } catch (Exception e) { LOG.error("Error finding user with id " + userId + ": " + e.getMessage()); return ResultSet.error("Error finding user with id " + userId); } }</code><technical_language>this is a REST interface return entities, Map<String, Objects, is based ResultSet.success(...), is Ext-JS specific format, it</technical_language>

Target:
public ResponseEntity<Set<UserGroup>> findGroupsOfUser(@PathVariable Integer userId) { try { Set<UserGroup> userGroupsSet = this.service.getGroupsOfUser(userId); return new ResponseEntity<Set<UserGroup>>(userGroupsSet, HttpStatus.OK); } catch (Exception e) { LOG.error("Error finding user with id " + userId + ": " + e.getMessage()); return new ResponseEntity<Set<UserGroup>>(HttpStatus.NOT_FOUND); } }
Source:
<code>public void onCollide(ICollidable other) { if (other instanceof IEatable) { IEatable eatable = (IEatable) other; if (eatable.canBeEatenBy(this)) { eatable.eat(); this.addPoints((int) (eatable.getSize() / 200)); <START> double dSize = settings.getInteger("GROWTH_SPEED") * eatable.getSize() / getSize(); <END> getBoundingArea().increaseSize(dSize); State old = getState(); notifyObservers(old, getState(), "EnemyKill"); } if (this.canBeEatenBy(eatable)) { eatable.eat(this); } } }</code><technical_language>getGrowthSpeed() instead, also, is this calculation double precision? <organisation</technical_language>

Target:
public void onCollide(ICollidable other) { if (other instanceof IEatable) { IEatable eatable = (IEatable) other; if (eatable.canBeEatenBy(this)) { eatable.eat(); this.addPoints((int) (eatable.getSize() / 200)); double dSize = getGrowthSpeed() * eatable.getSize() / getSize(); getBoundingArea().increaseSize(dSize); State old = getState(); notifyObservers(old, getState(), "EnemyKill"); } if (this.canBeEatenBy(eatable)) { eatable.eat(this); } } }
Source:
<code>private synchronized void notifyListeners(CruiseConfig newCruiseConfig) { LOGGER.info("About to notify config listeners"); for (ConfigChangedListener listener : listeners) { try { long startTime = System.currentTimeMillis(); listener.onConfigChange(newCruiseConfig); <START> LOGGER.debug("Notifying " + listener.getClass() + " took (in ms): " + (System.currentTimeMillis() - startTime)); <END> } catch (Exception e) { LOGGER.error("Failed to fire config changed event for listener: " + listener, e); } } LOGGER.info("Finished notifying all listeners"); }</code><technical_language>Wrap this in a isDebugEnabled() ? String.format? slf4j instead done GoConfigDao</technical_language>

Target:
private synchronized void notifyListeners(CruiseConfig newCruiseConfig) { LOGGER.info("About to notify config listeners"); for (ConfigChangedListener listener : listeners) { try { long startTime = System.currentTimeMillis(); listener.onConfigChange(newCruiseConfig); LOGGER.debug("Notifying took (in ms): {}", listener.getClass(), (System.currentTimeMillis() - startTime)); } catch (Exception e) { LOGGER.error("Failed to fire config changed event for listener: " + listener, e); } } LOGGER.info("Finished notifying all listeners"); }
Source:
<code>public boolean deleteTemplate(DeleteTemplateCmd cmd) { Long templateId = cmd.getId(); Account caller = CallContext.current().getCallingAccount(); VMTemplateVO template = _tmpltDao.findById(templateId); if (template == null) { throw new InvalidParameterValueException("unable to find template with id " + templateId); } List<VMInstanceVO> vmInstanceVOList; if(cmd.getZoneId() != null) { vmInstanceVOList = _vmInstanceDao.listNonExpungedByZoneAndTemplate(cmd.getZoneId(), templateId); } else { vmInstanceVOList = _vmInstanceDao.listNonExpungedByTemplate(templateId); } if(!cmd.isForced() && CollectionUtils.isNotEmpty(vmInstanceVOList)) { StringBuilder s = new StringBuilder("Unable to delete template with id: " + templateId + " because some VM instances are using it. "); for (VMInstanceVO elm : vmInstanceVOList) { s.append(elm.getInstanceName() + ", "); } s_logger.warn(s.substring(0,s.length()-2)); <START> throw new InvalidParameterValueException(s.substring(0,s.length()-2)); <END> } _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template); if (template.getFormat() == ImageFormat.ISO) { throw new InvalidParameterValueException("Please specify a valid template."); } TemplateAdapter adapter = getAdapter(template.getHypervisorType()); TemplateProfile profile = adapter.prepareDelete(cmd); return adapter.delete(profile); }</code><technical_language>Lines 1187-1193 replaced DRY improve clarity: java final String message = String.format("Unable delete template id: %1$s VM instances: [%2$s] it.", templateId, Joiner.on(",").join(vmInstanceVOList)); s_logger.warn(message); throw new InvalidParameterValueException(message);</technical_language>

Target:
public boolean deleteTemplate(DeleteTemplateCmd cmd) { Long templateId = cmd.getId(); Account caller = CallContext.current().getCallingAccount(); VMTemplateVO template = _tmpltDao.findById(templateId); if (template == null) { throw new InvalidParameterValueException("unable to find template with id " + templateId); } List<VMInstanceVO> vmInstanceVOList; if(cmd.getZoneId() != null) { vmInstanceVOList = _vmInstanceDao.listNonExpungedByZoneAndTemplate(cmd.getZoneId(), templateId); } else { vmInstanceVOList = _vmInstanceDao.listNonExpungedByTemplate(templateId); } if(!cmd.isForced() && CollectionUtils.isNotEmpty(vmInstanceVOList)) { final String message = String.format("Unable to delete template with id: %1$s because VM instances: [%2$s] are using it.", templateId, Joiner.on(",").join(vmInstanceVOList)); s_logger.warn(message); throw new InvalidParameterValueException(message); } _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template); if (template.getFormat() == ImageFormat.ISO) { throw new InvalidParameterValueException("Please specify a valid template."); } TemplateAdapter adapter = getAdapter(template.getHypervisorType()); TemplateProfile profile = adapter.prepareDelete(cmd); return adapter.delete(profile); }
Source:
<code>public int hashCode() { <START> <END> return Objects.hash( routers, ttl ); }</code><technical_language>odd newline</technical_language>

Target:
public int hashCode() { return Objects.hash( routers, timeToLiveMillis ); }
Source:
<code>private int getPinFromHeader(int header) { <START> return header & 0x0F; <END> }</code><technical_language>please put "magic numbers" in a static variable e.g. BITMASK_PIN</technical_language>

Target:
private int getPinFromHeader(int header) { return header & BITMASK_PIN; }
Source:
<code><START> public void testPartialQueryLoadsInBulkMode() throws XPathSyntaxException, UnfullfilledRequirementsException, <END> XmlPullParserException, IOException, InvalidStructureException { ParseUtils.parseIntoSandbox(getClass().getResourceAsStream("/indexed_fixture/partial_lookup_load_body_large_scope.xml"), sandbox); EvaluationContext ec = MockDataUtils.buildContextWithInstance(sandbox, "testfixture", "jr://fixture/testfixture"); EvaluationContext ecForTest = ec.spawnWithCleanLifecycle(); QueryContext context = ecForTest.getCurrentQueryContext(); ScopeLimitedReferenceRequestCache cache = context.getQueryCache(ScopeLimitedReferenceRequestCache.class); String exprString = "instance('testfixture')/test/entry[@filter_attribute = 'pass'][true() and filter_one = 'pass']/name"; XPathExpression expr = XPathParseTool.parseXPath(exprString); cache.addTreeReferencesToLimitedScope(new TreeReferenceAccumulatingAnalyzer(ecForTest).accumulate(expr)); CaseTestUtils.xpathEvalAndAssert(ecForTest, exprString, "succeed"); }</code><technical_language>gathering this test is supposed test a code path test. clear disparate path is, I checks code path executed</technical_language>

Target:
public void testPartialQueryLoadsInBulkMode() throws XPathSyntaxException, UnfullfilledRequirementsException, XmlPullParserException, IOException, InvalidStructureException { ParseUtils.parseIntoSandbox(getClass().getResourceAsStream("/indexed_fixture/partial_lookup_load_body_large_scope.xml"), sandbox); doPartialLookupTest(); }
Source:
<code>public StageResult processAckOnMaster(List<DistStageAck> acks) { StageResult result = super.processAckOnMaster(acks); if (result.isError()) return result; Report report = masterState.getReport(); <START> Report.Test test = report.createTest("Stream_Stage", null, true); <END> int testIteration = test.getIterations().size(); Map<Integer, Report.SlaveResult> numberOfResultKeysResult = new HashMap<>(); Map<Integer, Report.SlaveResult> durationsResult = new HashMap<>(); for (StreamStageAck ack : Projections.instancesOf(acks, StreamStageAck.class)) { if (ack.stats != null) { DataOperationStats opStats = (DataOperationStats) ack.stats.getOperationsStats().get(Streamable.STREAMABLE.name); opStats.setTotalBytes((Long) masterState.get(totalBytesKey)); test.addStatistics(testIteration, ack.getSlaveIndex(), Collections.singletonList(ack.stats)); durationsResult.put(ack.getSlaveIndex(), new Report.SlaveResult(opStats.getResponseTimes(), false)); test.addResult(testIteration, new Report.TestResult("Stream task durations", durationsResult, "", false)); } if (ack.numberOfResultKeys != null) { numberOfResultKeysResult.put(ack.getSlaveIndex(), new Report.SlaveResult(ack.numberOfResultKeys, false)); test.addResult(testIteration, new Report.TestResult("Key count in stream result map", numberOfResultKeysResult, "", false)); } } return StageResult.SUCCESS; }</code><technical_language>Please test name property (testName consistent other stages)</technical_language>

Target:
public StageResult processAckOnMaster(List<DistStageAck> acks) { StageResult result = super.processAckOnMaster(acks); if (result.isError()) return result; Report report = masterState.getReport(); Report.Test test = report.createTest(testName, null, true); int testIteration = test.getIterations().size(); Map<Integer, Report.SlaveResult> numberOfResultKeysResult = new HashMap<>(); Map<Integer, Report.SlaveResult> durationsResult = new HashMap<>(); for (StreamStageAck ack : Projections.instancesOf(acks, StreamStageAck.class)) { if (ack.stats != null) { DataOperationStats opStats = (DataOperationStats) ack.stats.getOperationsStats().get(Streamable.STREAMABLE.name); opStats.setTotalBytes((Long) masterState.get(totalBytesKey)); test.addStatistics(testIteration, ack.getSlaveIndex(), Collections.singletonList(ack.stats)); durationsResult.put(ack.getSlaveIndex(), new Report.SlaveResult(opStats.getResponseTimes(), false)); test.addResult(testIteration, new Report.TestResult("Stream task durations on slave" + ack.getSlaveIndex(), durationsResult, "", false)); } if (ack.numberOfResultKeys != null) { numberOfResultKeysResult.put(ack.getSlaveIndex(), new Report.SlaveResult(ack.numberOfResultKeys, false)); test.addResult(testIteration, new Report.TestResult("Key count in stream result map on slave" + ack.getSlaveIndex(), numberOfResultKeysResult, "", false)); } } return StageResult.SUCCESS; }
Source:
<code>public void onMessage(Message message) { try { <START> log.infof("onMessage received message: %s '%s'", message, ((TextMessage) message).getText()); <END> final Destination replyTo = message.getJMSReplyTo(); if (replyTo == null) { throw new RuntimeException("ReplyTo info in message was not specified" + " and bean does not know where to reply to"); } TxTestUtil.enlistTestXAResource(tm.getTransaction()); try ( JMSContext context = factory.createContext() ) { context.createProducer() .setJMSCorrelationID(message.getJMSMessageID()) .send(replyTo, REPLY_PREFIX + ((TextMessage) message).getText()); } TxTestUtil.waitForTimeout(tm); } catch (Exception e) { throw new RuntimeException("onMessage method execution failed", e); } }</code><technical_language>log.trace if</technical_language>

Target:
public void onMessage(Message message) { try { log.tracef("onMessage received message: %s '%s'", message, ((TextMessage) message).getText()); final Destination replyTo = message.getJMSReplyTo(); if (replyTo == null) { throw new RuntimeException("ReplyTo info in message was not specified" + " and bean does not know where to reply to"); } TxTestUtil.enlistTestXAResource(tm.getTransaction()); try ( JMSContext context = factory.createContext() ) { context.createProducer() .setJMSCorrelationID(message.getJMSMessageID()) .send(replyTo, REPLY_PREFIX + ((TextMessage) message).getText()); } TxTestUtil.waitForTimeout(tm); } catch (Exception e) { throw new RuntimeException("onMessage method execution failed", e); } }
Source:
<code>public GridH2Table( CreateTableData createTblData, GridH2RowDescriptor desc, H2TableDescriptor tblDesc, GridCacheContextInfo cacheInfo ) { super(createTblData); assert tblDesc != null; this.desc = desc; this.cacheInfo = cacheInfo; affKeyCol = calculateAffinityKeyColumn(); affKeyColIsKey = affKeyCol != null && desc.isKeyColumn(affKeyCol.column.getColumnId()); identifier = new QueryTable(getSchema().getName(), getName()); identifierStr = identifier.schema() + "." + identifier.table(); idxs = tblDesc.createSystemIndexes(this); assert idxs != null; List<Index> clones = new ArrayList<>(idxs.size()); for (Index index : idxs) { Index clone = createDuplicateIndexIfNeeded(index); if (clone != null) clones.add(clone); } idxs.addAll(clones); boolean hasHashIndex = idxs.size() >= 2 && index(0).getIndexType().isHash(); if (hasHashIndex) idxs.add(0, new H2TableScanIndex(this, index(1), index(0))); else idxs.add(0, new H2TableScanIndex(this, index(0), null)); pkIndexPos = hasHashIndex ? 2 : 1; sysIdxsCnt = idxs.size(); lock = new ReentrantReadWriteLock(); <START> if (hasHashIndex) { END> long totalTblSize = rowCountAllSegments(false); size.add(totalTblSize); } tblStats = new TableStatistics(0, 0); }</code><technical_language>I propose check direct sign 'cacheInfo.affinityNode()' instead of indirect one</technical_language>

Target:
public GridH2Table( CreateTableData createTblData, GridH2RowDescriptor desc, H2TableDescriptor tblDesc, GridCacheContextInfo cacheInfo ) { super(createTblData); assert tblDesc != null; this.desc = desc; this.cacheInfo = cacheInfo; affKeyCol = calculateAffinityKeyColumn(); affKeyColIsKey = affKeyCol != null && desc.isKeyColumn(affKeyCol.column.getColumnId()); identifier = new QueryTable(getSchema().getName(), getName()); identifierStr = identifier.schema() + "." + identifier.table(); idxs = tblDesc.createSystemIndexes(this); assert idxs != null; List<Index> clones = new ArrayList<>(idxs.size()); for (Index index : idxs) { Index clone = createDuplicateIndexIfNeeded(index); if (clone != null) clones.add(clone); } idxs.addAll(clones); boolean hasHashIndex = idxs.size() >= 2 && index(0).getIndexType().isHash(); if (hasHashIndex) idxs.add(0, new H2TableScanIndex(this, index(1), index(0))); else idxs.add(0, new H2TableScanIndex(this, index(0), null)); pkIndexPos = hasHashIndex ? 2 : 1; sysIdxsCnt = idxs.size(); lock = new ReentrantReadWriteLock(); if (cacheInfo.affinityNode()) { long totalTblSize = rowCount(false); size.add(totalTblSize); } tblStats = new TableStatistics(0, 0); }
Source:
<code>private void checkConnection() { Boolean hasRemoteSrvNodes = null; long elapsed = (lastRingMsgSentTime + U.millisToNanos(connCheckInterval)) - System.nanoTime(); if (elapsed > 0) return; if (hasRemoteSrvNodes == null) hasRemoteSrvNodes = ring.hasRemoteServerNodes(); <START> if (hasRemoteSrvNodes) <END> sendMessageAcrossRing(new TcpDiscoveryConnectionCheckMessage(locNode)); }</code><technical_language>call updateLastSentMessageTime method well</technical_language>

Target:
private void checkConnection() { long elapsed = (lastRingMsgSentTime + U.millisToNanos(connCheckInterval)) - System.nanoTime(); if (elapsed > 0) return; if (ring.hasRemoteServerNodes()) sendMessageAcrossRing(new TcpDiscoveryConnectionCheckMessage(locNode)); }
Source:
<code>public static TileEntity getBlockTile(IBlockAccess world, BlockPos pos) { <START> return world instanceof ChunkCache ? ((ChunkCache) world).getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK) : world.getTileEntity(pos); <END> }</code><technical_language>leave world bounds check? game crash if passed y == -1</technical_language>

Target:
public static TileEntity getBlockTile(IBlockAccess world, BlockPos pos) { if (pos.getY() < 0) { Game.log(Level.INFO, "Attempted to access tile entity in an invalid position"); } return world instanceof ChunkCache ? ((ChunkCache) world).getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK) : world.getTileEntity(pos); }
Source:
<code>public void fooMethod() { <START> for(int i = 1, J = 1; i <10; i++) { <END> } int i = 0; for(int index = 1; index < 10; index++) { } for(int Index = 1; Index < 10; Index++) { } int index = 1; for(; index < 10; index++) { } for(; i < 12; i++) { } Map<String, String> map = new HashMap<String, String>(); for (Map.Entry<String, String> e : map.entrySet()) { } for (Map.Entry<String, String> E : map.entrySet()) { } }</code><technical_language>update in tests is small, I expected more updates. Please provide links lines in Input files covers cases discussed in issue in doc examples</technical_language>

Target:
public void fooMethod() { for(int i = 1; i <10; i++) { int j = 1; } for(int K = 1; K < 10; K++) { int A = 1; } int i = 0; for(int index = 1; index < 10; index++) { } for(int Index = 1; Index < 10; Index++) { } int index = 1; for(; index < 10; index++) { } for(; i < 12; i++) { } Map<String, String> map = new HashMap<String, String>(); for (Map.Entry<String, String> e : map.entrySet()) { String a = ""; } for (Map.Entry<String, String> E : map.entrySet()) { String B = ""; } }
Source:
<code>public void testGetPreviousOffsets() throws IOException, InterruptedException, CopycatException { Properties props = createProps(); HdfsSinkConnectorConfig connectorConfig = new HdfsSinkConnectorConfig(props); String topicsDir = connectorConfig.getString(HdfsSinkConnectorConfig.TOPIC_DIR_CONFIG); String topic = "topic"; int partition = 0; TopicPartition topicPart = new TopicPartition(topic, partition); long[] startOffsets = {0, 3}; long[] endOffsets = {2, 5}; for (int i = 0; i < startOffsets.length; ++i) { <START> Path <END> path = new Path(FileUtils.committedFileName(url, topicsDir, topicPart, startOffsets[i], endOffsets[i])); fs.createNewFile(path); } Path path = new Path(FileUtils.tempFileName(url, topicsDir, topicPart)); fs.createNewFile(path); path = new Path(FileUtils.fileName(url, topicsDir, topicPart, "abcd")); fs.createNewFile(path); HdfsWriter hdfsWriter = new HdfsWriter(connectorConfig); Map<TopicPartition, Long> previousOffsets = hdfsWriter.getPreviousOffsets(); assertTrue(previousOffsets.containsKey(topicPart)); long previousOffset = previousOffsets.get(topicPart); assertEquals(previousOffset, 6L); hdfsWriter.close(); }</code><technical_language>Nit, clean formatting of lines</technical_language>

Target:
public void testGetPreviousOffsets() throws Exception { long[] startOffsets = {0, 3}; long[] endOffsets = {2, 5}; for (int i = 0; i < startOffsets.length; ++i) { Path path = new Path(FileUtils.committedFileName(url, topicsDir, TOPIC_PARTITION, startOffsets[i], endOffsets[i])); fs.createNewFile(path); } Path path = new Path(FileUtils.tempFileName(url, topicsDir, TOPIC_PARTITION)); fs.createNewFile(path); path = new Path(FileUtils.fileName(url, topicsDir, TOPIC_PARTITION, "abcd")); fs.createNewFile(path); HdfsWriter hdfsWriter = new HdfsWriter(connectorConfig, context, avroData); hdfsWriter.recover(TOPIC_PARTITION); Map<TopicPartition, Long> committedOffsets = hdfsWriter.getCommittedOffsets(); assertTrue(committedOffsets.containsKey(TOPIC_PARTITION)); long previousOffset = committedOffsets.get(TOPIC_PARTITION); assertEquals(previousOffset, 5L); hdfsWriter.close(); }
Source:
<code>public CruelCelebrant(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{W}{B}"); this.subtype.add(SubType.VAMPIRE); this.power = new MageInt(1); this.toughness = new MageInt(2); Ability ability = new DiesThisOrAnotherCreatureOrPlaneswalkerTriggeredAbility(new LoseLifeOpponentsEffect(1), false, filter); <START> ability.addEffect(new GainLifeEffect(1)); <END> this.addAbility(ability); }</code><technical_language>want .concatBy() method add "and" this effect's text</technical_language>

Target:
public CruelCelebrant(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{W}{B}"); this.subtype.add(SubType.VAMPIRE); this.power = new MageInt(1); this.toughness = new MageInt(2); Ability ability = new DiesThisOrAnotherCreatureOrPlaneswalkerTriggeredAbility(new LoseLifeOpponentsEffect(1), false, filter); ability.addEffect(new GainLifeEffect(1).concatBy("and")); this.addAbility(ability); }
Source:
<code>public CertificateValidator validateTimestamps(boolean isValidationEnabled) throws GeneralSecurityException { if (!isValidationEnabled) { return this; } X509Certificate x509Certificate = _certChain[_certChain.length - 1]; <START> if (x509Certificate.getNotBefore().getTime() > Instant.now().toEpochMilli()) { <END> String message = "certificate is not valid yet: " + x509Certificate.getNotBefore().toInstant().toString(); throw new GeneralSecurityException(message); } if (x509Certificate.getNotAfter().getTime() < Instant.now().toEpochMilli()) { String message = "certificate has expired on: " + x509Certificate.getNotAfter().toInstant().toString(); throw new GeneralSecurityException(message); } return this; }</code><technical_language>org.keycloak.common.util.Time supports tweaking time for testing purposes</technical_language>

Target:
public CertificateValidator validateTimestamps(boolean isValidationEnabled) throws GeneralSecurityException { if (!isValidationEnabled) { return this; } for (int i = 0; i < _certChain.length; i++) { X509Certificate x509Certificate = _certChain[i]; if (x509Certificate.getNotBefore().getTime() > Time.currentTimeMillis()) { String serialNumber = x509Certificate.getSerialNumber().toString(16).replaceAll("..(?!$)", "$0 "); String message = "certificate with serialnumber '" + serialNumber + "' is not valid yet: " + x509Certificate.getNotBefore().toString(); throw new GeneralSecurityException(message); } if (x509Certificate.getNotAfter().getTime() < Time.currentTimeMillis()) { String serialNumber = x509Certificate.getSerialNumber().toString(16).replaceAll("..(?!$)", "$0 "); String message = "certificate with serialnumber '" + serialNumber + "' has expired on: " + x509Certificate.getNotAfter().toString(); throw new GeneralSecurityException(message); } } return this; }
Source:
<code>public void setMinMaxFromBytes(byte[] minBytes, byte[] maxBytes) { max = Binary.fromUnmodifiedByteArray(maxBytes); <START> min = Binary.fromUnmodifiedByteArray(minBytes); <END> this.markAsNotEmpty(); }</code><technical_language>Do this is called constant byte buffers reused byte buffers</technical_language>

Target:
public void setMinMaxFromBytes(byte[] minBytes, byte[] maxBytes) { max = Binary.fromReusedByteArray(maxBytes); min = Binary.fromReusedByteArray(minBytes); this.markAsNotEmpty(); }
Source:
<code>public WebSocketMessagePanel(ChannelSortedListModel channelsModel, JToolBar controlToolbar, HttpPanel messagePanel, WebSocketPanelSender sender) throws IllegalArgumentException { super(new BorderLayout()); if (messagePanel == null) { throw new IllegalArgumentException("The request panel cannot be null."); } this.messagePanel = messagePanel; wsUiHelper = new WebSocketUiHelper(); wsUiHelper.setChannelsModel(channelsModel); controlToolbar.add(wsUiHelper.getChannelLabel()); controlToolbar.add(wsUiHelper.getChannelSingleSelect()); wsUiHelper.getChannelSingleSelect().setSelectedIndex(0); addWebSocketReopenListener(sender); JButton btnReopen = getBtnReopen(sender); JButton btnReopenEdit = getBtnReopenEdit(sender); controlToolbar.add(btnReopen); <START> controlToolbar.add(btnReopenEdit); <END> wsUiHelper.disableButtonsWhenComboBoxSelectedNull(btnReopen,btnReopenEdit); controlToolbar.addSeparator(new Dimension(15, 21)); controlToolbar.add(wsUiHelper.getOpcodeLabel()); controlToolbar.add(wsUiHelper.getOpcodeSingleSelect()); wsUiHelper.getOpcodeSingleSelect().setSelectedItem(WebSocketMessage.opcode2string(WebSocketMessage.OPCODE_TEXT)); controlToolbar.addSeparator(new Dimension(15, 21)); controlToolbar.add(wsUiHelper.getDirectionLabel()); controlToolbar.add(wsUiHelper.getDirectionSingleSelect()); }</code><technical_language>Instead of this in steps controlToolbar.add(getBtnReopen(sender));</technical_language>

Target:
public WebSocketMessagePanel(ChannelSortedListModel channelsModel, JToolBar controlToolbar, HttpPanel messagePanel, WebSocketPanelSender sender) throws IllegalArgumentException { super(new BorderLayout()); if (messagePanel == null) { throw new IllegalArgumentException("The request panel cannot be null."); } this.messagePanel = messagePanel; this.sender = sender; wsUiHelper = new WebSocketUiHelper(); wsUiHelper.setChannelsModel(channelsModel); setControlToolbar(controlToolbar); }
Source:
<code>private void rejectDeathDateIfBeforeBirthDate(Errors errors, Date deathdate, Date birthdate, String dateField) { if (deathdate.before(birthdate)) { <START> errors.rejectValue(dateField, "error.date.nonsensical"); <END> } }</code><technical_language>a more specific error message generic nonsensical date message? shows exact problem is</technical_language>

Target:
private void rejectDeathDateIfBeforeBirthDate(Errors errors, Date deathdate, Date birthdate, String dateField) { if (deathdate.before(birthdate)) { errors.rejectValue(dateField, "error.deathdate.before.birthdate"); } }
Source:
<code>private void broadcastGlobalMinimumClock() { if (!minimumClockWorkers.isEmpty()) { throw new RuntimeException("minimum worker clock list should be empty and updated now"); } for (final Map.Entry<String, Integer> elem : workerClockMap.entrySet()) { final String workerId = elem.getKey(); try { final byte[] data = codec.encode(getBroadcastGlobalMinimumClockMessage(globalMinimumClock)); aggregationMaster.send(AGGREGATION_CLIENT_NAME, workerId, data); } catch (final NetworkException e) { <START> LOG.log(Level.INFO, "Target worker failed to receive global minimum clock message", e); <END> } if (elem.getValue() == globalMinimumClock) { minimumClockWorkers.add(workerId); } } }</code><technical_language>Other exception handling choices, retrying message sending throwing exception possible. explain chose this policy deal NetworkExcpetion</technical_language>

Target:
private void broadcastGlobalMinimumClock() { if (!minimumClockWorkers.isEmpty()) { throw new RuntimeException("Minimum worker clock list should be empty and updated now"); } for (final Map.Entry<String, Integer> elem : workerClockMap.entrySet()) { final String workerId = elem.getKey(); int retryCount = 0; while (true) { if (retryCount++ > MAXIMUM_RETRY_COUNTS) { throw new RuntimeException(String.format("Sending global minimum clock message to %s has failed %d times", workerId, MAXIMUM_RETRY_COUNTS + 1)); } try { final byte[] data = codec.encode(getBroadcastMinClockMessage(globalMinimumClock)); aggregationMaster.send(AGGREGATION_CLIENT_NAME, workerId, data); break; } catch (final NetworkException e) { LOG.log(Level.INFO, String.format("ClockManager failed to send global minimum clock message to %s", workerId), e); } } if (elem.getValue() == globalMinimumClock) { minimumClockWorkers.add(workerId); } } }
Source:
<code>public AccountPB readFrom(ProtoStreamReader reader) throws IOException { int id = reader.readInt("id"); String description = reader.readString("description"); long creationDate = reader.readLong("creationDate"); Limits limits = reader.readObject("limits", LimitsPB.class); Limits hardLimits = reader.readObject("hardLimits", LimitsPB.class); List<byte[]> blurb = reader.readCollection("blurb", new ArrayList<>(), byte[].class); <START> List<Account.Currency> currencies = reader.readCollection("currencies", new ArrayList<>(), Account.Currency.class); <END> AccountPB account = new AccountPB(); account.setId(id); account.setDescription(description); account.setCreationDate(new Date(creationDate)); account.setLimits(limits); account.setHardLimits(hardLimits); account.setBlurb(blurb); account.setCurrencies(currencies); return account; }</code><technical_language>this in a places (moving array list), issue</technical_language>

Target:
public AccountPB readFrom(ProtoStreamReader reader) throws IOException { int id = reader.readInt("id"); String description = reader.readString("description"); long creationDate = reader.readLong("creationDate"); Limits limits = reader.readObject("limits", LimitsPB.class); Limits hardLimits = reader.readObject("hardLimits", LimitsPB.class); List<byte[]> blurb = reader.readCollection("blurb", new ArrayList<>(), byte[].class); Account.Currency[] currencies = reader.readArray("currencies", Account.Currency.class); AccountPB account = new AccountPB(); account.setId(id); account.setDescription(description); account.setCreationDate(new Date(creationDate)); account.setLimits(limits); account.setHardLimits(hardLimits); account.setBlurb(blurb); account.setCurrencies(currencies); return account; }
Source:
<code>public static void addRecoveryListenerIfNecessary(Channel channel) { if (channel instanceof ChannelProxy) { if (((ChannelProxy) channel).getTargetChannel() instanceof AutorecoveringChannel) { <START> AutorecoveringChannel autorecoveringChannel = (AutorecoveringChannel) ((ChannelProxy) channel) <END> .getTargetChannel(); if (hasListener.putIfAbsent(autorecoveringChannel, Boolean.TRUE) == null) { autorecoveringChannel.addRecoveryListener(INSTANCE); } } } }</code><technical_language>need deal else variant well? other hand ChannelProxy implement AutorecoveringChannel delegate respectively? I is some overhead disable auto-recovery, fill this cache for nothing..</technical_language>

Target:
public static void addRecoveryListenerIfNecessary(Channel channel) { AutorecoveringChannel autorecoveringChannel = null; if (channel instanceof ChannelProxy) { if (((ChannelProxy) channel).getTargetChannel() instanceof AutorecoveringChannel) { autorecoveringChannel = (AutorecoveringChannel) ((ChannelProxy) channel) .getTargetChannel(); } } else if (channel instanceof AutorecoveringChannel) { autorecoveringChannel = (AutorecoveringChannel) channel; } if (autorecoveringChannel != null && hasListener.putIfAbsent(autorecoveringChannel, Boolean.TRUE) == null) { autorecoveringChannel.addRecoveryListener(INSTANCE); } }
Source:
<code>private static void deleteDir(Path root) { if (root == null || !Files.exists(root)) { return; } try { Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { try { Files.delete(file); } catch (IOException ex) { <START> } <END> return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e != null) { throw e; } try { Files.delete(dir); } catch (IOException ex) { } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { } }</code><technical_language>Is a reason swallowing errors here</technical_language>

Target:
private void deleteDir(Path root) { if (root == null || !Files.exists(root)) { return; } try { Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { try { Files.delete(file); } catch (IOException ex) { log.cantDelete(file.toString(), ex); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { try { Files.delete(dir); } catch (IOException ex) { log.cantDelete(dir.toString(), ex); } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { } }
Source:
<code>public synchronized BreakpointEnabling<MessageReceiverBreakpoint> getReceiverBreakpoint( final FullSourceCoordinate section) { BreakpointEnabling<MessageReceiverBreakpoint> bkp = receiverBreakpoints.computeIfAbsent(section, ss -> new BreakpointEnabling<>(new MessageReceiverBreakpoint(false, section))); if (bkp.isDisabled() && stepping != null) { <START> bkp.setEnabled(stepping.getSteppingTypeOperation(section) == SteppingType.STEP_INTO); <END> } return bkp; }</code><technical_language>is enabling status of breakpoint depending some stepping info? stepping info global? local activity/actor</technical_language>

Target:
public synchronized BreakpointEnabling<SectionBreakpoint> getReceiverBreakpoint( final FullSourceCoordinate section) { return receiverBreakpoints.computeIfAbsent(section, ss -> new BreakpointEnabling<SectionBreakpoint>( new SectionBreakpoint(false, section, BreakpointType.MSG_RECEIVER))); }
Source:
<code>protected Optional<KubernetesNamespaceMeta> fetchNamespace(String name) <START> throws KubernetesClientException, InfrastructureException { <END> try { Project project = clientFactory.createOC().projects().withName(name).get(); return Optional.of(asNamespaceMeta(project)); } catch (KubernetesClientException e) { if (e.getCode() == 403) { return Optional.empty(); } else { throw new InfrastructureException( "Error occurred when tried to fetch default project. Cause: " + e.getMessage(), e); } } }</code><technical_language>KubernetesClientException thrown here</technical_language>

Target:
protected Optional<KubernetesNamespaceMeta> fetchNamespace(String name) throws InfrastructureException { try { Project project = clientFactory.createOC().projects().withName(name).get(); return Optional.of(asNamespaceMeta(project)); } catch (KubernetesClientException e) { if (e.getCode() == 403) { return Optional.empty(); } else { throw new InfrastructureException( "Error occurred when tried to fetch default project. Cause: " + e.getMessage(), e); } } }
Source:
<code>protected UpdateInfo call() throws Exception { <START> RestTemplate restTemplate = new RestTemplate(); LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); headers.add("Accept", "application/vnd.github.v3+json"); HttpEntity<String> entity = new HttpEntity<>(null, headers); ResponseEntity<List<GitHubRelease>> response = restTemplate.exchange(clientProperties.getGitHubRepo().getApiUrl() + PATH_FOR_RELEASE, HttpMethod.GET, entity, new ParameterizedTypeReference<List<GitHubRelease>>() { }); List<GitHubRelease> responseBody = response.getBody(); if (responseBody == null || responseBody.isEmpty()) { return null; } GitHubRelease latestRelease = responseBody.get(0); if (!latestRelease.isPrerelease()) { return null; } <END> GitHubAssets asset; if (org.bridj.Platform.isWindows()) { asset = getAssetOfFileWithEnding(latestRelease, ".exe"); } else if (org.bridj.Platform.isLinux()) { asset = getAssetOfFileWithEnding(latestRelease, ".tar.gz"); } else if (org.bridj.Platform.isMacOSX()) { asset = getAssetOfFileWithEnding(latestRelease, ".tar.gz"); } else { return null; } String version = latestRelease.getTagName().substring(1); return new UpdateInfo( version, asset.getName(), asset.getBrowserDownloadUrl(), asset.getSize(), latestRelease.getReleaseNotes(), latestRelease.isPrerelease() ); }</code><technical_language>1. RestTemplate DI? 2. If need a new one, create in constructor 3. code of setting restTemplate call extracted a separate method for readability</technical_language>

Target:
protected UpdateInfo call() throws Exception { LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); headers.add("Accept", "application/vnd.github.v3+json"); HttpEntity<String> entity = new HttpEntity<>(null, headers); ClientConfiguration clientConfiguration = preferencesService.getRemotePreferences(); ResponseEntity<List<GitHubRelease>> response = restTemplate.exchange(clientConfiguration.getGitHubRepo().getApiUrl() + PATH_FOR_RELEASE, HttpMethod.GET, entity, new ParameterizedTypeReference<List<GitHubRelease>>() { }); List<GitHubRelease> responseBody = response.getBody(); if (responseBody == null || responseBody.isEmpty()) { return null; } GitHubRelease latestRelease = responseBody.get(0); if (!latestRelease.isPrerelease()) { return null; } GitHubAssets asset; if (org.bridj.Platform.isWindows()) { asset = getAssetOfFileWithEnding(latestRelease, ".exe"); } else if (org.bridj.Platform.isLinux()) { asset = getAssetOfFileWithEnding(latestRelease, ".tar.gz"); } else if (org.bridj.Platform.isMacOSX()) { asset = getAssetOfFileWithEnding(latestRelease, ".tar.gz"); } else { return null; } String version = latestRelease.getTagName().substring(1); return new UpdateInfo( version, asset.getName(), asset.getBrowserDownloadUrl(), asset.getSize(), latestRelease.getReleaseNotes(), latestRelease.isPrerelease() ); }
Source:
<code>private void requestChildViewOnScreen(View child) { Rect vitalPortion = new Rect(); child.getDrawingRect(vitalPortion); Rect vitalPortionSaved = new Rect(); child.getDrawingRect(vitalPortionSaved); Rect wholeView = new Rect(); this.getDrawingRect(wholeView); if(mFrameHeight == -1){ <START> child.requestRectangleOnScreen(vitalPortion); <END> } if(wholeView.height() < mFrameHeight) { this.requestRectangleOnScreen(wholeView); return; } int topY = wholeView.top; int bottomY = wholeView.bottom; wholeView.inset(0, (wholeView.height() - mFrameHeight) / 2); wholeView.offsetTo(wholeView.left, topY); this.offsetDescendantRectToMyCoords(child, vitalPortion); if(wholeView.contains(vitalPortion)) { this.requestRectangleOnScreen(wholeView); return; } wholeView.offsetTo(wholeView.left, bottomY - wholeView.height()); if(wholeView.contains(vitalPortion)) { this.requestRectangleOnScreen(wholeView); return; } child.requestRectangleOnScreen(vitalPortionSaved); }</code><technical_language>this function return this point</technical_language>

Target:
private void requestChildViewOnScreen(View child) { Rect vitalPortion = new Rect(); child.getDrawingRect(vitalPortion); Rect vitalPortionSaved = new Rect(); child.getDrawingRect(vitalPortionSaved); Rect wholeView = new Rect(); this.getDrawingRect(wholeView); if(mFrameHeight == -1){ child.requestRectangleOnScreen(vitalPortion); return; } if(wholeView.height() < mFrameHeight) { this.requestRectangleOnScreen(wholeView); return; } int topY = wholeView.top; int bottomY = wholeView.bottom; wholeView.inset(0, (wholeView.height() - mFrameHeight) / 2); wholeView.offsetTo(wholeView.left, topY); this.offsetDescendantRectToMyCoords(child, vitalPortion); if(wholeView.contains(vitalPortion)) { this.requestRectangleOnScreen(wholeView); return; } wholeView.offsetTo(wholeView.left, bottomY - wholeView.height()); if(wholeView.contains(vitalPortion)) { this.requestRectangleOnScreen(wholeView); return; } child.requestRectangleOnScreen(vitalPortionSaved); }