auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void reconnectMesos() { callWithStateLock(() -> { state.setMesosSchedulerState(MesosSchedulerState.PAUSED_FOR_MESOS_RECONNECT); <START> mesosSchedulerClient.close(); <END> try { Retryer<Void> startRetryer = RetryerBuilder.<Void>newBuilder() .retryIfException() .retryIfRuntimeException() .withWaitStrategy(WaitStrategies.exponentialWait()) .withStopStrategy(StopStrategies.stopAfterDelay(configuration.getMesosConfiguration().getReconnectTimeoutMillis(), TimeUnit.MILLISECONDS)) .build(); startRetryer.call(() -> { start(); return null; }); } catch (RetryException re) { if (re.getLastFailedAttempt().getExceptionCause() != null) { LOG.error("Unable to retry mesos master connection", re.getLastFailedAttempt().getExceptionCause()); notifyStopping(); abort.abort(AbortReason.MESOS_ERROR, Optional.of(re.getLastFailedAttempt().getExceptionCause())); } } catch (Throwable t) { LOG.error("Unable to retry mesos master connection", t); notifyStopping(); abort.abort(AbortReason.MESOS_ERROR, Optional.of(t)); } }, "reconnectMesos", false); }</code><technical_language>this throw exception</technical_language>

Target:
public void reconnectMesos() { callWithStateLock(() -> { state.setMesosSchedulerState(MesosSchedulerState.PAUSED_FOR_MESOS_RECONNECT); LOG.info("Paused scheduler actions, closing existing mesos connection"); mesosSchedulerClient.close(); LOG.info("Closed existing mesos connection"); try { Retryer<Void> startRetryer = RetryerBuilder.<Void>newBuilder() .retryIfException() .retryIfRuntimeException() .withWaitStrategy(WaitStrategies.exponentialWait()) .withStopStrategy(StopStrategies.stopAfterDelay(configuration.getMesosConfiguration().getReconnectTimeoutMillis(), TimeUnit.MILLISECONDS)) .build(); startRetryer.call(() -> { start(); return null; }); } catch (RetryException re) { if (re.getLastFailedAttempt().getExceptionCause() != null) { LOG.error("Unable to retry mesos master connection", re.getLastFailedAttempt().getExceptionCause()); notifyStopping(); abort.abort(AbortReason.MESOS_ERROR, Optional.of(re.getLastFailedAttempt().getExceptionCause())); } } catch (Throwable t) { LOG.error("Unable to retry mesos master connection", t); notifyStopping(); abort.abort(AbortReason.MESOS_ERROR, Optional.of(t)); } }, "reconnectMesos", false); }
Source:
<code>private ImmutableList<String> buildAnnotationClasses() { ImmutableList.Builder<String> builder = ImmutableList.builder(); for (AnnotationMirror annotationMirror : method.getAnnotationMirrors()) { <START> String fullName = typeSimplifier.simplify(annotationMirror.getAnnotationType()); <END> String annotationClass = "@" + fullName; List<String> values = FluentIterable .from(annotationMirror.getElementValues().entrySet()) .filter(Predicates.notNull()) .transform(valuesToString) .toList(); if (!values.isEmpty()) { annotationClass += "("; annotationClass += Joiner.on(", ").join(values); annotationClass += ")"; } builder.add(annotationClass); } return builder.build(); }</code><technical_language>a bit strange call this fullName. annotationName</technical_language>

Target:
private ImmutableList<String> buildAnnotationClasses() { ImmutableList.Builder<String> builder = ImmutableList.builder(); for (AnnotationMirror annotationMirror : method.getAnnotationMirrors()) { String annotationName = typeSimplifier.simplify(annotationMirror.getAnnotationType()); String annotation = "@" + annotationName; List<String> values = FluentIterable .from(annotationMirror.getElementValues().entrySet()) .filter(Predicates.notNull()) .transform(valuesToString) .toList(); if (!values.isEmpty()) { annotation += "(" + Joiner.on(", ").join(values) + ")"; } builder.add(annotation); } return builder.build(); }
Source:
<code>public void clearChildrenProducerBatch() { <START> childrenProducerBatch.clear(); <END> }</code><technical_language>wondering if care of concurrent modification for this list. should, maybe</technical_language>

Target:
private synchronized void clearChildrenProducerBatch() { if (childrenProducerBatch != null) { childrenProducerBatch.clear(); } }
Source:
<code>private static void populateHiveConf(HiveConf hiveConf, String[] args) { if (args == null) { return; } int index = 0; for (; index < args.length; index++) { if ("-hiveconf".equals(args[index])) { String hiveConfParam = args[++index]; String[] tokens = hiveConfParam.split("="); if (tokens.length == 2) { String name = tokens[0]; <START> if (name.startsWith("'") || name.startsWith("\"")) { <END> name = name.substring(1); } String value = tokens[1]; if (value.endsWith("'") || value.endsWith("\"")) { value = value.substring(1); } logger.info("Setting: " + name + " value:" + value + " to hiveConf"); hiveConf.set(name, value); } else { logger.warn("Invalid hiveconf: " + hiveConfParam); } } } }</code><technical_language>azkaban.utils.StringUtils.SINGLE_QUOTE azkaban.utils.StringUtils.DOUBLE_QUOTE here. line 272</technical_language>

Target:
private static void populateHiveConf(HiveConf hiveConf, String[] args) { if (args == null) { return; } int index = 0; for (; index < args.length; index++) { if ("-hiveconf".equals(args[index])) { String hiveConfParam = stripSingleDoubleQuote(args[++index]); String[] tokens = hiveConfParam.split("="); if (tokens.length == 2) { String name = tokens[0]; String value = tokens[1]; logger.info("Setting: " + name + "=" + value + " to hiveConf"); hiveConf.set(name, value); } else { logger.warn("Invalid hiveconf: " + hiveConfParam); } } } }
Source:
<code>private Set<String> getRoles(PrincipalCollection principals, final LdapContextFactory ldapContextFactory) throws NamingException { final String username = (String) getAvailablePrincipal(principals); LdapContext systemLdapCtx = null; try { systemLdapCtx = ldapContextFactory.getSystemLdapContext(); return rolesFor(principals, username, systemLdapCtx, ldapContextFactory, SecurityUtils.getSubject().getSession()); } catch (Throwable t) { <START> t.printStackTrace(); <END> return Collections.emptySet(); } finally { LdapUtils.closeContext(systemLdapCtx); } }</code><technical_language>Logger.error logging error message</technical_language>

Target:
private Set<String> getRoles(PrincipalCollection principals, final LdapContextFactory ldapContextFactory) throws NamingException { final String username = (String) getAvailablePrincipal(principals); LdapContext systemLdapCtx = null; try { systemLdapCtx = ldapContextFactory.getSystemLdapContext(); return rolesFor(principals, username, systemLdapCtx, ldapContextFactory, SecurityUtils.getSubject().getSession()); } catch (Throwable t) { log.warn("Failed to get roles in current context for " + username, t); return Collections.emptySet(); } finally { LdapUtils.closeContext(systemLdapCtx); } }
Source:
<code>private List<String> getAllChanges() { ArrayList<String> result = new ArrayList<String>(globalQueue); <START> globalQueue.clear(); <END> return result; }</code><technical_language>Oh, right, me. Sorry</technical_language>

Target:
private List<String> getAllChanges() { Set<String> seen = new HashSet<String>((int) (globalQueue.size() / 0.75f) + 1, 0.75f); List<String> result = new ArrayList<String>(globalQueue.size()); while (true) { String path = globalQueue.poll(); if (path == null) { break; } if (seen.add(path)) { result.add(path); } } return result; }
Source:
<code>Config generateConfig() { Map<String, String> streamConfig = new HashMap<>(); StreamSpec spec = getStreamSpec(); streamConfig.put(String.format(StreamConfig.SYSTEM_FOR_STREAM_ID(), spec.getId()), spec.getSystemName()); streamConfig.put(String.format(StreamConfig.PHYSICAL_NAME_FOR_STREAM_ID(), spec.getId()), spec.getPhysicalName()); if (isIntermediate()) { streamConfig.put(String.format(StreamConfig.IS_INTERMEDIATE_FOR_STREAM_ID(), spec.getId()), "true"); streamConfig.put(String.format(StreamConfig.DELETE_COMMITTED_MESSAGES_FOR_STREAM_ID(), spec.getId()), "true"); <START> if (new ApplicationConfig(config).getAppMode().equals(ApplicationConfig.ApplicationMode.BATCH)) { <END> streamConfig.put(String.format(StreamConfig.CONSUMER_OFFSET_DEFAULT_FOR_STREAM_ID(), spec.getId()), "oldest"); } streamConfig.put(String.format(StreamConfig.PRIORITY_FOR_STREAM_ID(), spec.getId()), String.valueOf(Integer.MAX_VALUE)); } spec.getConfig().forEach((property, value) -> { streamConfig.put(String.format(StreamConfig.STREAM_ID_PREFIX(), spec.getId()) + property, value); }); return new MapConfig(streamConfig); }</code><technical_language>nit: suggest do this other guard getAppMode() returning potential nulls currently return STREAM default. ApplicationConfig.ApplicationMode.BATCH.equals(...)</technical_language>

Target:
Config generateConfig() { Map<String, String> streamConfig = new HashMap<>(); StreamSpec spec = getStreamSpec(); String streamId = spec.getId(); streamConfig.put(String.format(StreamConfig.SYSTEM_FOR_STREAM_ID(), streamId), spec.getSystemName()); streamConfig.put(String.format(StreamConfig.PHYSICAL_NAME_FOR_STREAM_ID(), streamId), spec.getPhysicalName()); if (isIntermediate()) { streamConfig.put(String.format(StreamConfig.IS_INTERMEDIATE_FOR_STREAM_ID(), streamId), "true"); streamConfig.put(String.format(StreamConfig.DELETE_COMMITTED_MESSAGES_FOR_STREAM_ID(), streamId), "true"); if (ApplicationConfig.ApplicationMode.BATCH.equals(new ApplicationConfig(config).getAppMode())) { streamConfig.put(String.format(StreamConfig.CONSUMER_OFFSET_DEFAULT_FOR_STREAM_ID(), streamId), "oldest"); } streamConfig.put(String.format(StreamConfig.PRIORITY_FOR_STREAM_ID(), streamId), String.valueOf(Integer.MAX_VALUE)); } spec.getConfig().forEach((property, value) -> { streamConfig.put(String.format(StreamConfig.STREAM_ID_PREFIX(), streamId) + property, value); }); return new MapConfig(streamConfig); }
Source:
<code>private Resource snapshotStoreFiles( Collection<StoreFileMetadata> files ) throws IOException { final Collection<ResourceIterator<File>> snapshots = new ArrayList<>(); Lock lock = configurationLock.readLock(); lock.lock(); try { for ( WritableFulltext index : Iterables.concat( writableNodeIndices[ASIDE].values(), writableNodeIndices[BSIDE].values(), writableRelationshipIndices[ASIDE].values(), writableRelationshipIndices[BSIDE].values() ) ) { index.saveConfiguration( transactionIdStore.getLastCommittedTransactionId() ); try { applier.writeBarrier().awaitCompletion(); } catch ( ExecutionException e ) { throw new IOException( "Unable to prepare index for snapshot." ); } index.flush(); ResourceIterator<File> snapshot = index.snapshot(); snapshots.add( snapshot ); files.addAll( getSnapshotFilesMetadata( snapshot ) ); } } finally { lock.unlock(); <START> } <END> return new MultiResource( snapshots ); }</code><technical_language>need configuration read lock for duration of snapshotting? happen if drop index while reading snapshot</technical_language>

Target:
private Resource snapshotStoreFiles( Collection<StoreFileMetadata> files ) throws IOException { final Collection<ResourceIterator<File>> snapshots = new ArrayList<>(); for ( WritableFulltext index : Iterables.concat( writableNodeIndices[ASIDE].values(), writableNodeIndices[BSIDE].values(), writableRelationshipIndices[ASIDE].values(), writableRelationshipIndices[BSIDE].values() ) ) { Lock listingLock = configurationLock.readLock(); listingLock.lock(); index.saveConfiguration( transactionIdStore.getLastCommittedTransactionId() ); try { applier.writeBarrier().awaitCompletion(); } catch ( ExecutionException e ) { throw new IOException( "Unable to prepare index for snapshot.", e ); } index.flush(); ResourceIterator<File> snapshot = index.snapshot(); ResourceIterator<File> lockedSnapshot = lockedSnapshot( listingLock, snapshot ); snapshots.add( lockedSnapshot ); files.addAll( getSnapshotFilesMetadata( lockedSnapshot ) ); } return new MultiResource( snapshots ); }
Source:
<code>private void presentIcalFile(ICalendar ical, HttpServletResponse response){ try{ File file = File.createTempFile("ical", ".ics"); <START> ICalWriter writer = new ICalWriter(file, ICalVersion.V2_0); <END> writer.write(ical); writer.close(); IOUtils.copy(new FileInputStream(file), response.getOutputStream()); response.flushBuffer(); } catch (IOException e) { throw new RuntimeException("IOError writing ICalendar to response output stream"); } }</code><technical_language>write OutputStream (e.g. ByteArrayOutputStream), instead</technical_language>

Target:
private void presentIcalFile(ICalendar ical, HttpServletResponse response){ try{ ICalWriter writer = new ICalWriter(response.getOutputStream(), ICalVersion.V2_0); writer.write(ical); writer.close(); response.flushBuffer(); } catch (IOException e) { throw new RuntimeException("IOError writing ICalendar to response output stream", e); } }
Source:
<code>public void reset() throws IOException { <START> if (inputStreamFactory != null) { <END> in = new BufferedReader(new InputStreamReader(inputStreamFactory.createInputStream(), encoding)); } }</code><technical_language>Is this if needed is else for it</technical_language>

Target:
public void reset() throws IOException { in = new BufferedReader(new InputStreamReader(inputStreamFactory.createInputStream(), encoding)); }
Source:
<code>private void parseAddress(XmlPullParser parser, VCard vCard) throws XmlPullParserException, IOException { boolean isWork = true; <START> boolean done = false; <END> while (!done) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG && parser.getName().equals("HOME")) { isWork = false; } else if (eventType == XmlPullParser.START_TAG) { String name = parser.getName(); for (Adr a : Adr.class.getEnumConstants()) { if (a.name().equals(name)) { if (isWork) { vCard.setAddressFieldWork(name, parser.nextText()); } else { vCard.setAddressFieldHome(name, parser.nextText()); } } } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getName().equals("ADR")) { done = true; } } } }</code><technical_language>labeled loop instead</technical_language>

Target:
private void parseAddress(XmlPullParser parser, VCard vCard) throws XmlPullParserException, IOException { int initialDepth = parser.getDepth(); boolean isWork = true; outerloop: while (true) { int eventType = parser.next(); switch (eventType) { case XmlPullParser.START_TAG: String name = parser.getName(); if ("HOME".equals(name)) { isWork = false; } else { for (Adr a : Adr.class.getEnumConstants()) { if (a.name().equals(name)) { if (isWork) { vCard.setAddressFieldWork(name, parser.nextText()); } else { vCard.setAddressFieldHome(name, parser.nextText()); } } } } break; case XmlPullParser.END_TAG: if (parser.getDepth() == initialDepth) { break outerloop; } break; default: break; } } }
Source:
<code><START> FunctionDef mockFunctionDef(String function) { <END> List<ParamDef> params = new ArrayList<>(); params.add(mockParamDef(PARAM1_NAME, PARAM1_TYPE)); params.add(mockParamDef(PARAM2_NAME, PARAM2_TYPE)); FunctionDef functionDef = new FunctionDef(function, params); when(functionNamingService.getFunctionName(function)).thenReturn(FUNCTION_TRANSLATED_NAME); when(functionNamingService.getParamName(function, PARAM1_NAME)).thenReturn(PARAM1_TRANSLATED_NAME); when(functionNamingService.getParamHelp(function, PARAM1_NAME)).thenReturn(PARAM1_TRANSLATED_HELP); when(functionNamingService.getParamName(function, PARAM2_NAME)).thenReturn(PARAM2_TRANSLATED_NAME); when(functionNamingService.getParamHelp(function, PARAM2_NAME)).thenReturn(PARAM2_TRANSLATED_HELP); return functionDef; }</code><technical_language>constant FUNCTION is for this parameter for invocations</technical_language>

Target:
private FunctionDef mockFunctionDef(String function) { List<ParamDef> params = new ArrayList<>(); params.add(mockParamDef(PARAM1_NAME, PARAM1_TYPE)); params.add(mockParamDef(PARAM2_NAME, PARAM2_TYPE)); FunctionDef functionDef = new FunctionDef(function, params); when(functionNamingService.getFunctionName(function)).thenReturn(FUNCTION_TRANSLATED_NAME); when(functionNamingService.getParamName(function, PARAM1_NAME)).thenReturn(PARAM1_TRANSLATED_NAME); when(functionNamingService.getParamHelp(function, PARAM1_NAME)).thenReturn(PARAM1_TRANSLATED_HELP); when(functionNamingService.getParamName(function, PARAM2_NAME)).thenReturn(PARAM2_TRANSLATED_NAME); when(functionNamingService.getParamHelp(function, PARAM2_NAME)).thenReturn(PARAM2_TRANSLATED_HELP); return functionDef; }
Source:
<code><START> public void close() { <END> wrappedIterator.close(); }</code><technical_language>close invalidate iterator, reliant internal iterator for this. a flag isOpen (or isClosed) is checked for methods. a htsjdk/samtools/util/CloseableIterator.java (evidently) call close() if hasNext is return false</technical_language>

Target:
public void close() { isOpen = false; wrappedIterator.close(); }
Source:
<code>public void after() throws InterruptedException { <START> if (storageManager != null) { <END> storageManager.shutdown(); } }</code><technical_language>If storageManager a in constructor, need check null</technical_language>

Target:
public void after() throws InterruptedException { storageManager.shutdown(); }
Source:
<code>private List<Artifact> mergeArtifactLists(List<Artifact> childArtifacts, List<Artifact> parentArtifacts) { List<Artifact> artifactList = new ArrayList<>(); artifactList.addAll(childArtifacts); for (Artifact parentArtifact : parentArtifacts) { boolean found = false; for (Artifact childArtifact : childArtifacts) { <START> if (childArtifact.getArtifactId().equals(parentArtifact.getArtifactId())) { <END> found = true; break; } } if (!found) { artifactList.add(parentArtifact); } } return artifactList; }</code><technical_language>artifactId is enough... groupId packaging match</technical_language>

Target:
private List<Artifact> mergeArtifactLists(List<Artifact> childArtifacts, List<Artifact> parentArtifacts) { List<Artifact> artifactList = new ArrayList<>(); artifactList.addAll(childArtifacts); for (Artifact parentArtifact : parentArtifacts) { boolean found = false; for (Artifact childArtifact : childArtifacts) { boolean isGroupIdMatch = childArtifact.getGroupId().equals(parentArtifact.getGroupId()); boolean isArtifactIdMatch = childArtifact.getArtifactId().equals(parentArtifact.getArtifactId()); boolean isTypeMatch = childArtifact.getType().equals(parentArtifact.getType()); if (isGroupIdMatch && isArtifactIdMatch && isTypeMatch) { found = true; break; } } if (!found) { artifactList.add(parentArtifact); } } return artifactList; }
Source:
<code>protected VpcOffering createVpcOffering(final String name, final String displayText, final Map<Network.Service, Set<Network.Provider>> svcProviderMap, final boolean isDefault, final VpcOffering.State state, final Long serviceOfferingId) { return Transaction.execute(new TransactionCallback<VpcOffering>() { @Override public VpcOffering doInTransaction(TransactionStatus status) { VpcOfferingVO offering = new VpcOfferingVO(name, displayText, isDefault, serviceOfferingId, false, false); if (state != null) { offering.setState(state); } <START> s_logger.debug("Adding vpc offering " + offering); <END> offering = _vpcOffDao.persist(offering); if (svcProviderMap != null) { for (Network.Service service : svcProviderMap.keySet()) { Set<Network.Provider> providers = svcProviderMap.get(service); if (providers != null && !providers.isEmpty()) { for (Network.Provider provider : providers) { VpcOfferingServiceMapVO offService = new VpcOfferingServiceMapVO(offering.getId(), service, provider); _vpcOffSvcMapDao.persist(offService); s_logger.trace("Added service for the vpc offering: " + offService + " with provider " + provider.getName()); } } else { throw new InvalidParameterValueException("Provider is missing for the VPC offering service " + service.getName()); } } } return offering; } }); }</code><technical_language>Wrap in a if (s_logger.isDebugEnabled()) { ... } block avoid unnecessary pressure string pool debug logging is enabled</technical_language>

Target:
protected VpcOffering createVpcOffering(final String name, final String displayText, final Map<Network.Service, Set<Network.Provider>> svcProviderMap, final boolean isDefault, final VpcOffering.State state, final Long serviceOfferingId) { return Transaction.execute(new TransactionCallback<VpcOffering>() { @Override public VpcOffering doInTransaction(TransactionStatus status) { VpcOfferingVO offering = new VpcOfferingVO(name, displayText, isDefault, serviceOfferingId, false, false); if (state != null) { offering.setState(state); } if (s_logger.isDebugEnabled()) { s_logger.debug("Adding vpc offering " + offering); } offering = _vpcOffDao.persist(offering); if (svcProviderMap != null) { for (Network.Service service : svcProviderMap.keySet()) { Set<Network.Provider> providers = svcProviderMap.get(service); if (providers != null && !providers.isEmpty()) { for (Network.Provider provider : providers) { VpcOfferingServiceMapVO offService = new VpcOfferingServiceMapVO(offering.getId(), service, provider); _vpcOffSvcMapDao.persist(offService); if (s_logger.isTraceEnabled()) { s_logger.trace("Added service for the vpc offering: " + offService + " with provider " + provider.getName()); } } } else { throw new InvalidParameterValueException("Provider is missing for the VPC offering service " + service.getName()); } } } return offering; } }); }
Source:
<code>public void test(TestHarness th) { try { client = (LocalMessageProtocolConnection)Connector.open("localmsg://" + PROTO_NAME); testProtocolVersion(th); testScaleImage(th, 0, 100, 100); testScaleImage(th, 1, 0, 0); testScaleImage(th, 10000, 0, 0); <START> testScaleImage(th, 10000, 101, 101); <END> client.close(); } catch (IOException ioe) { th.fail("Unexpected exception"); ioe.printStackTrace(); } }</code><technical_language>good test case send image scaling (max_kb > file size, max_hres > image width, max_vres > image height)</technical_language>

Target:
public void test(TestHarness th) { try { client = (LocalMessageProtocolConnection)Connector.open("localmsg://" + PROTO_NAME); testProtocolVersion(th); testScaleImage(th, 0, 100, 100); testScaleImage(th, 1, 0, 0); testScaleImage(th, 10000, 0, 0); testScaleImage(th, 10000, 101, 101); testScaleImage(th, 10000, 10000, 10000); client.close(); } catch (IOException ioe) { th.fail("Unexpected exception"); ioe.printStackTrace(); } }
Source:
<code>boolean isDualTable(String tableName) { <START> return ((schemaName == null || equalsToken(schemaName, "SYS")) && equalsToken("F", tableName)) <END> || (database.getMode().sysDummy1 && (schemaName == null || equalsToken(schemaName, "SYSIBM")) && equalsToken("SYSDUMMY1", tableName)); }</code><technical_language>code broken</technical_language>

Target:
boolean isDualTable(String tableName) { return ((schemaName == null || equalsToken(schemaName, "SYS")) && equalsToken("DUAL", tableName)) || (database.getMode().sysDummy1 && (schemaName == null || equalsToken(schemaName, "SYSIBM")) && equalsToken("SYSDUMMY1", tableName)); }
Source:
<code>void projectionTestHelper(String projectionField, Object expectedValue) { ExtendedSearchIntegrator searchFactory = sfHolder.getSearchFactory(); <START> QueryBuilder guestQueryBuilder = searchFactory.buildQueryBuilder().forEntity( ExampleEntity.class ).get(); <END> Query queryAllGuests = guestQueryBuilder.all().createQuery(); List<EntityInfo> queryEntityInfos = searchFactory.createHSQuery().luceneQuery( queryAllGuests ) .targetedEntities( Arrays.asList( new Class<?>[] { ExampleEntity.class } ) ) .projection( projectionField ) .queryEntityInfos(); Assert.assertEquals( 1, queryEntityInfos.size() ); EntityInfo entityInfo = queryEntityInfos.get( 0 ); Object projectedValue = entityInfo.getProjection()[0]; Assert.assertEquals( expectedValue, projectedValue ); }</code><technical_language>'guestQueryBuilder'!? is 'guest' coming from</technical_language>

Target:
void projectionTestHelper(String projectionField, Object expectedValue) { ExtendedSearchIntegrator searchFactory = sfHolder.getSearchFactory(); QueryBuilder queryBuilder = searchFactory.buildQueryBuilder().forEntity( ExampleEntity.class ).get(); Query queryAllGuests = queryBuilder.all().createQuery(); List<EntityInfo> queryEntityInfos = searchFactory.createHSQuery().luceneQuery( queryAllGuests ) .targetedEntities( Arrays.asList( new Class<?>[] { ExampleEntity.class } ) ) .projection( projectionField ) .queryEntityInfos(); Assert.assertEquals( 1, queryEntityInfos.size() ); EntityInfo entityInfo = queryEntityInfos.get( 0 ); Object projectedValue = entityInfo.getProjection()[0]; Assert.assertEquals( expectedValue, projectedValue ); }
Source:
<code><START> protected File discoverGitSystemConfig() { <END> File gitExe = discoverGitExe(); if (gitExe == null) return null; Map<String, String> env = new HashMap<>(); env.put("GIT_EDITOR", "echo"); String w = readPipe(gitExe.getParentFile(), new String[]{"git", "config", "--system", "--edit"}, Charset.defaultCharset().name(), env); if (StringUtils.isEmptyOrNull(w)) return null; return new File(w); }</code><technical_language>missing @since tag</technical_language>

Target:
protected File discoverGitSystemConfig() { File gitExe = discoverGitExe(); if (gitExe == null) { return null; } Map<String, String> env = new HashMap<>(); env.put("GIT_EDITOR", "echo"); String w = readPipe(gitExe.getParentFile(), new String[] { "git", "config", "--system", "--edit" }, Charset.defaultCharset().name(), env); if (StringUtils.isEmptyOrNull(w)) { return null; } return new File(w); }
Source:
<code>public Object getRelation(DataStoreTransaction relationTx, Object entity, String relationName, Optional<FilterExpression> filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination, RequestScope scope) { Object values = PersistentResource.getValue(entity, relationName, scope); <START> Map<String, Object> validChildren = new HashMap<>(); <END> if (dictionary.getRelationshipType(entity, relationName).isToOne()) { if (values == null) { return null; } validChildren.put(dictionary.getId(values), values); } else if (values instanceof Collection) { validChildren.putAll((Map) ((Collection) values).stream() .collect(Collectors.toMap(dictionary::getId, Function.identity()))); } else { throw new IllegalStateException("An unexpected error occurred querying a relationship"); } Class entityClass = dictionary.getParameterizedType(entity, relationName); return processData(entityClass, validChildren, filterExpression, sorting, pagination, scope); }</code><technical_language>rename idToChildResource lines</technical_language>

Target:
public Object getRelation(DataStoreTransaction relationTx, Object entity, String relationName, Optional<FilterExpression> filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination, RequestScope scope) { Object values = PersistentResource.getValue(entity, relationName, scope); Map<String, Object> idToChildResource = new HashMap<>(); if (dictionary.getRelationshipType(entity, relationName).isToOne()) { if (values == null) { return null; } idToChildResource.put(dictionary.getId(values), values); } else if (values instanceof Collection) { idToChildResource.putAll((Map) ((Collection) values).stream() .collect(Collectors.toMap(dictionary::getId, Function.identity()))); } else { throw new IllegalStateException("An unexpected error occurred querying a relationship"); } Class entityClass = dictionary.getParameterizedType(entity, relationName); return processData(entityClass, idToChildResource, filterExpression, sorting, pagination, scope); }
Source:
<code>public KafkaRyaSubGraphExporter(KafkaProducer<String, RyaSubGraph> producer) { <START> Preconditions.checkNotNull(producer); <END> this.producer = producer; }</code><technical_language>this statically imported</technical_language>

Target:
public KafkaRyaSubGraphExporter(KafkaProducer<String, RyaSubGraph> producer) { checkNotNull(producer); this.producer = producer; }
Source:
<code>public static void setUpBeforeClass() throws Exception { Path cnfPath = FileSystems.getDefault().getPath("target/test-classes/hbase-site.xml"); Path cnf2Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site2.xml"); Path cnf3Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site3.xml"); String absoluteDataPath = TEST_UTIL.getDataTestDir().toString(); String dataBasePath = System.getProperty(HBaseCommonTestingUtility.BASE_TEST_DIRECTORY_KEY, <START> HBaseCommonTestingUtility.DEFAULT_BASE_TEST_DIRECTORY); <END> String dataPath = absoluteDataPath.substring(absoluteDataPath.indexOf(dataBasePath)); newCnfPath = Paths.get(dataPath + "/hbase-site.xml"); newCnf2Path = Paths.get(dataPath + "/hbase-site2.xml"); newCnf3Path = Paths.get(dataPath + "/hbase-site3.xml"); Files.createDirectories(Paths.get(dataPath)); Files.copy(cnfPath, newCnfPath); Files.copy(cnf2Path, newCnf2Path); Files.copy(cnf3Path, newCnf3Path); TEST_UTIL.getConfiguration().addResource(TEST_UTIL.getDataTestDir("hbase-site.xml")); TEST_UTIL.getConfiguration().setInt(HConstants.MASTER_INFO_PORT, 0); TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 60000); TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT, 120000); TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 2); TEST_UTIL.getConfiguration().setInt(START_LOG_ERRORS_AFTER_COUNT_KEY, 0); TEST_UTIL.startMiniCluster(2); ASYNC_CONN = ConnectionFactory.createAsyncConnection(TEST_UTIL.getConfiguration()).get(); for (int i = 0; i < 2; i ++) { TEST_UTIL.getMiniHBaseCluster().getRegionServer(i).getConfiguration(). addResource(TEST_UTIL.getDataTestDir("hbase-site.xml")); } }</code><technical_language>This is interesting. Do trust get TEST_UTIL#getDataTestDir</technical_language>

Target:
public static void setUpBeforeClass() throws Exception { setUpConfigurationFiles(TEST_UTIL); TEST_UTIL.getConfiguration().setInt(HConstants.MASTER_INFO_PORT, 0); TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 60000); TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT, 120000); TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 2); TEST_UTIL.getConfiguration().setInt(START_LOG_ERRORS_AFTER_COUNT_KEY, 0); TEST_UTIL.startMiniCluster(2); ASYNC_CONN = ConnectionFactory.createAsyncConnection(TEST_UTIL.getConfiguration()).get(); addResourceToRegionServerConfiguration(TEST_UTIL); }
Source:
<code><START> private static boolean isValid(final String s) { <END> final int includeTrailingEmpty = -1; final String[] parts = s.split("/", includeTrailingEmpty); boolean wildcard = false; for (int i = 0; i < parts.length; i++) { String part = parts[i]; if (part.length() == 0) return false; if (part.equals("*")) { if (wildcard) return false; wildcard = true; } else if (part.contains("*")) { return false; } } return true; }</code><technical_language>I write this method as: int s = str.indexOf('*'); if (s < 1) return true; if (str.indexOf('*', s + 1) > s) return false; if (str.charAt(s - 1) != '/') return false; if (s == str.length() - 1) return true; return str.charAt(s + 1) == '/'; version fail check for // case, check for either</technical_language>

Target:
private static boolean isValid(final String s) { if (s.startsWith("/")) return false; if (s.contains(" return false; int i = s.indexOf('*'); if (i != -1) { if (s.indexOf('*', i + 1) > i) return false; if (i > 0 && s.charAt(i - 1) != '/') return false; if (i < s.length() - 1 && s.charAt(i + 1) != '/') return false; } return true; }
Source:
<code>public void init(FilterConfig filterConfig) throws ServletException { if (filterConfig == null) { <START> pathComponents = DEFAULT_PATH_COMPONENTS; <END> return; } if (!StringUtils.isEmpty(filterConfig.getInitParameter(PATH_COMPONENT_PARAM))) { pathComponents = Integer.valueOf(filterConfig.getInitParameter(PATH_COMPONENT_PARAM)); } }</code><technical_language>This is 3 levels of indirection find value, please simplify</technical_language>

Target:
public void init(FilterConfig filterConfig) throws ServletException { Histogram.Builder builder = Histogram.build() .labelNames("path", "method"); if (filterConfig == null && isEmpty(metricName)) { throw new ServletException("No configuration object provided, and no metricName passed via constructor"); } if (filterConfig != null) { if (isEmpty(metricName)) { metricName = filterConfig.getInitParameter(METRIC_NAME_PARAM); if (isEmpty(metricName)) { throw new ServletException("Init parameter \"" + METRIC_NAME_PARAM + "\" is required; please supply a value"); } } if (!isEmpty(filterConfig.getInitParameter(HELP_PARAM))) { help = filterConfig.getInitParameter(HELP_PARAM); } if (!isEmpty(filterConfig.getInitParameter(PATH_COMPONENT_PARAM))) { pathComponents = Integer.valueOf(filterConfig.getInitParameter(PATH_COMPONENT_PARAM)); } if (!isEmpty(filterConfig.getInitParameter(BUCKET_CONFIG_PARAM))) { String[] bucketParams = filterConfig.getInitParameter(BUCKET_CONFIG_PARAM).split(","); buckets = new double[bucketParams.length]; for (int i = 0; i < bucketParams.length; i++) { buckets[i] = Double.parseDouble(bucketParams[i]); } } } if (buckets != null) { builder = builder.buckets(buckets); } histogram = builder .help(help) .name(metricName) .register(); }
Source:
<code>public Set<QualifiedTablePrefix> calculatePrefixesWithTableName( ConnectorSession connectorSession, Set<QualifiedTablePrefix> prefixes, TupleDomain<ColumnHandle> constraint, Predicate<Map<ColumnHandle, NullableValue>> predicate) { <START> Optional<Set<String>> tables = stringFilter(constraint, TABLE_COLUMN_HANDLE); <END> ImmutableSet.Builder<QualifiedTablePrefix> result = ImmutableSet.builder(); if (tables.isPresent()) { for (QualifiedTablePrefix prefix : prefixes) { tables.get().stream() .map(table -> new QualifiedTablePrefix(prefix.getCatalogName(), prefix.getSchemaName().get(), table)) .forEach(result::add); } } else { Session session = ((FullConnectorSession) connectorSession).getSession(); for (QualifiedTablePrefix prefix : prefixes) { Stream.concat( metadata.listTables(session, prefix).stream(), metadata.listViews(session, prefix).stream()) .filter(objectName -> predicate.test(ImmutableMap.of( CATALOG_COLUMN_HANDLE, new NullableValue(createUnboundedVarcharType(), utf8Slice(catalogName)), SCHEMA_COLUMN_HANDLE, new NullableValue(createUnboundedVarcharType(), utf8Slice(objectName.getSchemaName())), TABLE_COLUMN_HANDLE, new NullableValue(createUnboundedVarcharType(), utf8Slice(objectName.getObjectName()))))) .map(QualifiedObjectName::asQualifiedTablePrefix) .forEach(result::add); } } return result.build(); }</code><technical_language>Is this needed? apply predicate? this pre-optimization (maybe isn't, idk)</technical_language>

Target:
public Set<QualifiedTablePrefix> calculatePrefixesWithTableName( ConnectorSession connectorSession, Set<QualifiedTablePrefix> prefixes, TupleDomain<ColumnHandle> constraint, Predicate<Map<ColumnHandle, NullableValue>> predicate) { Session session = ((FullConnectorSession) connectorSession).getSession(); Optional<Set<String>> tables = filterString(constraint, TABLE_NAME_COLUMN_HANDLE); if (tables.isPresent()) { return prefixes.stream() .flatMap(prefix -> tables.get().stream() .map(table -> new QualifiedObjectName(catalogName, prefix.getSchemaName().get(), table))) .filter(objectName -> metadata.getTableHandle(session, objectName).isPresent() || metadata.getView(session, objectName).isPresent()) .map(QualifiedObjectName::asQualifiedTablePrefix) .collect(toImmutableSet()); } return prefixes.stream() .flatMap(prefix -> Stream.concat( metadata.listTables(session, prefix).stream(), metadata.listViews(session, prefix).stream())) .filter(objectName -> predicate.test(asFixedValues(objectName))) .map(QualifiedObjectName::asQualifiedTablePrefix) .collect(toImmutableSet()); }
Source:
<code>public IterableStream<ServiceBusReceivedMessage> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } <START> final Flux<ServiceBusReceivedMessage> messages = Flux.create((emitter) -> queueWork(maxMessages, maxWaitTime, <END> emitter)); return new IterableStream<>(messages); }</code><technical_language>extra parenthesis? a single parameter lambda</technical_language>

Target:
public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); }
Source:
<code>private SortedPositionLinks(PositionLinks positionLinks, int[][] sortedPositionLinks, JoinFilterFunction lessThanFunction) { this.positionLinks = requireNonNull(positionLinks, "positionLinks is null"); this.sortedPositionLinks = requireNonNull(sortedPositionLinks, "sortedPositionLinks is null"); this.lessThanFunction = requireNonNull(lessThanFunction, "lessThanFunction is null"); <START> this.sizeInBytes = INSTANCE_SIZE + positionLinks.getSizeInBytes() + (SizeOf.sizeOf(sortedPositionLinks[0]) * sortedPositionLinks.length); <END> }</code><technical_language>Do arrays in sortedPositionLinks length</technical_language>

Target:
private SortedPositionLinks(PositionLinks positionLinks, int[][] sortedPositionLinks, JoinFilterFunction lessThanFunction) { this.positionLinks = requireNonNull(positionLinks, "positionLinks is null"); this.sortedPositionLinks = requireNonNull(sortedPositionLinks, "sortedPositionLinks is null"); this.lessThanFunction = requireNonNull(lessThanFunction, "lessThanFunction is null"); this.sizeInBytes = INSTANCE_SIZE + positionLinks.getSizeInBytes() + sizeOfPositionLinks(sortedPositionLinks); }
Source:
<code>public ClusterValidator( ClusterDao clusterDao, StoragePoolDao dataCenterDao, Cluster cluster, CpuFlagsManagerHandler cpuFlagsManagerHandler) { this(clusterDao, dataCenterDao, cluster, cpuFlagsManagerHandler, <START> null, <END> null, null, null, null, null); }</code><technical_language>inject dao's this class, this nice, nulls</technical_language>

Target:
public ClusterValidator( ClusterDao clusterDao, StoragePoolDao dataCenterDao, Cluster cluster, CpuFlagsManagerHandler cpuFlagsManagerHandler) { this.cluster = cluster; this.clusterDao = clusterDao; this.dataCenterDao = dataCenterDao; this.cpuFlagsManagerHandler = cpuFlagsManagerHandler; }
Source:
<code>public String entityId(final Object message) { if (message instanceof JobExecutorActor.Reload) { <START> return _refSerializer.jobRefToEntityID(((JobExecutorActor.Reload) message).getJobRef()); <END> } return null; }</code><technical_language>Is case a reload change ref? starting a reload payload-less trigger logic instead of describing reload. Effectively changes actor's identify changing name. dangerous</technical_language>

Target:
public String entityId(final Object message) { if (message instanceof JobExecutorActor.Reload) { return _refSerializer.serialize(((JobExecutorActor.Reload) message).getJobRef()); } return null; }
Source:
<code>private boolean verifyMetricsFromSink() throws InterruptedException { Map<String, Long> expectedMetrics = new HashMap<>(); for (GlobalMetric m : PhoenixRuntime.getGlobalPhoenixClientMetrics()) { expectedMetrics.put(m.getMetricType().name(), m.getTotalSum()); } for (int i = 0; i < MAX_RETRIES; i++) { LOG.info("Verifying Global Metrics from Hadoop Sink, Retry: " + (i + 1)); if (verifyMetricsFromSinkOnce(expectedMetrics)) { LOG.info("Values from Hadoop Metrics Sink match actual values"); return true; } <START> Thread.sleep(1000); <END> } return false; }</code><technical_language>Change this to: try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } Then, remove throws InterruptedException. catching, re-setting interrupted state returning ASAP. Likely, this code invoked in a unit-test context, good practice</technical_language>

Target:
private boolean verifyMetricsFromSink() { Map<String, Long> expectedMetrics = new HashMap<>(); for (GlobalMetric m : PhoenixRuntime.getGlobalPhoenixClientMetrics()) { expectedMetrics.put(m.getMetricType().name(), m.getTotalSum()); } for (int i = 0; i < MAX_RETRIES; i++) { LOG.info("Verifying Global Metrics from Hadoop Sink, Retry: " + (i + 1)); if (verifyMetricsFromSinkOnce(expectedMetrics)) { LOG.info("Values from Hadoop Metrics Sink match actual values"); return true; } try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } } return false; }
Source:
<code>private Retryer<MessageSendingResult> createRetryer(final MessageBatch batch, int messageBackoff, int messageTtl, boolean retryClientErrors) { return RetryerBuilder.<MessageSendingResult>newBuilder() .retryIfExceptionOfType(IOException.class) .retryIfRuntimeException() <START> .retryIfResult(result -> isConsuming() && !result.succeeded() && (!result.isClientError() || retryClientErrors)) <END> .withWaitStrategy(fixedWait(messageBackoff, MILLISECONDS)) .withStopStrategy(attempt -> attempt.getDelaySinceFirstAttempt() > messageTtl) .withRetryListener(getRetryListener(result -> monitoring.markFailed(batch, subscription, result))) .build(); }</code><technical_language>add some labels this? hard parse exact conditions</technical_language>

Target:
private Retryer<MessageSendingResult> createRetryer(final MessageBatch batch, int messageBackoff, int messageTtl, boolean retryClientErrors) { return RetryerBuilder.<MessageSendingResult>newBuilder() .retryIfExceptionOfType(IOException.class) .retryIfRuntimeException() .retryIfResult(result -> isConsuming() && !result.succeeded() && shouldRetryOnClientError(retryClientErrors, result)) .withWaitStrategy(fixedWait(messageBackoff, MILLISECONDS)) .withStopStrategy(attempt -> attempt.getDelaySinceFirstAttempt() > messageTtl) .withRetryListener(getRetryListener(result -> monitoring.markFailed(batch, subscription, result))) .build(); }
Source:
<code>private void createOptionGroup(Composite parent) { if (fExperimentName != null) { Group comp = new Group(parent, SWT.SHADOW_NONE); comp.setText(RemoteMessages.RemoteFetchLogWizardRemotePage_OptionsGroupName); GridLayout layout = new GridLayout(2, false); comp.setLayout(layout); GridData data = new GridData(GridData.FILL, GridData.CENTER, true, false); comp.setLayoutData(data); fCreateExperimentCheckbox = new Button(comp, SWT.CHECK); fCreateExperimentCheckbox.setFont(comp.getFont()); fCreateExperimentCheckbox.setText(RemoteMessages.RemoteFetchLogWizardRemotePage_CreateExperimentName); fCreateExperimentCheckbox.setSelection(false); data = new GridData(GridData.BEGINNING, GridData.CENTER, false, false); fCreateExperimentCheckbox.setLayoutData(data); fExperimentNameText = new Text(comp, <START> SWT.NONE); <END> data = new GridData(GridData.FILL, GridData.CENTER, true, false); fExperimentNameText.setLayoutData(data); fExperimentNameText.setText(fExperimentName); fExperimentNameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePageCompletion(); } }); fCreateExperimentCheckbox.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fExperimentNameText.setEnabled(fCreateExperimentCheckbox.getSelection()); } }); } }</code><technical_language>BORDER</technical_language>

Target:
private void createOptionGroup(Composite parent) { if (fExperimentName != null) { Group comp = new Group(parent, SWT.SHADOW_NONE); comp.setText(RemoteMessages.RemoteFetchLogWizardRemotePage_OptionsGroupName); GridLayout layout = new GridLayout(2, false); comp.setLayout(layout); GridData data = new GridData(GridData.FILL, GridData.CENTER, true, false); comp.setLayoutData(data); fCreateExperimentCheckbox = new Button(comp, SWT.CHECK); fCreateExperimentCheckbox.setFont(comp.getFont()); fCreateExperimentCheckbox.setText(RemoteMessages.RemoteFetchLogWizardRemotePage_CreateExperimentName); fCreateExperimentCheckbox.setSelection(false); data = new GridData(GridData.BEGINNING, GridData.CENTER, false, false); fCreateExperimentCheckbox.setLayoutData(data); fExperimentNameText = new Text(comp, SWT.BORDER); data = new GridData(GridData.FILL, GridData.CENTER, true, false); fExperimentNameText.setLayoutData(data); fExperimentNameText.setText(fExperimentName); fExperimentNameText.setEnabled(fCreateExperimentCheckbox.getSelection()); fExperimentNameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePageCompletion(); } }); fCreateExperimentCheckbox.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fExperimentNameText.setEnabled(fCreateExperimentCheckbox.getSelection()); updatePageCompletion(); } }); } }
Source:
<code><START> static Collection<Column> getColumns(Class<? extends Entity> entityClass) { <END> checkNotNull(entityClass); ensureRegistered(entityClass); return knownEntityProperties.get(entityClass); }</code><technical_language>Please test this method properly</technical_language>

Target:
static Collection<Column> getColumns(Class<? extends Entity> entityClass) { checkNotNull(entityClass); ensureRegistered(entityClass); final Collection<Column> result = knownEntityProperties.get(entityClass); return result; }