auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> @Test void sortedAgg() { <END> tester(false, new JdbcTest.HrSchema()) .query( "select deptno, " + "max(salary) as max_salary, count(name) as num_employee " + "from emps group by deptno") .withHook(Hook.PLANNER, (Consumer<RelOptPlanner>) planner -> { planner.removeRule(EnumerableRules.ENUMERABLE_AGGREGATE_RULE); planner.addRule(EnumerableRules.ENUMERABLE_SORTED_AGGREGATE_RULE); }) .explainContains( "EnumerableSortedAggregate(group=[{1}], max_salary=[MAX($3)], num_employee=[COUNT($2)])\n" + " EnumerableSort(sort0=[$1], dir0=[ASC])\n" + " EnumerableTableScan(table=[[s, emps]])") .returnsUnordered( "deptno=10; max_salary=11500.0; num_employee=3", "deptno=20; max_salary=8000.0; num_employee=1"); }</code><technical_language>I propose e.g. - group X, Y (several columns) - group X + order X - group X + order Y</technical_language>

Target:
@Test void sortedAgg() { tester(false, new JdbcTest.HrSchema()) .query( "select deptno, " + "max(salary) as max_salary, count(name) as num_employee " + "from emps group by deptno") .withHook(Hook.PLANNER, (Consumer<RelOptPlanner>) planner -> { planner.removeRule(EnumerableRules.ENUMERABLE_AGGREGATE_RULE); planner.addRule(EnumerableRules.ENUMERABLE_SORTED_AGGREGATE_RULE); }) .explainContains( "EnumerableSortedAggregate(group=[{1}], max_salary=[MAX($3)], num_employee=[COUNT($2)])\n" + " EnumerableSort(sort0=[$1], dir0=[ASC])\n" + " EnumerableTableScan(table=[[s, emps]])") .returnsOrdered( "deptno=10; max_salary=11500.0; num_employee=3", "deptno=20; max_salary=8000.0; num_employee=1"); }
Source:
<code>private void validateWildcardPath(String path) { <START> if (!path.matches("^([^*]*\\*){1}[^*]*$") || !path.endsWith("*")) { <END> throw new IllegalStateException("Please provide correct path. Ex demoResources/*"); } }</code><technical_language>this does. i want is if a star, end only. matches is complicated for that</technical_language>

Target:
private void validateWildcardPath(String path) { if (!containsSingleWildcardSymbol(path) || !path.endsWith("*")) { throw new IllegalStateException("Wildcard can only appear at end of classpath: " + path); } }
Source:
<code><START> public static void checkAccessPermission(Field field) { <END> checkAccessPermission(field.getDeclaringClass(), field.getModifiers(), field.isAccessible() ); }</code><technical_language>public needed</technical_language>

Target:
static void checkAccessPermission(Field field) { try { checkAccessPermission(field.getDeclaringClass(), field.getModifiers(), field.isAccessible()); } catch (AccessControlException e) { throw createCacheAccessControlExceptionOf(field, e); } }
Source:
<code>private void sendToRedis(RowMap msg) throws Exception { String messageStr = msg.toJSON(outputConfig); switch (redisType) { case "lpush": jedis.lpush(this.channel, messageStr); break; case "xadd": Map<String, String> message = new HashMap<>(); String jsonKey = this.context.getConfig().redisStreamJsonKey; if (jsonKey == null) { throw new IllegalArgumentException("Stream requires key name for serialized JSON value"); } else { message.put(jsonKey, messageStr); } <START> jedis.xadd(this.channel, new StreamEntryID(), message); <END> break; case "pubsub": default: jedis.publish(this.channel, messageStr); break; } if (logger.isDebugEnabled()) { switch (redisType) { case "lpush": logger.debug("-> queue:" + channel + ", msg:" + msg); break; case "xadd": logger.debug("-> stream:" + channel + ", msg:" + msg); break; case "pubsub": default: logger.debug("-> channel:" + channel + ", msg:" + msg); break; } } this.succeededMessageCount.inc(); this.succeededMessageMeter.mark(); }</code><technical_language>strange Jedis forces generate StreamEntryID -- <LINK_0> vastly preferred method of ID-ing is pass "*" redis generate id. In particular, worry about: > a user explicit ID XADD, ... user ID is greater other ID currently stream, command fail. means producers sending stream screw other up. ... Ah. Ok. source code reading passing StreamEntryID.NEW_ENTRY instead of doing</technical_language>

Target:
private void sendToRedis(RowMap msg) throws Exception { String messageStr = msg.toJSON(outputConfig); switch (redisType) { case "lpush": jedis.lpush(this.channel, messageStr); break; case "xadd": Map<String, String> message = new HashMap<>(); String jsonKey = this.context.getConfig().redisStreamJsonKey; if (jsonKey == null) { throw new IllegalArgumentException("Stream requires key name for serialized JSON value"); } else { message.put(jsonKey, messageStr); } jedis.xadd(this.channel, StreamEntryID.NEW_ENTRY, message); break; case "pubsub": default: jedis.publish(this.channel, messageStr); break; } if (logger.isDebugEnabled()) { switch (redisType) { case "lpush": logger.debug("-> queue:" + channel + ", msg:" + msg); break; case "xadd": logger.debug("-> stream:" + channel + ", msg:" + msg); break; case "pubsub": default: logger.debug("-> channel:" + channel + ", msg:" + msg); break; } } this.succeededMessageCount.inc(); this.succeededMessageMeter.mark(); }
Source:
<code>public static long parseDate(String dateString) { String pattern = ""; if (dateString.length() == 10) { char separator = dateString.charAt(4); pattern = "yyyy" + separator + "MM" + separator + "dd"; } else if (dateString.length() == 8) { char separator = dateString.charAt(2); pattern = "MM" + separator + "dd" + separator + "yy"; } try { <START> Date date = new SimpleDateFormat(pattern).parse(dateString); <END> return date.getTime(); } catch (ParseException e) { return 0L; } }</code><technical_language>I suggest instead java.time package java LocalDate localDate = LocalDate.from(DateTimeFormatter.ofPattern(pattern).parse(dateString)) return localDate.toEpochDay() epoch day means do conversions worry time zones. number of days unix epoch (1970-01-01). print out this value, simply LocalDate.fromEpochDay(epochDay).toString() yyyy-MM-dd format</technical_language>

Target:
public static long parseDate(String dateString) { String pattern = ""; if (dateString.length() == 10) { char separator = dateString.charAt(4); pattern = "yyyy" + separator + "MM" + separator + "dd"; } else if (dateString.length() == 8) { char separator = dateString.charAt(2); pattern = "MM" + separator + "dd" + separator + "yy"; } LocalDate localDate = LocalDate.from(DateTimeFormatter.ofPattern(pattern).parse(dateString)); return localDate.toEpochDay(); }
Source:
<code>public static void refreshProjects(Repository repository, IProgressMonitor monitor) throws CoreException { final IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() .getProjects(); final File parentFile = repository.getWorkDir(); <START> for (IProject p : projects) { <END> final File file = p.getLocation().toFile(); if (file.getAbsolutePath().startsWith(parentFile.getAbsolutePath())) { p.refreshLocal(IResource.DEPTH_INFINITE, monitor); } } }</code><technical_language>put a child monitor here, set number of units of work project has, do 'worked' for of them</technical_language>

Target:
public static void refreshProjects(Repository repository, IProgressMonitor monitor) throws CoreException { final IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() .getProjects(); try { monitor.beginTask(CoreText.ProjectUtil_refreshingProjects, projects.length); final File parentFile = repository.getWorkDir(); for (IProject p : projects) { if (monitor.isCanceled()) break; final File file = p.getLocation().toFile(); if (file.getAbsolutePath().startsWith( parentFile.getAbsolutePath())) { p.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 1)); monitor.worked(1); } } } finally { monitor.done(); } }
Source:
<code>public void setAmount(int amount) throws Throwable { if ((sourceImmutablePolicy == null) || !(sourceImmutablePolicy instanceof MethodAmountPolicy)) { <START> throw new Throwable("Source Policy is not of type method amount policy cannot add amount"); <END> } sourceImmutablePolicy = new MethodAmountPolicy(sourceImmutablePolicy.getDenyRootedJailbroken(), sourceImmutablePolicy.getDenyEmulatorSimulator(), sourceImmutablePolicy.getFences(), amount); }</code><technical_language>Source Policy is of type "method amount" policy add amount</technical_language>

Target:
public void setAmount(int amount) throws Throwable { if ((sourceImmutablePolicy == null) || !(sourceImmutablePolicy instanceof MethodAmountPolicy)) { throw new Throwable("Source Policy is not of type method amount policy and thus cannot add amount"); } sourceImmutablePolicy = new MethodAmountPolicy(sourceImmutablePolicy.getDenyRootedJailbroken(), sourceImmutablePolicy.getDenyEmulatorSimulator(), sourceImmutablePolicy.getFences(), amount); }
Source:
<code>public ScanQuery toScanQuery( final DataSource dataSource, final PlannerContext plannerContext ) { if (grouping != null) { return null; } if (getRowOrder().isEmpty()) { throw new ISE("WTF?! Attempting to convert to Scan query without any columns?"); } final Filtration filtration = Filtration.create(filter).optimize(sourceRowSignature); return new ScanQuery( dataSource, filtration.getQuerySegmentSpec(), selectProjection != null ? VirtualColumns.create(selectProjection.getVirtualColumns()) : VirtualColumns.EMPTY, ScanQuery.RESULT_FORMAT_COMPACTED_LIST, 0, <START> limitSpec == null || limitSpec.getLimit() == Integer.MAX_VALUE ? 0 : limitSpec.getLimit(), <END> filtration.getDimFilter(), Ordering.natural().sortedCopy(ImmutableSet.copyOf(getRowOrder())), false, plannerContext.getQueryContext() ); }</code><technical_language>this 'limit' in ScanQuery is long type, do need change limitSpec.getLimit() long</technical_language>

Target:
public ScanQuery toScanQuery( final DataSource dataSource, final PlannerContext plannerContext ) { if (grouping != null) { return null; } if (limitSpec != null && limitSpec.getColumns().size() > 0) { return null; } if (getRowOrder().isEmpty()) { throw new ISE("WTF?! Attempting to convert to Scan query without any columns?"); } final Filtration filtration = Filtration.create(filter).optimize(sourceRowSignature); final long scanLimit = limitSpec == null || limitSpec.getLimit() == Integer.MAX_VALUE ? 0L : (long) limitSpec.getLimit(); return new ScanQuery( dataSource, filtration.getQuerySegmentSpec(), selectProjection != null ? VirtualColumns.create(selectProjection.getVirtualColumns()) : VirtualColumns.EMPTY, ScanQuery.RESULT_FORMAT_COMPACTED_LIST, 0, scanLimit, filtration.getDimFilter(), Ordering.natural().sortedCopy(ImmutableSet.copyOf(getRowOrder())), false, plannerContext.getQueryContext() ); }
Source:
<code>private void giveFlagToPlayer(EntityRef flag, EntityRef player) { BlockComponent blockComponent = flag.getComponent(BlockComponent.class); LASTeamComponent flagTeamComponent = flag.getComponent(LASTeamComponent.class); <START> inventoryManager.giveItem(player, EntityRef.NULL, blockFactory.newInstance(blockManager.getBlockFamily(LASUtils.getFlagURI(flagTeamComponent.team)))); <END> player.addComponent(new HasFlagComponent(flagTeamComponent.team)); worldProvider.setBlock(blockComponent.getPosition(), blockManager.getBlock(BlockManager.AIR_ID)); flag.destroy(); }</code><technical_language>Initialise blockFactory here, right usage</technical_language>

Target:
private void giveFlagToPlayer(EntityRef flag, EntityRef player) { BlockComponent blockComponent = flag.getComponent(BlockComponent.class); LASTeamComponent flagTeamComponent = flag.getComponent(LASTeamComponent.class); BlockItemFactory blockFactory = new BlockItemFactory(entityManager); inventoryManager.giveItem(player, EntityRef.NULL, blockFactory.newInstance(blockManager.getBlockFamily(LASUtils.getFlagURI(flagTeamComponent.team)))); worldProvider.setBlock(blockComponent.getPosition(), blockManager.getBlock(BlockManager.AIR_ID)); flag.destroy(); }
Source:
<code>public Response intercept(Chain chain) throws IOException { DetachedSpan attemptSpan = chain.request().tag(AttemptSpan.class).attemptSpan(); DetachedSpan dispatcherSpan = chain.request().tag(SettableDispatcherSpan.class).dispatcherSpan(); <START> if (dispatcherSpan == null) { <END> return chain.proceed(chain.request()); } dispatcherSpan.complete(); try { return chain.proceed(chain.request()); } finally { attemptSpan.complete(); chain.request().tag(SettableWaitForBodySpan.class).waitForBodySpan().complete(); } }</code><technical_language>If dispatcher is null a bug in cjr. log some sort of warning</technical_language>

Target:
public Response intercept(Chain chain) throws IOException { DetachedSpan attemptSpan = chain.request().tag(Tags.AttemptSpan.class).attemptSpan(); DetachedSpan dispatcherSpan = chain.request().tag(Tags.SettableDispatcherSpan.class).dispatcherSpan(); if (attemptSpan == null || dispatcherSpan == null) { log.warn("Missing attemptSpan / dispatcherSpan, which will result in missing spans. Likely a " + "conjure-java-runtime bug"); return chain.proceed(chain.request()); } dispatcherSpan.complete(); try { return chain.proceed(chain.request()); } finally { attemptSpan.complete(); chain.request().tag(Tags.SettableWaitForBodySpan.class).waitForBodySpan().complete(); } }
Source:
<code>public int onStartCommand(Intent intent, int flags, int startId) { <START> if (intent != null) { <END> String email = intent.getStringExtra("email"); ClientUser user = YieldsApplication.getUser(); if (user == null || user.getEmail() != email) { YieldsApplication.setUser(new ClientUser(email)); } ServiceRequest connectReq = new UserConnectRequest(YieldsApplication.getUser()); sendRequest(connectReq); } Log.d("Y:" + this.getClass().getName(), "Starting yield service"); return START_STICKY; }</code><technical_language>throwing exception is testing if intent is null</technical_language>

Target:
public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { String email = intent.getStringExtra("email"); if (email == null) { throw new IllegalArgumentException("Intent didn't start the service with an email"); } ClientUser user = YieldsApplication.getUser(); if (user == null || user.getEmail() != email) { YieldsApplication.setUser(new ClientUser(email)); } ServiceRequest connectReq = new UserConnectRequest(YieldsApplication.getUser()); sendRequest(connectReq); } Log.d("Y:" + this.getClass().getName(), "Starting yield service"); return START_STICKY; }
Source:
<code>public static String buildPasswordResetUrl(final String username, final PasswordManagementService passwordManagementService, final CasConfigurationProperties casProperties, final WebApplicationService service) { val token = passwordManagementService.createToken(username); if (StringUtils.isNotBlank(token)) { final StringBuilder restetUrl = new StringBuilder(casProperties.getServer().getPrefix()) .append('/').append(CasWebflowConfigurer.FLOW_ID_LOGIN).append('?') .append(PARAMETER_NAME_TOKEN).append('=').append(token); if (casProperties.getAuthn().getPm().getReset().isAddServiceToPasswordResetUrl() && service != null) { <START> final String encodeServiceUrl = UriUtils.encode(service.getOriginalUrl(), "UTF-8"); <END> restetUrl.append('&').append(PARAMETER_NAME_SERVICE).append('=').append(encodeServiceUrl); } return restetUrl.toString(); } LOGGER.error("Could not create password reset url since no reset token could be generated"); return null; }</code><technical_language>Remove, StandardCharsets.UTF_8</technical_language>

Target:
public static String buildPasswordResetUrl(final String username, final PasswordManagementService passwordManagementService, final CasConfigurationProperties casProperties, final WebApplicationService service) { val token = passwordManagementService.createToken(username); if (StringUtils.isNotBlank(token)) { StringBuilder restetUrl = new StringBuilder(casProperties.getServer().getPrefix()) .append('/').append(CasWebflowConfigurer.FLOW_ID_LOGIN).append('?') .append(PARAMETER_NAME_TOKEN).append('=').append(token); if (service != null) { val encodeServiceUrl = UriUtils.encode(service.getOriginalUrl(), StandardCharsets.UTF_8); restetUrl.append('&').append(CasProtocolConstants.PARAMETER_SERVICE).append('=').append(encodeServiceUrl); } return restetUrl.toString(); } LOGGER.error("Could not create password reset url since no reset token could be generated"); return null; }
Source:
<code>protected String getUserNameForCertificates(final X509Certificate[] certs) throws LoginException { if (certs == null) { throw new LoginException("Client certificates not found. Cannot authenticate."); } String dn = getDistinguishedName(certs); String name = usersByDn.get(dn); if (name == null && regexpByUser != null) { <START> name = getUserByRegexp(dn); <END> } return name; }</code><technical_language>getUserByRegexp is synchronized of usersByDn regexpByUser, ones, not: is reason String getUserByRegexp(String dn) synchronized</technical_language>

Target:
protected String getUserNameForCertificates(final X509Certificate[] certs) throws LoginException { if (certs == null) { throw new LoginException("Client certificates not found. Cannot authenticate."); } String dn = getDistinguishedName(certs); return usersByDn.containsKey(dn) ? usersByDn.get(dn) : getUserByRegexp(dn); }
Source:
<code>protected TestResultSummary run() throws Exception { final long buildTime = build.getTimestamp().getTimeInMillis(); final long timeOnMaster = System.currentTimeMillis(); String location = step.location; if (location == null) { <START> location = "**/target/surefire-reports/TEST-*.xml"; <END> } LOGGER.info("Looking for JUnit tests results in " + location + " in workspace " + workspace); TestResult result = workspace.act(new ParseResultCallable(location, buildTime, timeOnMaster, step.keepLongStdio)); result.tally(); if (result.isEmpty()) { throw new AbortException(Messages.JUnitResultArchiver_ResultIsEmpty()); } synchronized (build) { TestResultAction action = build.getAction(TestResultAction.class); if (action == null) { action = new TestResultAction(build, result, listener); build.addAction(action); } else { result.freeze(action); action.mergeResult(result, listener); build.save(); } if (action.getResult().getFailCount() > 0) { build.setResult(Result.UNSTABLE); } } return new TestResultSummary(result); }</code><technical_language>this field mandatory, if default attribute f:textbox in config.jelly (and/or suggest this in help-location.html)</technical_language>

Target:
protected TestResultSummary run() throws Exception { final long buildTime = build.getTimestamp().getTimeInMillis(); final long timeOnMaster = System.currentTimeMillis(); String location = step.testResults; if (location == null) { location = "**/target/surefire-reports/TEST-*.xml"; } LOGGER.info("Looking for JUnit tests results in " + location + " in workspace " + workspace); TestResult result = workspace.act(new ParseResultCallable(location, buildTime, timeOnMaster, step.keepLongStdio)); result.tally(); if (result.isEmpty()) { throw new AbortException(Messages.JUnitResultArchiver_ResultIsEmpty()); } synchronized (build) { TestResultAction action = build.getAction(TestResultAction.class); if (action == null) { action = new TestResultAction(build, result, listener); build.addAction(action); } else { result.freeze(action); action.mergeResult(result, listener); build.save(); } } return new TestResultSummary(result); }
Source:
<code><START> static public void fixNMandUQ(final SAMRecord record, final ReferenceSequenceFileWalker refSeqWalker, final boolean isBisulfiteSequence){ <END> final byte[] referenceBases = refSeqWalker.get(refSeqWalker.getSequenceDictionary().getSequenceIndex(record.getReferenceName())).getBases(); record.setAttribute(SAMTag.NM.name(), SequenceUtil.calculateSamNmTag(record, referenceBases, 0, isBisulfiteSequence)); if (record.getBaseQualities() != SAMRecord.NULL_QUALS) { record.setAttribute(SAMTag.UQ.name(), SequenceUtil.sumQualitiesOfMismatches(record, referenceBases, 0, isBisulfiteSequence)); } }</code><technical_language>public static? Is keyword ordering important in this codebase</technical_language>

Target:
public static void fixNMandUQ(final SAMRecord record, final ReferenceSequenceFileWalker refSeqWalker, final boolean isBisulfiteSequence) { final byte[] referenceBases = refSeqWalker.get(refSeqWalker.getSequenceDictionary().getSequenceIndex(record.getReferenceName())).getBases(); record.setAttribute(SAMTag.NM.name(), SequenceUtil.calculateSamNmTag(record, referenceBases, 0, isBisulfiteSequence)); if (record.getBaseQualities() != SAMRecord.NULL_QUALS) { record.setAttribute(SAMTag.UQ.name(), SequenceUtil.sumQualitiesOfMismatches(record, referenceBases, 0, isBisulfiteSequence)); } }
Source:
<code>public void onBushGrowth(DelayedActionTriggeredEvent event, EntityRef bush, BushDefinitionComponent bushComponent) { EntityRef newBush = null; <START> if (bushComponent.currentStage < bushComponent.stages.length - 1) { <END> newBush = doBushGrowth(bushComponent, 1); } resetDelay(newBush == null ? bush : newBush, bushComponent.stages[bushComponent.currentStage].minTime, bushComponent.stages[bushComponent.currentStage].maxTime); }</code><technical_language>good isInLastStage(bushComponent), replace this !isInLastStage(bushComponent)</technical_language>

Target:
public void onBushGrowth(DelayedActionTriggeredEvent event, EntityRef bush, BushDefinitionComponent bushComponent) { EntityRef newBush = null; if (!isInLastStage(bushComponent)) { newBush = doBushGrowth(bushComponent, 1); } resetDelay(newBush == null ? bush : newBush, bushComponent.stages[bushComponent.currentStage].minTime, bushComponent.stages[bushComponent.currentStage].maxTime); }
Source:
<code>NotFoundException(Exception innerException) { <START> this(RMResources.NotFound, innerException, new HashMap<>(), null); <END> }</code><technical_language>cast (Map<String, String>) null is instead of creating object</technical_language>

Target:
NotFoundException(Exception innerException) { this(RMResources.NotFound, innerException, (Map<String, String>) null, null); }
Source:
<code><START> private String stringValueOf(int value) { <END> return value != 0 ? String.valueOf(value) : EMPTY_VALUE; }</code><technical_language>consider extracting functionality of stringValueOf(...) some helper/utility class, functionality elsewhere? :cake:</technical_language>

Target:
private String stringValueOf(int value) { return value != 0 ? String.valueOf(NumberFormat.getInstance(Locale.getDefault()).format(value)) : EMPTY_VALUE; }
Source:
<code>public synchronized void detonateBomb(Bomb bomb){ bomb.setDetonated(); for (Point p : grid.getAffectedExplosionSquares(bomb)){ for (Entity entity : grid.get(p)){ if (entity instanceof Player){ <START> if(!((Player) entity).isInvulnerable() && !((Player) entity).isImmuneToBombs()){ <END> killPlayer((Player) entity); } } else if (entity instanceof Bomb && !((Bomb)entity).isDetonated()){ detonateBomb((Bomb)entity); } else if (entity instanceof Enemy){ aiScheduler.removeEnemy((Enemy) entity); grid.remove(entity); } else if (entity.isDestructible()){ grid.remove(entity); } } } }</code><technical_language>I add public boolean BeHurtBy(Entity entity) Player takes flamepass invulnerability account depending type of entity attempting hurt it. logic is more centralized this way</technical_language>

Target:
public synchronized void detonateBomb(Bomb bomb){ bomb.setDetonated(); for (Point p : grid.getAffectedExplosionSquares(bomb)){ for (Entity entity : grid.get(p)){ if (entity instanceof Unit){ if(!((Unit) entity).isImmuneToBombs()){ killUnit((Unit) entity); } } else if (entity instanceof Bomb && !((Bomb)entity).isDetonated()){ detonateBomb((Bomb)entity); } else if (entity.isDestructible()){ grid.remove(entity); } } } }
Source:
<code>private MethodExecutionResult invokeStaticMethod(String methodName, List<String> paths, Object... args) throws Throwable { Method method; int i = methodName.lastIndexOf('.'); if (i >=0) { String className = methodName.substring(0, i); String staticMethodName = methodName.substring(i+1); Class<?> clazz = searchPathsForClass(paths, className); if (clazz != null) { method = findMatchingMethod(new String[]{staticMethodName}, clazz.getMethods(), args.length); <START> return this.invokeMethod(null, method, args); <END> } } return null; }</code><technical_language>is this line indented more? More importantly: I check method is null invoke it..</technical_language>

Target:
private MethodExecutionResult invokeStaticMethod(String methodName, List<String> paths, Object... args) throws Throwable { Method method; int i = methodName.lastIndexOf('.'); if (i >=0) { String className = methodName.substring(0, i); String staticMethodName = methodName.substring(i+1); Class<?> clazz = searchPathsForClass(paths, className); if (clazz != null) { method = findMatchingMethod(new String[]{staticMethodName}, clazz.getMethods(), args.length); if (method != null) { return this.invokeMethod(null, method, args); } else { return MethodExecutionResult.noMethod(staticMethodName + "(static)", clazz, args.length); } } } return null; }
Source:
<code>public void cacheStarted(ComponentRegistry cr, String cacheName) { Configuration configuration = cr.getComponent(Configuration.class); boolean indexingEnabled = configuration.indexing().enabled(); if ( ! indexingEnabled ) { if ( verifyChainContainsQueryInterceptor(cr) ) { throw new IllegalStateException( "It was NOT expected to find the Query interceptor registered in the InterceptorChain as indexing was disabled, but it was found" ); } return; } if ( ! verifyChainContainsQueryInterceptor(cr) ) { throw new IllegalStateException( "It was expected to find the Query interceptor registered in the InterceptorChain but it wasn't found" ); } Cache<?, ?> cache = cr.getComponent(Cache.class); CommandInitializer initializer = cr.getComponent(CommandInitializer.class); EmbeddedCacheManager cacheManager = cr.getGlobalComponentRegistry().getComponent(EmbeddedCacheManager.class); <START> initializer.setCache(cacheManager); <END> QueryBox queryBox = new QueryBox(); queryBox.setCache(cache.getAdvancedCache()); cr.registerComponent(queryBox, QueryBox.class); registerQueryMBeans(cache.getAdvancedCache(), cr, cacheName); }</code><technical_language>update method name setCacheManager IMO</technical_language>

Target:
public void cacheStarted(ComponentRegistry cr, String cacheName) { Configuration configuration = cr.getComponent(Configuration.class); boolean indexingEnabled = configuration.indexing().enabled(); if ( ! indexingEnabled ) { if ( verifyChainContainsQueryInterceptor(cr) ) { throw new IllegalStateException( "It was NOT expected to find the Query interceptor registered in the InterceptorChain as indexing was disabled, but it was found" ); } return; } if ( ! verifyChainContainsQueryInterceptor(cr) ) { throw new IllegalStateException( "It was expected to find the Query interceptor registered in the InterceptorChain but it wasn't found" ); } Cache<?, ?> cache = cr.getComponent(Cache.class); CommandInitializer initializer = cr.getComponent(CommandInitializer.class); EmbeddedCacheManager cacheManager = cr.getGlobalComponentRegistry().getComponent(EmbeddedCacheManager.class); initializer.setCacheManager(cacheManager); QueryBox queryBox = new QueryBox(); queryBox.setCache(cache.getAdvancedCache()); cr.registerComponent(queryBox, QueryBox.class); registerQueryMBeans(cache.getAdvancedCache(), cr, cacheName); }
Source:
<code>void close() { try { m_reader.close(); <START> } catch (IOException e) { } <END> }</code><technical_language>throw IOException caller handle log etc</technical_language>

Target:
public void close() { try { m_reader.close(); } catch (IOException e) { } }
Source:
<code>private RevTag[] getRevTags() { Collection<Ref> revTags = repo.getTags().values(); List<RevTag> tags = new ArrayList<RevTag>(); RevWalk walk = new RevWalk(repo); for (Ref ref : revTags) { try { tags.add(walk.parseTag(repo.resolve(ref.getName()))); } catch (IncorrectObjectTypeException e) { } catch (IOException e) { Activator.logError( UIText.TagAction_unableToResolveHeadObjectId, e); setErrorMessage(UIText.TagAction_unableToResolveHeadObjectId); } } <START> return tags.toArray(new RevTag[tags.size()]); <END> }</code><technical_language>Technically speaking, this mandatory ArrayContentProvider takes array a java.util.Collection. If implementation, call toArray() for you. really, is if want call toArray() later, I thought I point out for information (about ArrayContentProvider works)</technical_language>

Target:
private List<RevTag> getRevTags() { Collection<Ref> revTags = repo.getTags().values(); List<RevTag> tags = new ArrayList<RevTag>(); RevWalk walk = new RevWalk(repo); for (Ref ref : revTags) { try { tags.add(walk.parseTag(repo.resolve(ref.getName()))); } catch (IncorrectObjectTypeException e) { } catch (IOException e) { Activator.logError( UIText.TagAction_unableToResolveHeadObjectId, e); setErrorMessage(UIText.TagAction_unableToResolveHeadObjectId); } } return tags; }
Source:
<code>public <T> boolean putMapping(Class<T> clazz) { if (clazz.isAnnotationPresent(Mapping.class)) { String mappingPath = clazz.getAnnotation(Mapping.class).mappingPath(); if (hasText(mappingPath)) { String mappings = readFileFromClasspath(mappingPath); if (hasText(mappings)) { return putMapping(clazz, mappings); } } else { logger.info("mappingPath in @Mapping has to be defined. Building mappings using @Field"); } } try { <START> final MappingBuilder mappingBuilder = new MappingBuilder(elasticsearchConverter); <END> return putMapping(clazz, mappingBuilder.buildMapping(clazz)); } catch (Exception e) { throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName(), e); } }</code><technical_language>Nit: need for final variables</technical_language>

Target:
public <T> boolean putMapping(Class<T> clazz) { if (clazz.isAnnotationPresent(Mapping.class)) { String mappingPath = clazz.getAnnotation(Mapping.class).mappingPath(); if (hasText(mappingPath)) { String mappings = readFileFromClasspath(mappingPath); if (hasText(mappings)) { return putMapping(clazz, mappings); } } else { logger.info("mappingPath in @Mapping has to be defined. Building mappings using @Field"); } } try { MappingBuilder mappingBuilder = new MappingBuilder(elasticsearchConverter); return putMapping(clazz, mappingBuilder.buildMapping(clazz)); } catch (Exception e) { throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName(), e); } }
Source:
<code>public UUID enqueue(E e) { final Long id = guidGenerator.nextLong(); this.put(id, e); return new UUID(0, id); <START> } <END></code><technical_language>Removing SMR counter simplify this. Nested transactions enqueue expensive needed</technical_language>

Target:
public CorfuRecordId enqueue(E e) { final Long id = guidGenerator.nextLong(); corfuTable.put(id, e); return new CorfuRecordId(0, id); }
Source:
<code>private void parse(RevCommit commit) throws ConfigInvalidException { PatchSet.Id psId = parsePatchSetId(commit); Account.Id accountId = parseIdent(commit); List<PatchSetApproval> psas = approvals.get(psId); Map<String, PatchSetApproval> curr = Maps.newHashMapWithExpectedSize(psas.size()); for (PatchSetApproval psa : psas) { if (psa.getAccountId().equals(accountId)) { curr.put(psa.getLabel(), psa); } } for (String line : commit.getFooterLines(FOOTER_LABEL)) { PatchSetApproval psa = parseApproval(psId, accountId, commit, line); PatchSetApproval old = curr.get(psa.getLabel()); if (old == null || <START> old.getGranted().compareTo(psa.getGranted()) < 0) { <END> curr.put(psa.getLabel(), psa); psas.add(psa); } } for (ReviewerState state : ReviewerState.values()) { for (String line : commit.getFooterLines(state.getFooterKey())) { parseReviewer(state, line); } } }</code><technical_language>conclude this happen</technical_language>

Target:
private void parse(RevCommit commit) throws ConfigInvalidException { PatchSet.Id psId = parsePatchSetId(commit); Account.Id accountId = parseIdent(commit); List<PatchSetApproval> psas = approvals.get(psId); Map<String, PatchSetApproval> curr = Maps.newHashMapWithExpectedSize(psas.size()); for (PatchSetApproval psa : psas) { if (psa.getAccountId().equals(accountId)) { curr.put(psa.getLabel(), psa); } } for (String line : commit.getFooterLines(FOOTER_LABEL)) { PatchSetApproval psa = parseApproval(psId, accountId, commit, line); if (!curr.containsKey(psa.getLabel())) { curr.put(psa.getLabel(), psa); psas.add(psa); } } for (ReviewerState state : ReviewerState.values()) { for (String line : commit.getFooterLines(state.getFooterKey())) { parseReviewer(state, line); } } }
Source:
<code>private static void cleanupOutdatedEsData(EsCommand esCommand) { EsFileSystem esFileSystem = esCommand.getFileSystem(); esFileSystem.getOutdatedDataDirectories().forEach(outdatedDir -> { if (outdatedDir.exists()) { LOG.info("Deleting outdated search index data directory {}", outdatedDir.getAbsolutePath()); try { FileUtils.deleteDirectory(outdatedDir); } catch (IOException e) { LOG.info("Failed to delete outdated search index data directory " + outdatedDir.getAbsolutePath(), e); } } else { <START> LOG.trace("No outdated search index data directory found at {}", outdatedDir.getAbsolutePath()); <END> } }); }</code><technical_language>I dropped. regular case</technical_language>

Target:
private static void cleanupOutdatedEsData(EsCommand esCommand) { EsFileSystem esFileSystem = esCommand.getFileSystem(); esFileSystem.getOutdatedDataDirectories().forEach(outdatedDir -> { if (outdatedDir.exists()) { LOG.info("Deleting outdated search index data directory {}", outdatedDir.getAbsolutePath()); try { FileUtils.deleteDirectory(outdatedDir); } catch (IOException e) { LOG.info("Failed to delete outdated search index data directory " + outdatedDir.getAbsolutePath(), e); } } }); }
Source:
<code>private static Geometry readGeometry(BasicSliceInput input, GeometryType type) { switch (type) { case POINT: return readPoint(input); case MULTI_POINT: return readMultiPoint(input); case LINE_STRING: return readPolyline(input, false); case MULTI_LINE_STRING: return readPolyline(input, true); case POLYGON: return readPolygon(input, false); case MULTI_POLYGON: return readPolygon(input, true); case GEOMETRY_COLLECTION: return readGeometryCollection(input); case ENVELOPE: <START> verify(input.available() > 0); <END> double xMin = input.readDouble(); double yMin = input.readDouble(); double xMax = input.readDouble(); double yMax = input.readDouble(); Coordinate[] coordinates = new Coordinate[5]; coordinates[0] = new Coordinate(xMin, yMin); coordinates[1] = new Coordinate(xMin, yMax); coordinates[2] = new Coordinate(xMax, yMax); coordinates[3] = new Coordinate(xMax, yMin); coordinates[4] = coordinates[0]; return GEOMETRY_FACTORY.createPolygon(coordinates); default: throw new UnsupportedOperationException("Unexpected type: " + type); } }</code><technical_language>extract readEnvelope similar readPolygon</technical_language>

Target:
private static Geometry readGeometry(BasicSliceInput input, GeometryType type) { switch (type) { case POINT: return readPoint(input); case MULTI_POINT: return readMultiPoint(input); case LINE_STRING: return readPolyline(input, false); case MULTI_LINE_STRING: return readPolyline(input, true); case POLYGON: return readPolygon(input, false); case MULTI_POLYGON: return readPolygon(input, true); case GEOMETRY_COLLECTION: return readGeometryCollection(input); case ENVELOPE: return readEnvelope(input); default: throw new UnsupportedOperationException("Unexpected type: " + type); } }
Source:
<code>public java.sql.Array prepareSQLArrayOfNumbers(List<? extends PerunBean> perunBeans, PreparedStatement preparedStatement) throws SQLException, InternalErrorRuntimeException { Connection connection = preparedStatement.getConnection().unwrap(Connection.class); if(Compatibility.isOracle()) { int[] arrayOfBeansIds = perunBeans.stream().mapToInt(PerunBean::getId).toArray(); try { Method createOracleArrayMethod = connection.getClass().getMethod(nameOfOracleArrayMethod, String.class, Object.class); createOracleArrayMethod.setAccessible(true); return (java.sql.Array) createOracleArrayMethod.invoke(connection, AttributesManager.ORACLE_ARRAY_OF_NUMBERS, arrayOfBeansIds); } catch (Exception ex) { throw new InternalErrorRuntimeException("Can't access to method " + nameOfOracleArrayMethod, ex); } } else { <START> Integer[] arrayOfBeansIds = perunBeans.stream().map(PerunBean::getId).collect(Collectors.toList()).stream().toArray(Integer[]::new); <END> return connection.createArrayOf(JDBCType.INTEGER.name(), arrayOfBeansIds); } }</code><technical_language>I shorter: suggestion Integer[] arrayOfBeansIds = perunBeans.stream().map(PerunBean::getId).toArray(Integer[]::new);</technical_language>

Target:
public java.sql.Array prepareSQLArrayOfNumbers(List<? extends PerunBean> perunBeans, PreparedStatement preparedStatement) throws SQLException, InternalErrorRuntimeException { Connection connection = preparedStatement.getConnection().unwrap(Connection.class); if(Compatibility.isOracle()) { int[] arrayOfBeansIds = perunBeans.stream().mapToInt(PerunBean::getId).toArray(); try { Method createOracleArrayMethod = connection.getClass().getMethod(NAME_OF_ORACLE_ARRAY_METHOD, String.class, Object.class); createOracleArrayMethod.setAccessible(true); return (java.sql.Array) createOracleArrayMethod.invoke(connection, AttributesManager.ORACLE_ARRAY_OF_NUMBERS, arrayOfBeansIds); } catch (Exception ex) { throw new InternalErrorRuntimeException("Can't access to method " + NAME_OF_ORACLE_ARRAY_METHOD, ex); } } else { Integer[] arrayOfBeansIds = perunBeans.stream().map(PerunBean::getId).toArray(Integer[]::new); return connection.createArrayOf(JDBCType.INTEGER.name(), arrayOfBeansIds); } }
Source:
<code>public void initTrace(IResource resource, String path, Class<? extends ITmfEvent> eventType) throws TmfTraceException { super.initTrace(resource, path, eventType); Map<String, String> traceEnv = this.getEnvironment(); String tracerName = traceEnv.get("tracer_name"); String tracerMajor = traceEnv.get("tracer_major"); String tracerMinor = traceEnv.get("tracer_minor"); if ("\"perf\"".equals(tracerName)) { fOriginTracer = OriginTracer.PERF; <START> } else if ("\"lttng-modules\"".equals(tracerName) && tracerMajor != null && tracerMinor != null) { END> if (Integer.valueOf(tracerMajor) >= 2) { if (Integer.valueOf(tracerMinor) >= 7) { fOriginTracer = OriginTracer.LTTNG27; } else if (Integer.valueOf(tracerMinor) >= 6) { fOriginTracer = OriginTracer.LTTNG26; } } } else { fOriginTracer = OriginTracer.LTTNG; } }</code><technical_language>this extracted a method, get complicated fast</technical_language>

Target:
public void initTrace(IResource resource, String path, Class<? extends ITmfEvent> eventType) throws TmfTraceException { super.initTrace(resource, path, eventType); fOriginTracer = getTracerFromEnv(this.getEnvironment()); }
Source:
<code>public void onWindowClosing(WindowActionEvent event) { if (!closeImmediately) { if (!isEditorsClean()) { <START> event.setMessage("ask user"); <END> } else if (Boolean.parseBoolean(preferencesManager.getValue(PREF_IDE_GENERAL_TAB_CLOSING))) { event.setMessage("ask user"); } } }</code><technical_language>user 'ask user' message</technical_language>

Target:
public void onWindowClosing(WindowActionEvent event) { if (!closeImmediately) { if (!isEditorsClean()) { event.setMessage(localizationConstant.changesMayBeLost()); } else if (Boolean.parseBoolean(preferencesManager.getValue(PREF_IDE_GENERAL_TAB_CLOSING))) { event.setMessage(localizationConstant.closeTabConfirmation()); } } }
Source:
<code>private void updateAudioSourceFunction() { boolean enabled = UsbManager.containsFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_AUDIO_SOURCE); if (enabled != mAudioSourceEnabled) { <START> int card = -1; <END> int device = -1; if (enabled) { Scanner scanner = null; try { scanner = new Scanner(new File(AUDIO_SOURCE_PCM_PATH)); mAudioSourceCard = scanner.nextInt(); mAudioSourceDevice = scanner.nextInt(); } catch (FileNotFoundException e) { Slog.e(TAG, "could not open audio source PCM file", e); enabled = false; } finally { if (scanner != null) { scanner.close(); } } } mAudioSourceEnabled = enabled; } mUsbAlsaManager.setAccessoryAudioState( mAudioSourceEnabled && mConfigured, mAudioSourceCard, mAudioSourceDevice); }</code><technical_language>unused</technical_language>

Target:
private void updateAudioSourceFunction() { boolean enabled = UsbManager.containsFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_AUDIO_SOURCE); if (enabled != mAudioSourceEnabled) { if (enabled) { Scanner scanner = null; try { scanner = new Scanner(new File(AUDIO_SOURCE_PCM_PATH)); mAudioSourceCard = scanner.nextInt(); mAudioSourceDevice = scanner.nextInt(); } catch (FileNotFoundException e) { Slog.e(TAG, "could not open audio source PCM file", e); enabled = false; } finally { if (scanner != null) { scanner.close(); } } } mAudioSourceEnabled = enabled; } mUsbAlsaManager.setAccessoryAudioState( mAudioSourceEnabled && mConfigured, mAudioSourceCard, mAudioSourceDevice); }
Source:
<code>public String toString() { return "DiscoveryConfig{" + "discoveryStrategyConfigs=" + discoveryStrategyConfigs + ", discoveryServiceProvider=" + discoveryServiceProvider <START> + ", nodeFilter=" + nodeFilter + '\'' <END> + ", nodeFilterClass='" + nodeFilterClass + '\'' + '}'; }</code><technical_language>Single quotation marks needed line 145. escape class names strings. problem appears in other classes</technical_language>

Target:
public String toString() { return "DiscoveryConfig{" + "discoveryStrategyConfigs=" + discoveryStrategyConfigs + ", discoveryServiceProvider=" + discoveryServiceProvider + ", nodeFilter=" + nodeFilter + ", nodeFilterClass='" + nodeFilterClass + '\'' + '}'; }
Source:
<code>public String docs() { return "void {key, value} Stores a value in the global storage register." + " An arbitrary value is stored with the given key, and can be retreived using import." + " If the value is already stored, it is overwritten. See {{function|import}}." + " The reference to the value is stored, not a copy of the value, so in the case of" + " arrays, manipulating the contents of the array will manipulate the stored value." <START> + " export() is threadsafe."; <END> }</code><technical_language>add a blurb array('key1', 'key2') format in docs, add example. This is true for functions</technical_language>

Target:
public String docs() { return "void {key, value} Stores a value in the global storage register." + " An arbitrary value is stored with the given key, and can be retreived using import." + " If the value is already stored, it is overwritten. See {{function|import}}." + " The reference to the value is stored, not a copy of the value, so in the case of" + " arrays, manipulating the contents of the array will manipulate the stored value. An array may" + " be used as a key. It is converted into a string with the array values separated by dots." + " export() is threadsafe."; }
Source:
<code>public void execute(FunctionContext<Object[]> context) { Object[] arguments = context.getArguments(); RestoreRedundancyRequest request = (RestoreRedundancyRequest) arguments[0]; boolean isStatusCommand = (boolean) arguments[1]; RestoreRedundancyOperation redundancyOperation = context.getCache().getResourceManager().createRestoreRedundancyOperation(); Set<String> includeRegionsSet = null; if (request.getIncludeRegions() != null) { includeRegionsSet = new HashSet<>(request.getIncludeRegions()); } Set<String> excludeRegionsSet = null; if (request.getExcludeRegions() != null) { excludeRegionsSet = new HashSet<>(request.getExcludeRegions()); } redundancyOperation.includeRegions(includeRegionsSet); redundancyOperation.excludeRegions(excludeRegionsSet); RestoreRedundancyResultsImpl results; try { if (isStatusCommand) { results = (RestoreRedundancyResultsImpl) redundancyOperation.redundancyStatus(); } else { redundancyOperation.shouldReassignPrimaries(request.getReassignPrimaries()); results = (RestoreRedundancyResultsImpl) redundancyOperation.start().join(); } if (results.getRegionOperationStatus().equals(ERROR)) { Exception e = new Exception(results.getRegionOperationMessage()); throw e; } results.setSuccess(true); <START> results.setStatusMessage("Success"); END> } catch (Exception e) { results = new SerializableRestoreRedundancyResultsImpl(); results.setSuccess(false); results.setStatusMessage(e.getMessage()); } context.getResultSender().lastResult(results); }</code><technical_language>Remove initials</technical_language>

Target:
public void execute(FunctionContext<Object[]> context) { Object[] arguments = context.getArguments(); RestoreRedundancyRequest request = (RestoreRedundancyRequest) arguments[0]; boolean isStatusCommand = (boolean) arguments[1]; RestoreRedundancyOperation redundancyOperation = context.getCache().getResourceManager().createRestoreRedundancyOperation(); Set<String> includeRegionsSet = null; if (request.getIncludeRegions() != null) { includeRegionsSet = new HashSet<>(request.getIncludeRegions()); } Set<String> excludeRegionsSet = null; if (request.getExcludeRegions() != null) { excludeRegionsSet = new HashSet<>(request.getExcludeRegions()); } redundancyOperation.includeRegions(includeRegionsSet); redundancyOperation.excludeRegions(excludeRegionsSet); RestoreRedundancyResultsImpl results; try { if (isStatusCommand) { results = (RestoreRedundancyResultsImpl) redundancyOperation.redundancyStatus(); } else { redundancyOperation.shouldReassignPrimaries(request.getReassignPrimaries()); results = (RestoreRedundancyResultsImpl) redundancyOperation.start().join(); } results.setSuccess(true); results.setStatusMessage("Success"); } catch (Exception e) { results = new SerializableRestoreRedundancyResultsImpl(); results.setSuccess(false); results.setStatusMessage(e.getMessage()); } context.getResultSender().lastResult(results); }
Source:
<code>public long getMeanTimeToRecovery(Run<?, ?> run) { if (buildFailed(run.getPreviousBuiltBuild())) { Run<?, ?> firstFailedRun = run.getPreviousBuiltBuild(); while (firstFailedRun != null && buildFailed(firstFailedRun.getPreviousBuiltBuild())) { firstFailedRun = firstFailedRun.getPreviousBuiltBuild(); } if (firstFailedRun != null) { <START> long mttf = run.getStartTimeInMillis() - firstFailedRun.getStartTimeInMillis(); <END> return mttf; } } return 0; }</code><technical_language>why</technical_language>

Target:
private long getMeanTimeToRecovery(Run<?, ?> run) { if (isFailedBuild(run.getPreviousBuiltBuild())) { Run<?, ?> firstFailedRun = run.getPreviousBuiltBuild(); while (firstFailedRun != null && isFailedBuild(firstFailedRun.getPreviousBuiltBuild())) { firstFailedRun = firstFailedRun.getPreviousBuiltBuild(); } if (firstFailedRun != null) { return getStartTimeInMillis(run) - getStartTimeInMillis(firstFailedRun); } } return 0; }