auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testChangeTheStatusOfTheAPIToRetired() throws Exception { restAPIPublisher.changeAPILifeCycleStatus(apiId, APILifeCycleAction.RETIRE.getAction()); <START> assertTrue(restAPIPublisher.getLifecycleStatus(apiId).getData().equals("Retired"), apiNameTest + <END> "status not updated as Retired"); HttpResponse retiredApiResponse = restAPIPublisher.getAPI(apiId); assertEquals(retiredApiResponse.getResponseCode(), Response.Status.OK.getStatusCode(), apiNameTest + " is not visible in publisher"); assertTrue(retiredApiResponse.getData().contains(apiNameTest), apiNameTest + " is not visible in " + "publisher"); }</code><technical_language>Lets switch equals constant for Retired</technical_language>

Target:
public void testChangeTheStatusOfTheAPIToRetired() throws Exception { restAPIPublisher.changeAPILifeCycleStatus(apiId, APILifeCycleAction.RETIRE.getAction()); assertTrue(APILifeCycleState.RETIRED.getState().equals(restAPIPublisher.getLifecycleStatus(apiId).getData()), apiNameTest + "status not updated as Retired"); HttpResponse retiredApiResponse = restAPIPublisher.getAPI(apiId); assertEquals(retiredApiResponse.getResponseCode(), Response.Status.OK.getStatusCode(), apiNameTest + " is not visible in publisher"); assertTrue(retiredApiResponse.getData().contains(apiNameTest), apiNameTest + " is not visible in " + "publisher"); }
Source:
<code>public void triggerJob(){ ResourceBundleProvider.updateLocale(new Locale("en_US")); List<String> schemas = studyDao.findAllSchemas(); for (String schema : schemas) { if (StringUtils.isEmpty(schema)) { logger.error("Schema should not be null"); continue; } ArrayList<RuleSetBean> ruleSets = ruleSetDao.findAllRunOnSchedulesPerSchema(true, schema); for (RuleSetBean ruleSet : ruleSets) { if (ruleSet.getStatus().AVAILABLE != null && ruleSet.isRunSchedule()) { CoreResources.tenantSchema.set(schema); if(ruleSet.getItemId()!=null){ <START> logger.info("*** Item Specific Rule ***"); <END> ArrayList<RuleSetBean> ruleSetBeans = new ArrayList<>(); StudyBean currentStudy = (StudyBean) getStudyDao().findByPK(ruleSet.getStudyId()); ResourceBundleProvider.updateLocale(Locale.getDefault()); UserAccountBean ub = (UserAccountBean) getUserAccountDao().findByPK(1); ruleSetBeans.add(ruleSet); ruleSetService.runRulesInBulk(ruleSetBeans, false, currentStudy, ub, true); } else { logger.info("*** Event Specific Rule ***"); StudyEventChangeDetails studyEventChangeDetails = new StudyEventChangeDetails(true, true); ArrayList<RuleSetBean> ruleSetBeans = new ArrayList<>(); ExpressionBean eBean = new ExpressionBean(); eBean.setValue(ruleSet.getTarget().getValue()+".A.B"); ruleSet.setTarget(eBean); ruleSetBeans.add(ruleSet); ruleSetService.runRulesInBeanProperty(ruleSetBeans ,1, studyEventChangeDetails); } } } } }</code><technical_language>reason for setting this info opposed debug</technical_language>

Target:
public void triggerJob(){ ResourceBundleProvider.updateLocale(new Locale("en_US")); List<String> schemas = studyDao.findAllSchemas(); for (String schema : schemas) { if (StringUtils.isEmpty(schema)) { logger.error("Schema should not be null"); continue; } ArrayList<RuleSetBean> ruleSets = ruleSetDao.findAllRunOnSchedulesPerSchema(true, schema); for (RuleSetBean ruleSet : ruleSets) { if (ruleSet.getStatus().AVAILABLE != null && ruleSet.isRunSchedule()) { CoreResources.tenantSchema.set(schema); if(ruleSet.getItemId()!=null){ logger.debug("*** Item Specific Rule ***"); ArrayList<RuleSetBean> ruleSetBeans = new ArrayList<>(); StudyBean currentStudy = (StudyBean) getStudyDao().findByPK(ruleSet.getStudyId()); ResourceBundleProvider.updateLocale(Locale.getDefault()); UserAccountBean ub = (UserAccountBean) getUserAccountDao().findByPK(1); ruleSetBeans.add(ruleSet); ruleSetService.runRulesInBulk(ruleSetBeans, false, currentStudy, ub, true); } else { logger.debug("*** Event Specific Rule ***"); StudyEventChangeDetails studyEventChangeDetails = new StudyEventChangeDetails(true, true); ArrayList<RuleSetBean> ruleSetBeans = new ArrayList<>(); ExpressionBean eBean = new ExpressionBean(); eBean.setValue(ruleSet.getTarget().getValue()+".A.B"); ruleSet.setTarget(eBean); ruleSetBeans.add(ruleSet); ruleSetService.runRulesInBeanProperty(ruleSetBeans ,1, studyEventChangeDetails); } } } } }
Source:
<code>public Response getDetail(@PathParam("extension-name") String extensionName){ checkIfExtensionServiceIsEnabled(); validateExtensionName(extensionName); JSONObject result = new JSONObject(); try { <START> result.put(EXTENSION_DETAIL,buildDetailResult(extensionName)); <END> return Response.ok(result).build(); } catch (Throwable e) { throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }</code><technical_language>JSON a JSON? send json object buildDetailResult directly</technical_language>

Target:
public Response getDetail(@PathParam("extension-name") String extensionName){ checkIfExtensionServiceIsEnabled(); validateExtensionName(extensionName); try { return Response.ok(buildDetailResult(extensionName)).build(); } catch (Throwable e) { throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
Source:
<code>public void deleteTaskContainerMappings(Iterable<String> taskNames) { for (String taskName : taskNames) { <START> metadataStore.remove(keySerde.toBytes(taskName)); <END> } }</code><technical_language>do need remove taskNameToContainerId</technical_language>

Target:
public void deleteTaskContainerMappings(Iterable<String> taskNames) { for (String taskName : taskNames) { metadataStore.delete(keySerde.toBytes(taskName)); taskNameToContainerId.remove(taskName); } }
Source:
<code>public void handleGenerateAndReplaceKeysResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("Handle generate and replace keys response for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Generate and replace keys response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } <START> this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() <END> .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
public void handleGenerateAndReplaceKeysResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("Handle generate and replace keys response for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Generate and replace keys response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send(responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>public void testRegistersMetricsCorrectly() throws Exception { String testCluster = "testCoordinatorMetrics"; Coordinator coordinator = createCoordinator(_zkConnectionString, testCluster); coordinator.start(); List<BrooklinMetricInfo> metricInfos = coordinator.getMetricInfos(); DynamicMetricsManager metricsManager = DynamicMetricsManager.getInstance(); String coordinatorSimpleClassName = Coordinator.class.getSimpleName(); Map<String, BrooklinMetricInfo> metricInfoByName = metricInfos.stream() .filter(info -> info.getNameOrRegex().startsWith(coordinatorSimpleClassName)) .collect(Collectors.toMap(BrooklinMetricInfo::getNameOrRegex, Function.identity())); Map<String, Metric> metrics = metricsManager.getMetricRegistry().getMetrics().entrySet().stream() .filter(entry -> entry.getKey().startsWith(coordinatorSimpleClassName)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Assert.assertEquals(metricInfoByName.size(), metrics.size()); Map<Class<? extends BrooklinMetricInfo>, Class<? extends Metric>> metricInfoTypeToMetricType = new HashMap<>(); metricInfoTypeToMetricType.put(BrooklinCounterInfo.class, Counter.class); metricInfoTypeToMetricType.put(BrooklinGaugeInfo.class, Gauge.class); metricInfoTypeToMetricType.put(BrooklinHistogramInfo.class, Histogram.class); metricInfoTypeToMetricType.put(BrooklinMeterInfo.class, Meter.class); for (Map.Entry<String, BrooklinMetricInfo> entry : metricInfoByName.entrySet()) { String metricInfoKey = entry.getKey(); BrooklinMetricInfo metricInfo = entry.getValue(); Metric metric = metrics.get(metricInfoKey); Assert.assertNotNull(metric); <START> Class<? extends Metric> actualMetricClazz = metric.getClass(); <END> Class<? extends Metric> expectedMetricClazz = metricInfoTypeToMetricType.get(metricInfo.getClass()); Assert.assertTrue(expectedMetricClazz.isAssignableFrom(actualMetricClazz)); } coordinator.stop(); }</code><technical_language>reason name variable actualMetricClazz actualMetricClass</technical_language>

Target:
public void testRegistersMetricsCorrectly() throws Exception { String testCluster = "testCoordinatorMetrics"; Coordinator coordinator = createCoordinator(_zkConnectionString, testCluster); coordinator.start(); MetricsTestUtils.verifyMetrics(coordinator, DynamicMetricsManager.getInstance()); coordinator.stop(); }
Source:
<code>public void test() throws Exception { final String tableName = getUniqueNames(1)[0]; final Connector c = getConnector(); c.tableOperations().create(tableName); Random random = new Random(); BatchWriter bw = c.createBatchWriter(tableName, null); for (int i = 0; i < 50000; i++) { byte[] row = new byte[100]; random.nextBytes(row); Mutation m = new Mutation(row); m.put("", "", ""); bw.addMutation(m); } bw.close(); c.tableOperations().flush(tableName, null, null, true); final AtomicBoolean stop = new AtomicBoolean(false); Thread t1 = slowScan(c, tableName, stop); t1.start(); Thread t2 = slowScan(c, tableName, stop); t2.start(); sleepUninterruptibly(500, TimeUnit.MILLISECONDS); long now = System.currentTimeMillis(); Scanner m = c.createScanner(MetadataTable.NAME, Authorizations.EMPTY); Iterators.size(m.iterator()); long delay = System.currentTimeMillis() - now; System.out.println("Delay = " + delay); assertTrue("metadata table scan was slow", delay < 1000); assertFalse(stop.get()); stop.set(true); t1.interrupt(); t2.interrupt(); t1.join(); t2.join(); <START> m.close(); <END> }</code><technical_language>I realize Mutation Closeable :smile:</technical_language>

Target:
public void test() throws Exception { final String tableName = getUniqueNames(1)[0]; final Connector c = getConnector(); c.tableOperations().create(tableName); Random random = new Random(); BatchWriter bw = c.createBatchWriter(tableName, null); for (int i = 0; i < 50000; i++) { byte[] row = new byte[100]; random.nextBytes(row); Mutation m = new Mutation(row); m.put("", "", ""); bw.addMutation(m); } bw.close(); c.tableOperations().flush(tableName, null, null, true); final AtomicBoolean stop = new AtomicBoolean(false); Thread t1 = slowScan(c, tableName, stop); t1.start(); Thread t2 = slowScan(c, tableName, stop); t2.start(); sleepUninterruptibly(500, TimeUnit.MILLISECONDS); long now = System.currentTimeMillis(); try (Scanner s = c.createScanner(MetadataTable.NAME, Authorizations.EMPTY)) { Iterators.size(s.iterator()); } long delay = System.currentTimeMillis() - now; System.out.println("Delay = " + delay); assertTrue("metadata table scan was slow", delay < 1000); assertFalse(stop.get()); stop.set(true); t1.interrupt(); t2.interrupt(); t1.join(); t2.join(); }
Source:
<code>public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { Component c = defaultRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); ColumnImpl column = myTableHeaderFacade.findColumnByViewIndex(col); if (column.getSort() == SortOrder.ASCENDING) { <START> ((JLabel) c).setIcon(ascIcon); <END> } if (column.getSort() == SortOrder.DESCENDING) { ((JLabel) c).setIcon(descIcon); } return c; }</code><technical_language>Please add instanceof JLabel check. If default component is JLabel ignore (or replace JLabel?)</technical_language>

Target:
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { Component c = myDefaultRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); ColumnImpl column = myTableHeaderFacade.findColumnByViewIndex(col); if (column.getSort() == SortOrder.ASCENDING && c instanceof JLabel) { ((JLabel) c).setIcon(myAscIcon); } if (column.getSort() == SortOrder.DESCENDING && c instanceof JLabel) { ((JLabel) c).setIcon(myDescIcon); } return c; }
Source:
<code>private void executeActions(Rule rule) { List<Action> actions = ((RuntimeRule) rule).getActions(); if (actions == null || actions.size() == 0) { return; } <START> for (Iterator< Action>it = actions.iterator(); it.hasNext();) { <END> RuntimeAction a = (RuntimeAction) it.next(); ActionHandler aHandler = a.getModuleHandler(); try { String rUID = rule.getUID(); Map<String, Object> context = getContext(rUID, a.getConnections()); Map<String, ?> outputs = aHandler.execute(context); if (outputs != null) { context = getContext(rUID); updateContext(rUID, a.getId(), outputs); } } catch (Throwable t) { logger.error("Fail to execute the action: " + a.getId(), t); } } }</code><technical_language>incorrect space</technical_language>

Target:
private void executeActions(Rule rule) { List<Action> actions = ((RuntimeRule) rule).getActions(); if (actions == null || actions.size() == 0) { return; } RuleStatus ruleStatus = null; for (Iterator< Action>it = actions.iterator(); it.hasNext();) { ruleStatus = getRuleStatus(rule.getUID()); if (ruleStatus != RuleStatus.RUNNING) { return; } RuntimeAction a = (RuntimeAction) it.next(); ActionHandler aHandler = a.getModuleHandler(); try { String rUID = rule.getUID(); Map<String, Object> context = getContext(rUID, a.getConnections()); Map<String, ?> outputs = aHandler.execute(context); if (outputs != null) { context = getContext(rUID); updateContext(rUID, a.getId(), outputs); } } catch (Throwable t) { logger.error("Fail to execute the action: " + a.getId(), t); } } }
Source:
<code><START> public String getRequestUrl(String reqContext, String page) { <END> if (reqContext == null) { reqContext = DEFAULT_URL + DEFAULT_APP; } return reqContext + "/" + page; }</code><technical_language>tool methods static</technical_language>

Target:
public static String getRequestUrl(String reqContext, String page) { if (reqContext == null) { reqContext = DEFAULT_URL + DEFAULT_APP; } return reqContext + "/" + page; }
Source:
<code><START> private NetworkProviderProxy getProviderProxy() { if (providerProxy == null) { Provider<?> provider = providerDao.get(getNetwork().getProvidedBy().getProviderId()); providerProxy = providerProxyFactory.create(provider); } return providerProxy; } <END></code><technical_language>Avoid fetching provider db: private NetworkProviderProxy getProviderProxy() { if (providerProxy == null) { providerProxy = providerProxyFactory.create(getProvider()); } return providerProxy; } private Provider<OpenStackImageProviderProperties> getProvider() { if (provider == null) { provider = providerDao.get(getNetwork().getProvidedBy().getProviderId()); } return provider; }</technical_language>

Target:
private NetworkProviderProxy getProviderProxy() { if (providerProxy == null) { Provider<?> provider = getProvider(); providerProxy = providerProxyFactory.create(provider); } return providerProxy; }
Source:
<code>public void setup() { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy() .grant(Jenkins.READ, Item.READ, Item.DISCOVER, Item.CONFIGURE).everywhere().toAuthenticated() <START> .grant(Jenkins.MANAGE).everywhere().to("bob")); <END> }</code><technical_language>Revert this</technical_language>

Target:
public void setup() { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy() .grant(Jenkins.READ, Item.READ, Item.DISCOVER, Item.CONFIGURE).everywhere().toAuthenticated() .grant(Jenkins.ADMINISTER).everywhere().to("bob")); }
Source:
<code>public boolean createProcessesWithCalendar(ProcessDTO processDTO) { Collection<String> functionalDivisions; try { Process process = ServiceManager.getProcessService().getById(processDTO.getId()); Integer rulesetId = process.getRuleset().getId(); <START> List<Property> workpieceProperties = process.getWorkpieces(); String docType = ""; for (Property workpieceProperty : workpieceProperties) { <END> if ("DocType".equals(workpieceProperty.getTitle())) { docType = workpieceProperty.getValue(); break; } } if (rulesetCache.containsKey(rulesetId)) { functionalDivisions = rulesetCache.get(rulesetId); } else { Ruleset ruleset = ServiceManager.getRulesetService().getById(rulesetId); functionalDivisions = ServiceManager.getRulesetService().openRuleset(ruleset) .getFunctionalDivisions(FunctionalDivision.CREATE_CHILDREN_WITH_CALENDAR); rulesetCache.put(rulesetId, functionalDivisions); } if (functionalDivisions.contains(docType)) { return true; } } catch (IOException | DAOException e) { Helper.setErrorMessage(ERROR_READING, new Object[] {ObjectType.PROCESS.getTranslationSingular() }, logger, e); } return false; }</code><technical_language>suggestion String docType = ""; for (Property workpieceProperty : process.getWorkpieces()) {</technical_language>

Target:
public boolean createProcessesWithCalendar(ProcessDTO processDTO) { Collection<String> functionalDivisions; try { Process process = ServiceManager.getProcessService().getById(processDTO.getId()); Integer rulesetId = process.getRuleset().getId(); String docType = ""; for (Property workpieceProperty : process.getWorkpieces()) { if ("DocType".equals(workpieceProperty.getTitle())) { docType = workpieceProperty.getValue(); break; } } if (rulesetCache.containsKey(rulesetId)) { functionalDivisions = rulesetCache.get(rulesetId); } else { Ruleset ruleset = ServiceManager.getRulesetService().getById(rulesetId); functionalDivisions = ServiceManager.getRulesetService().openRuleset(ruleset) .getFunctionalDivisions(FunctionalDivision.CREATE_CHILDREN_WITH_CALENDAR); rulesetCache.put(rulesetId, functionalDivisions); } if (functionalDivisions.contains(docType)) { return true; } } catch (IOException | DAOException e) { Helper.setErrorMessage(ERROR_READING, new Object[] {ObjectType.PROCESS.getTranslationSingular() }, logger, e); } return false; }
Source:
<code>private static Registration createRegistration() { <START> File tempKeystoreFile = TestFileUtil.createUniqueTempFile(authorityKeystorePath); <END> X509CertificateGenerator certificateGenerator = new X509CertificateGenerator(); certificateGenerator.createAndStoreCACertificates(tempKeystoreFile); return certificateGenerator.createAgentCertificate(tempKeystoreFile, "blah"); }</code><technical_language>junit temporary folder rule manage temporary file creation</technical_language>

Target:
private Registration createRegistration() throws IOException { File tempKeystoreFile = tmpFolder.newFile(); X509CertificateGenerator certificateGenerator = new X509CertificateGenerator(); certificateGenerator.createAndStoreCACertificates(tempKeystoreFile); return certificateGenerator.createAgentCertificate(tempKeystoreFile, "blah"); }
Source:
<code>private void canClose(Collection<URI> uris) { String exceptionMessagePrefix = "The lock cannot be released because there are still streams flowing for the following URIs: "; <START> String exceptionMessage = uris.parallelStream().filter(uri -> streamManagement.isKnowingAnOpenStreamTo(uri)) <END> .map(uri -> uri.toString()).collect(Collectors.joining(", ", exceptionMessagePrefix, "")); if (exceptionMessage.length() > exceptionMessagePrefix.length()) { throw new IllegalStateException(exceptionMessage); } }</code><technical_language>Lambda replaced method reference</technical_language>

Target:
private void canClose(Collection<URI> uris) { String exceptionMessagePrefix = "The lock cannot be released because there are still streams flowing for the following URIs: "; String exceptionMessage = uris.parallelStream().filter(streamManagement::isKnowingAnOpenStreamTo) .map(uri -> uri.toString()).collect(Collectors.joining(", ", exceptionMessagePrefix, "")); if (exceptionMessage.length() > exceptionMessagePrefix.length()) { throw new IllegalStateException(exceptionMessage); } }
Source:
<code>private void addAndOr(CodeWriter code, CondStack stack, IfCondition condition) throws CodegenException { Mode mode = condition.getMode(); String modeStr = mode == Mode.AND ? " && " : " || "; Iterator<IfCondition> it = condition.getArgs().iterator(); while (it.hasNext()) { IfCondition next = it.next(); if (next.getMode() == mode) { add(code, stack, next); } else { wrap(code, stack, next); <START> } <END> if (it.hasNext()) { code.add(modeStr); } } }</code><technical_language>check: is move this mode check wrap method contains call: boolean wrap = isWrapNeeded(cond); isWrapNeeded method? I prefer localize logic in code generators - optimizations in visitors codegen flags (like DONT_WRAP)</technical_language>

Target:
private void addAndOr(CodeWriter code, CondStack stack, IfCondition condition) throws CodegenException { String mode = condition.getMode() == Mode.AND ? " && " : " || "; Iterator<IfCondition> it = condition.getArgs().iterator(); while (it.hasNext()) { wrap(code, stack, it.next()); if (it.hasNext()) { code.add(mode); } } }
Source:
<code>protected String getParagraphNumber(ArtifactReadable artifact, String templateContent) { String startParagraphNumber = "1"; Matcher matcher = headElementsPattern.matcher(templateContent); if (matcher.find()) { String elementType = matcher.group(0); <START> if (elementType != null && elementType.equals(INSERT_ARTIFACT_HERE)) { <END> if (artifact.isAttributeTypeValid(ParagraphNumber)) { String paragraphNum = artifact.getSoleAttributeValue(ParagraphNumber, ""); if (Strings.isValid(paragraphNum)) { startParagraphNumber = paragraphNum; } } } } return startParagraphNumber; }</code><technical_language>need check validity of attr type getSole..</technical_language>

Target:
protected String getParagraphNumber(ArtifactReadable artifact, String templateContent) { String startParagraphNumber = "1"; Matcher matcher = headElementsPattern.matcher(templateContent); if (matcher.find()) { String elementType = matcher.group(0); if (elementType != null && elementType.equals(INSERT_ARTIFACT_HERE)) { String paragraphNum = artifact.getSoleAttributeValue(ParagraphNumber, ""); if (Strings.isValid(paragraphNum)) { startParagraphNumber = paragraphNum; } } } return startParagraphNumber; }
Source:
<code>public final PartitionDescProto getPartition(final String databaseName, final String tableName, final String partitionName) <START> throws UndefinedPartitionException, UndefinedPartitionMethodException { <END> try { final BlockingInterface stub = getStub(); final PartitionIdentifierProto request = PartitionIdentifierProto.newBuilder() .setDatabaseName(databaseName) .setTableName(tableName) .setPartitionName(partitionName) .build(); final GetPartitionDescResponse response = stub.getPartitionByPartitionName(null, request); throwsIfThisError(response.getState(), UndefinedPartitionMethodException.class); throwsIfThisError(response.getState(), UndefinedPartitionException.class); ensureOk(response.getState()); return response.getPartition(); } catch (ServiceException e) { throw new RuntimeException(e); } }</code><technical_language>UndefinedDatabaseException UndefinedTableExeption occur</technical_language>

Target:
public final PartitionDescProto getPartition(final String databaseName, final String tableName, final String partitionName) throws UndefinedDatabaseException, UndefinedTableException, UndefinedPartitionException, UndefinedPartitionMethodException { try { final BlockingInterface stub = getStub(); final PartitionIdentifierProto request = PartitionIdentifierProto.newBuilder() .setDatabaseName(databaseName) .setTableName(tableName) .setPartitionName(partitionName) .build(); final GetPartitionDescResponse response = stub.getPartitionByPartitionName(null, request); throwsIfThisError(response.getState(), UndefinedDatabaseException.class); throwsIfThisError(response.getState(), UndefinedTableException.class); throwsIfThisError(response.getState(), UndefinedPartitionMethodException.class); throwsIfThisError(response.getState(), UndefinedPartitionException.class); ensureOk(response.getState()); return response.getPartition(); } catch (ServiceException e) { throw new RuntimeException(e); } }
Source:
<code>public Encounter createEncounter(String configName, DateTime encounterDatetime, String encounterType, String locationName, String patientUuid, String providerUuid, String visitUuid, String formUuid, Map<String, String> observations) { Location location = getLocationByName(configName, locationName); Patient patient = patientService.getPatientByUuid(configName, patientUuid); Provider provider = providerService.getProviderByUuid(configName, providerUuid); Visit visit = null; Form form = null; if (StringUtils.isNotEmpty(visitUuid)) { visit = visitService.getVisitByUuid(configName, visitUuid); } if (StringUtils.isNotEmpty(formUuid)) { form = formService.getFormByUuid(configName, formUuid); } List<Observation> observationList = MapUtils.isNotEmpty(observations) ? convertObservationMapToList(observations, encounterDatetime) : null; <START> EncounterType type = new EncounterType(encounterType, null); <END> Encounter encounter = new Encounter(location, type, encounterDatetime.toDate(), patient, visit, Collections.singletonList(provider.getPerson()), observationList, form); return encounterService.createEncounter(configName, encounter); }</code><technical_language>new EncounterType(null, encounterType). Uuid is a parameter in constructor</technical_language>

Target:
public Encounter createEncounter(String configName, DateTime encounterDatetime, String encounterType, String locationName, String patientUuid, String providerUuid, String visitUuid, String formUuid, Map<String, String> observations) { Location location = getLocationByName(configName, locationName); Patient patient = patientService.getPatientByUuid(configName, patientUuid); Provider provider = providerService.getProviderByUuid(configName, providerUuid); Visit visit = null; Form form = null; if (StringUtils.isNotEmpty(visitUuid)) { visit = visitService.getVisitByUuid(configName, visitUuid); } if (StringUtils.isNotEmpty(formUuid)) { form = formService.getFormByUuid(configName, formUuid); } List<Observation> observationList = MapUtils.isNotEmpty(observations) ? convertObservationMapToList(observations, encounterDatetime) : null; EncounterType type = new EncounterType(null, encounterType); Encounter encounter = new Encounter(location, type, encounterDatetime.toDate(), patient, visit, Collections.singletonList(provider.getPerson()), observationList, form); return encounterService.createEncounter(configName, encounter); }
Source:
<code>public static void setCustomTags(final Scope scope, final Map<String, Object> tags) { for (final Map.Entry<String, Object> entry : tags.entrySet()) { if (entry.getValue() instanceof Boolean) { scope.span().setTag(entry.getKey(), (Boolean) entry.getValue()); } else if (entry.getValue() instanceof Number) { scope.span().setTag(entry.getKey(), (Number) entry.getValue()); } else if (entry.getValue() instanceof String) { scope.span().setTag(entry.getKey(), (String) entry.getValue()); } else { <START> LOG.error("Tag is not of the expected type"); <END> continue; } } }</code><technical_language>I this warn break code</technical_language>

Target:
public static void setCustomTags(final Scope scope, final Map<String, Object> tags) { for (final Map.Entry<String, Object> entry : tags.entrySet()) { if (entry.getValue() instanceof Boolean) { scope.span().setTag(entry.getKey(), (Boolean) entry.getValue()); } else if (entry.getValue() instanceof Number) { scope.span().setTag(entry.getKey(), (Number) entry.getValue()); } else if (entry.getValue() instanceof String) { scope.span().setTag(entry.getKey(), (String) entry.getValue()); } else { LOG.warn("Tag is not of the expected type"); continue; } } }
Source:
<code>public String asSummaryString() { <START> return "filesystem"; <END> }</code><technical_language>Filesystem</technical_language>

Target:
public String asSummaryString() { return "Filesystem"; }
Source:
<code>public Builder networks(final Map<String, AttachedNetwork> networks) { if (networks != null) { <START> final ImmutableMap.Builder<String, AttachedNetwork> builder = ImmutableMap.builder(); <END> for (Map.Entry<String, AttachedNetwork> entry : networks.entrySet()) { builder.put(entry.getKey(), entry.getValue()); } this.networks = builder.build(); } return this; }</code><technical_language>I replace in this if this.networks = ImmutableMap.copyOf(networks);</technical_language>

Target:
public Builder networks(final Map<String, AttachedNetwork> networks) { if (networks != null) { this.networks = ImmutableMap.copyOf(networks); } return this; }
Source:
<code>public RestTemplate newRestTemplate(String serviceUrl) { <START> RestTemplate restTemplate = new RestTemplate(); <END> try { URI serviceURI = new URI(serviceUrl); if (serviceURI.getUserInfo() != null) { String[] credentials = serviceURI.getUserInfo().split(":"); if (credentials.length == 2) { restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor( credentials[0], credentials[1])); } } } catch (URISyntaxException ignore) { } return restTemplate; }</code><technical_language>Shouldnt RestTemplateBuilder</technical_language>

Target:
public RestTemplate newRestTemplate(String serviceUrl) { RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); try { URI serviceURI = new URI(serviceUrl); if (serviceURI.getUserInfo() != null) { String[] credentials = serviceURI.getUserInfo().split(":"); if (credentials.length == 2) { restTemplateBuilder.interceptors(new BasicAuthorizationInterceptor( credentials[0], credentials[1])); } } } catch (URISyntaxException ignore) { } return restTemplateBuilder.build(); }
Source:
<code>public GroupArrayAggregationState(Type type) { this.type = type; this.headBlockIndex = new ShortBigArray(NULL); this.headPosition = new IntBigArray(NULL); this.nextBlockIndex = new ShortBigArray(NULL); this.nextPosition = new IntBigArray(NULL); this.tailAbsoluteAddress = new LongBigArray(NULL); this.pageBuilder = new PageBuilder(ImmutableList.of(type)); this.values = new ArrayList<>(); this.sumPositions = new LongArrayList(); values.add(getCurrentBlockBuilder()); <START> sumPositions.add(0L); <END> valueBlocksRetainedSizeInBytes = 0; totalPositions = 0; capacity = 1024; nextBlockIndex.ensureCapacity(capacity); nextPosition.ensureCapacity(capacity); }</code><technical_language>understand PageBuilder sometime, i peruse code. assuming behave implicit in contract here, a list of BlockBuilders manage full, allocate another</technical_language>

Target:
public GroupArrayAggregationState(Type type) { this.type = type; this.headBlockIndex = new ShortBigArray(NULL); this.headPosition = new IntBigArray(NULL); this.nextBlockIndex = new ShortBigArray(NULL); this.nextPosition = new IntBigArray(NULL); this.tailBlockIndex = new ShortBigArray(NULL); this.tailPosition = new IntBigArray(NULL); this.pageBuilderStatus = new PageBuilderStatus(MAX_BLOCK_SIZE, MAX_BLOCK_SIZE); this.currentBlockBuilder = type.createBlockBuilder(pageBuilderStatus.createBlockBuilderStatus(), 16); this.values = new ArrayList<>(); this.sumPositions = new LongArrayList(); values.add(currentBlockBuilder); sumPositions.add(0L); valueBlocksRetainedSizeInBytes = 0; totalPositions = 0; capacity = 1024; nextBlockIndex.ensureCapacity(capacity); nextPosition.ensureCapacity(capacity); }
Source:
<code>public Long getPosition(StreamPartition<Integer> partition) { <START> try { <END> return consumer.position(new TopicPartition(partition.getStream(), partition.getPartitionId())); } catch (TimeoutException e) { throw new PossiblyTransientStreamException(e); } catch (WakeupException | InterruptException e) { throw new TransientStreamException(e); } catch (KafkaException e) { throw new NonTransientStreamException(e); } }</code><technical_language>wrapping calls in assign(), seek(), seekToEarliest(), seekToLatest(), getAssignment()</technical_language>

Target:
public Long getPosition(StreamPartition<Integer> partition) { return wrapExceptions(() -> consumer.position(new TopicPartition( partition.getStream(), partition.getPartitionId() ))); }
Source:
<code>public void testFailureOnAllPollThatSends() throws Exception { router = getNonBlockingRouter(); setOperationParams(chunkSize); String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel).get(); mockSelectorState.set(MockSelectorState.ThrowExceptionOnSend); FutureResult futureResult; try { <START> futureResult = (FutureResult) router.getBlobInfo(blobId); <END> while (!futureResult.isDone()) { mockTime.sleep(routerConfig.routerRequestTimeoutMs + 1); Thread.yield(); } futureResult.get(); Assert.fail("operation should have thrown"); } catch (ExecutionException e) { RouterException routerException = (RouterException) e.getCause(); Assert.assertEquals("Exception received should be router closed error", RouterErrorCode.OperationTimedOut, routerException.getErrorCode()); } try { futureResult = (FutureResult) router.getBlob(blobId); while (!futureResult.isDone()) { mockTime.sleep(routerConfig.routerRequestTimeoutMs + 1); Thread.yield(); } futureResult.get(); Assert.fail("operation should have thrown"); } catch (ExecutionException e) { RouterException routerException = (RouterException) e.getCause(); Assert.assertEquals("Exception received should be router closed error", RouterErrorCode.OperationTimedOut, routerException.getErrorCode()); } router.close(); }</code><technical_language>I need cast. Future supports isDone() - this is API use</technical_language>

Target:
public void testFailureOnAllPollThatSends() throws Exception { router = getNonBlockingRouter(); setOperationParams(chunkSize); String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel).get(); mockSelectorState.set(MockSelectorState.ThrowExceptionOnSend); Future future; try { future = router.getBlobInfo(blobId); while (!future.isDone()) { mockTime.sleep(routerConfig.routerRequestTimeoutMs + 1); Thread.yield(); } future.get(); Assert.fail("operation should have thrown"); } catch (ExecutionException e) { RouterException routerException = (RouterException) e.getCause(); Assert.assertEquals(RouterErrorCode.OperationTimedOut, routerException.getErrorCode()); } try { future = router.getBlob(blobId); while (!future.isDone()) { mockTime.sleep(routerConfig.routerRequestTimeoutMs + 1); Thread.yield(); } future.get(); Assert.fail("operation should have thrown"); } catch (ExecutionException e) { RouterException routerException = (RouterException) e.getCause(); Assert.assertEquals(RouterErrorCode.OperationTimedOut, routerException.getErrorCode()); } router.close(); }
Source:
<code>public void testResetToNonexistingHEAD() throws JGitInternalException, AmbiguousObjectException, IOException { git = new Git(db); writeTrashFile("f", "content"); try { git.reset().setRef(Constants.HEAD).call(); <START> fail("Excpected JGitInternalException didn't occured"); <END> } catch (JGitInternalException e) { } }</code><technical_language>s/Excpected/Expected/</technical_language>

Target:
public void testResetToNonexistingHEAD() throws JGitInternalException, AmbiguousObjectException, IOException { git = new Git(db); writeTrashFile("f", "content"); try { git.reset().setRef(Constants.HEAD).call(); fail("Expected JGitInternalException didn't occur"); } catch (JGitInternalException e) { } }
Source:
<code>protected String getLocalAddressString(SSLSocket socket) { <START> InetAddress addr <END> = socket.getLocalAddress(); return String.format( (addr instanceof Inet6Address ? "[%s]:%d" : "%s:%d"), addr.getHostAddress(), socket.getLocalPort()); }</code><technical_language>final</technical_language>

Target:
protected String getLocalAddressString(SSLSocket socket) { final InetAddress addr = socket.getLocalAddress(); return String.format( (addr instanceof Inet6Address ? "[%s]:%d" : "%s:%d"), addr.getHostAddress(), socket.getLocalPort()); }
Source:
<code>public void extendTicket(Guid ticketUUID, long timeout) { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "PATCH", TICKETS_URI + ticketUUID, HttpVersion.HTTP_1_1); Map<String, Object> timeoutDict = new HashMap<>(); timeoutDict.put("timeout", timeout); StringEntity entity = new StringEntity(new Gson().toJson(timeoutDict), StandardCharsets.UTF_8); request.setEntity(entity); request.setHeader("content-length", <START> String.valueOf(request.getEntity().getContentLength())); <END> HttpEntity response = executeRequest(request); consumeEntity(response); }</code><technical_language>entity</technical_language>

Target:
public void extendTicket(Guid ticketUUID, long timeout) { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( "PATCH", TICKETS_URI + ticketUUID, HttpVersion.HTTP_1_1); Map<String, Object> timeoutDict = new HashMap<>(); timeoutDict.put("timeout", timeout); StringEntity entity = new StringEntity(new Gson().toJson(timeoutDict), StandardCharsets.UTF_8); request.setEntity(entity); request.setHeader("content-length", String.valueOf(entity.getContentLength())); HttpEntity response = executeRequest(request); consumeResponse(response); }
Source:
<code>public ValidationReport validate(String uri, InputStream inputstream, NestedValidatorContext context) { String fileName = uri.substring(uri.lastIndexOf("/")+1); String viewName = getViewName(fileName); IRepositoryViewObject viewObj = RepositoryResourceUtil.findViewObjectByName(IServerObjectRepositoryType.TYPE_VIEW, viewName); if (viewObj != null) { ViewValidationReport viewValidationReport = null; WSViewItem item = (WSViewItem) viewObj.getProperty().getItem(); WSViewE view = (WSViewE)item.getMDMServerObject(); EList<WSWhereConditionE> whereConditions = view.getWhereConditions(); if(whereConditions != null && whereConditions.size() >0) { viewValidationReport = new ViewValidationReport(uri); for (WSWhereConditionE conditionE : whereConditions) { String userVarValue = conditionE.getRightValueOrPath(); boolean isValid = UserVarValueValidator.validate(userVarValue); if(!isValid) { <START> String validateMsg = Messages.ViewValidator_0 + userVarValue + Messages.ViewValidator_1 + viewName +Messages.ViewValidator_2; <END> viewValidationReport.addValidationMessage(new ValidationMessage(validateMsg, -1, -1)); } } } return viewValidationReport; } return null; }</code><technical_language>Messages.bind method instead of "ViewValidator_0","ViewValidator_1" "ViewValidator_2", need variable definitions</technical_language>

Target:
public ValidationReport validate(String uri, InputStream inputstream, NestedValidatorContext context) { ViewValidationReport viewValidationReport = new ViewValidationReport(uri); String fileName = uri.substring(uri.lastIndexOf("/")+1); String viewName = getViewName(fileName); viewName = viewName.replace("$", "#"); IRepositoryViewObject viewObj = RepositoryResourceUtil.findViewObjectByName(IServerObjectRepositoryType.TYPE_VIEW, viewName); if (viewObj != null) { WSViewItem item = (WSViewItem) viewObj.getProperty().getItem(); WSViewE view = (WSViewE)item.getMDMServerObject(); EList<WSWhereConditionE> whereConditions = view.getWhereConditions(); if(whereConditions != null && whereConditions.size() >0) { for (WSWhereConditionE conditionE : whereConditions) { String userVarValue = conditionE.getRightValueOrPath(); boolean isValid = UserVarValueValidator.validate(userVarValue); if(!isValid) { String validateMsg = Messages.bind(Messages.ViewValidator_error, userVarValue,viewName); viewValidationReport.addValidationMessage(new ValidationMessage(validateMsg, -1, -1)); } } } } return viewValidationReport; }
Source:
<code>public CommCareApp getCurrentApp() { if (currentApp != null) { <START> System.out.println("current app has display name: " + this.currentApp.getAppRecord().getDisplayName()); <END> } return this.currentApp; }</code><technical_language>drop printlns this file</technical_language>

Target:
public CommCareApp getCurrentApp() { return this.currentApp; }
Source:
<code><START> public String[] toClassMethodNameWithoutPlan( TestIdentifier testIdentifier ) <END> { Optional<TestSource> testSource = testIdentifier.getSource(); String display = testIdentifier.getDisplayName(); if ( testSource.filter( MethodSource.class::isInstance ).isPresent() ) { MethodSource methodSource = testSource.map( MethodSource.class::cast ).get(); String realClassName = methodSource.getClassName(); String[] source = new String[] {realClassName, realClassName}; String methodName = methodSource.getMethodName(); boolean useMethod = display.equals( methodName ) || display.equals( methodName + "()" ); String resolvedMethodName = useMethod ? methodName : display; return new String[] {source[0], source[1], methodName, resolvedMethodName}; } else if ( testSource.filter( ClassSource.class::isInstance ).isPresent() ) { ClassSource classSource = testSource.map( ClassSource.class::cast ).get(); String className = classSource.getClassName(); String simpleClassName = className.substring( 1 + className.lastIndexOf( '.' ) ); String source = display.equals( simpleClassName ) ? className : display; return new String[] {className, source, null, null}; } else { String source = testPlan == null ? display : testPlan.getParent( testIdentifier ).map( TestIdentifier::getDisplayName ).orElse( display ); return new String[] {source, source, display, display}; } }</code><technical_language>I totally convinced this method is returns String[4]. I vote for a generic approach avoiding code duplication in single class</technical_language>

Target:
public String[] toClassMethodNameWithoutPlan( TestIdentifier testIdentifier ) { return toClassMethodName( testIdentifier, false ); }
Source:
<code>public void getBulkWithBadArgs() throws Exception { final Arguments args = new Arguments(new String[]{"ds3_java_cli", "-e", "localhost:8080", "-k", "key!", "-a", "access", "-c", "get_bulk", "-b", "bucketName", "-d", "targetdir", "--discard"}); final String expected = "Error (BadArgumentException): Cannot set both directory and --discard"; final Ds3ClientHelpers helpers = mock(Ds3ClientHelpers.class); final Ds3ClientHelpers.Job mockedGetJob = mock(Ds3ClientHelpers.Job.class); final FileUtils mockedFileUtils = mock(FileUtils.class); when(helpers.startReadAllJob(eq("bucketName"), any(ReadJobOptions.class))).thenReturn(mockedGetJob); final Ds3Cli cli = new Ds3Cli(new Ds3ProviderImpl(null, helpers), args, mockedFileUtils); try { final CommandResponse result = cli.call(); <START> } catch (Exception e) { <END> final Ds3ExceptionHandlerMapper exception = Ds3ExceptionHandlerMapper.getInstance(); final DefaultExceptionHandler handler = new DefaultExceptionHandler(); final String formattedException = handler.format(e); assertThat(formattedException, is(expected)); } }</code><technical_language>Missing final</technical_language>

Target:
public void getBulkWithBadArgs() throws Exception { final Arguments args = new Arguments(new String[]{"ds3_java_cli", "-e", "localhost:8080", "-k", "key!", "-a", "access", "-c", "get_bulk", "-b", "bucketName", "-d", "targetdir", "--discard"}); final String expected = "Error (BadArgumentException): Cannot set both directory and --discard"; final Ds3ClientHelpers helpers = mock(Ds3ClientHelpers.class); final Ds3ClientHelpers.Job mockedGetJob = mock(Ds3ClientHelpers.Job.class); final FileUtils mockedFileUtils = mock(FileUtils.class); when(helpers.startReadAllJob(eq("bucketName"), any(ReadJobOptions.class))).thenReturn(mockedGetJob); final Ds3Cli cli = new Ds3Cli(new Ds3ProviderImpl(null, helpers), args, mockedFileUtils); try { final CommandResponse result = cli.call(); } catch (final Exception e) { final Ds3ExceptionHandlerMapper exception = Ds3ExceptionHandlerMapper.getInstance(); final DefaultExceptionHandler handler = new DefaultExceptionHandler(); final String formattedException = handler.format(e); assertThat(formattedException, is(expected)); } }
Source:
<code>public int run() throws IOException { try { byte[] buf = new byte[8192]; int length = in.read(buf); if (length != -1) { aOut.write(buf, 0, length); size += length; return length; } else { aOut.close(); AnyLongObjectId loid = aOut.getId(); aOut = null; Path mediaFile = lfsUtil.getMediaFile(loid); if (Files.isRegularFile(mediaFile)) { long fsSize = Files.size(mediaFile); if (fsSize != size) { throw new CorruptMediaFile(mediaFile, size, fsSize); } else { FileUtils.delete(tmpFile.toFile()); } } else { Path parent = mediaFile.getParent(); if (parent != null) { FileUtils.mkdirs(parent.toFile(), true); } FileUtils.rename(tmpFile.toFile(), mediaFile.toFile(), StandardCopyOption.ATOMIC_MOVE); } LfsPointer lfsPointer = new LfsPointer(loid, size); lfsPointer.encode(out); <START> in.close(); <END> out.close(); return -1; } } catch (IOException e) { if (aOut != null) { aOut.abort(); } in.close(); out.close(); throw e; } }</code><technical_language>move this extra commit fixing unclosed streams</technical_language>

Target:
public int run() throws IOException { try { byte[] buf = new byte[8192]; int length = in.read(buf); if (length != -1) { aOut.write(buf, 0, length); size += length; return length; } else { aOut.close(); AnyLongObjectId loid = aOut.getId(); aOut = null; Path mediaFile = lfsUtil.getMediaFile(loid); if (Files.isRegularFile(mediaFile)) { long fsSize = Files.size(mediaFile); if (fsSize != size) { throw new CorruptMediaFile(mediaFile, size, fsSize); } else { FileUtils.delete(tmpFile.toFile()); } } else { Path parent = mediaFile.getParent(); if (parent != null) { FileUtils.mkdirs(parent.toFile(), true); } FileUtils.rename(tmpFile.toFile(), mediaFile.toFile(), StandardCopyOption.ATOMIC_MOVE); } LfsPointer lfsPointer = new LfsPointer(loid, size); lfsPointer.encode(out); out.close(); return -1; } } catch (IOException e) { if (aOut != null) { aOut.abort(); } out.close(); throw e; } }