auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Region getSecondLevelCacheRegion(String regionName) { Region region = entityRegionMap.get(regionName); if ( region != null ) { return region; } region = collectionRegionMap.get( regionName ); if ( region != null ) { return region; } <START> return getNonEntityNonCollectionRegions().get( regionName ); <END> }</code><technical_language>getNonEntityNonCollectionRegions creates a copy of collections, lookup other maps..</technical_language>

Target:
public Region getSecondLevelCacheRegion(String regionName) { Region region = entityRegionMap.get(regionName); if ( region != null ) { return region; } region = collectionRegionMap.get( regionName ); if ( region != null ) { return region; } region = naturalIdRegionMap.get( regionName ); if ( region != null ) { return region; } region = otherRegionMap.get( regionName ); if ( region != null ) { return region; } for ( QueryCache queryCacheValue : queryCaches.values() ) { if( queryCacheValue.getRegion().getName().equals( regionName ) ) { return queryCacheValue.getRegion(); } } if ( queryCache.getRegion().getName().equals( regionName ) ) { return queryCache.getRegion(); } if ( updateTimestampsCache.getRegion().getName().equals( regionName ) ) { return updateTimestampsCache.getRegion(); } return null; }
Source:
<code>public JComponent createComponent() { <START> configurationForm = new ConfigANTLRPerGrammar(project, ANTLRv4GrammarProperties.PROJECT_SETTINGS_PREFIX); <END> return configurationForm.getRootPane(); }</code><technical_language>is a good idea reuse this component, find a hide Cancel Save buttons, redundant other provided default IntelliJ: <img width="749" alt="image" src="<LINK_1>"> Also, nice implement isModified() correctly Apply button is enabled actual modifications made. moment, menu title appears in blue if modified, I change anything: <img width="227" alt="image" src="<LINK_0>"></technical_language>

Target:
public JComponent createComponent() { configurationForm = ConfigANTLRPerGrammar.getProjectSettingsForm(project, ANTLRv4GrammarProperties.PROJECT_SETTINGS_PREFIX); return configurationForm.$$$getRootComponent$$$(); }
Source:
<code><START> public Map<Guid, VdcObjectType> getPermissionCheckSubjects() { <END> return Collections.singletonMap(getQuotaId() == null ? null : getQuotaId().getValue(), VdcObjectType.Quota); }</code><technical_language>this fail, ask is user permissions quota create yet. add quota ask for permission parent, is storage pool</technical_language>

Target:
public Map<Guid, VdcObjectType> getPermissionCheckSubjects() { return Collections.singletonMap(getStoragePoolId() == null ? null : getStoragePoolId().getValue(), VdcObjectType.StoragePool); }
Source:
<code>public void lockResponeHasCorrectLeasedLock() { LockRequest lockRequest = mock(LockRequest.class); Lease lease = getLease(); when(timelockService.leasableLock(lockRequest)).thenReturn( LeasableLockResponse.of(LOCK_RESPONSE, lease)); LockResponse clientResponse = timelockClient.lock(lockRequest); LeasedLockToken leasedLockToken = (LeasedLockToken) clientResponse.getToken(); <START> assertEquals(LOCK_TOKEN, leasedLockToken.serverToken()); <END> assertEquals(lease, leasedLockToken.getLease()); }</code><technical_language>assertEquals, error-prone (people flip expected actual time). Prefer assertThat().isEqualTo() time</technical_language>

Target:
public void lockResponeHasCorrectLeasedLock() { Lease lease = getLease(); when(timelockRpcClient.lockV2(lockRequest)).thenReturn( LeasableLockResponse.of(LOCK_RESPONSE, lease)); LockResponse clientResponse = timelockService.lock(lockRequest); verify(timelockRpcClient).lockV2(lockRequest); LeasedLockToken leasedLockToken = (LeasedLockToken) clientResponse.getToken(); assertThat(leasedLockToken.serverToken()).isEqualTo(LOCK_TOKEN); assertThat(leasedLockToken.getLease()).isEqualTo(lease); }
Source:
<code>private Context startProcessTracingSpan(EventData eventData, String eventHubName, String fullyQualifiedNamespace) { Object diagnosticId = eventData.getProperties().get(DIAGNOSTIC_ID_KEY); if (diagnosticId == null || !tracerProvider.isEnabled()) { return Context.NONE; } Context spanContext = tracerProvider.extractContext(diagnosticId.toString(), Context.NONE) .addData(ENTITY_PATH_KEY, eventHubName).addData(HOST_NAME_KEY, fullyQualifiedNamespace); <START> return tracerProvider.startSpan(spanContext.addData(AZ_NAMESPACE_KEY, AZ_NAMESPACE_VALUE), <END> ProcessKind.PROCESS); }</code><technical_language>easier reason if chained .addData(NAMESPACE...) declaration here</technical_language>

Target:
private Context startProcessTracingSpan(EventData eventData, String eventHubName, String fullyQualifiedNamespace) { Object diagnosticId = eventData.getProperties().get(DIAGNOSTIC_ID_KEY); if (diagnosticId == null || !tracerProvider.isEnabled()) { return Context.NONE; } Context spanContext = tracerProvider.extractContext(diagnosticId.toString(), Context.NONE) .addData(ENTITY_PATH_KEY, eventHubName) .addData(HOST_NAME_KEY, fullyQualifiedNamespace) .addData(AZ_TRACING_NAMESPACE_KEY, AZ_NAMESPACE_VALUE); return tracerProvider.startSpan(spanContext, ProcessKind.PROCESS); }
Source:
<code>public boolean isPurposeFor(CallbackProperties properties) { NHIN_SERVICE_NAMES serviceName; boolean purposeFor = false; String action = properties.getAction(); serviceName = NHIN_SERVICE_NAMES.fromValueString(action); if (null == serviceName) { <START> LOG.warn("Could not read purpose of / for action: service name is null"); <END> return purposeFor; } GATEWAY_API_LEVEL apiLevel = properties.getTargetApiLevel(); String hcid = properties.getTargetHomeCommunityId(); if (hcid.startsWith(NhincConstants.HCID_PREFIX)) { hcid = hcid.replace(NhincConstants.HCID_PREFIX, ""); } if (apiLevel == null && hcid != null) { NhinEndpointManager nem = getNhinEndpointManager(); apiLevel = nem.getApiVersion(hcid, serviceName); } if (GATEWAY_API_LEVEL.LEVEL_g0 == apiLevel) { PurposeUseProxy purposeUse = getPurposeUseProxyObjectFactory(); purposeFor = purposeUse.isPurposeForUseEnabled(properties); } if (LOG.isDebugEnabled()) { logPurposeDecision(purposeFor, hcid, serviceName.getUDDIServiceName()); } return purposeFor; }</code><technical_language>include action name for troubleshooting on</technical_language>

Target:
public boolean isPurposeFor(CallbackProperties properties) { NHIN_SERVICE_NAMES serviceName; boolean purposeFor = false; String action = properties.getAction(); serviceName = NHIN_SERVICE_NAMES.fromValueString(action); if (null == serviceName) { LOG.warn("Could not read purpose of / for action: service name is null for action {}", action); return purposeFor; } GATEWAY_API_LEVEL apiLevel = properties.getTargetApiLevel(); String hcid = properties.getTargetHomeCommunityId(); if (hcid.startsWith(NhincConstants.HCID_PREFIX)) { hcid = hcid.replace(NhincConstants.HCID_PREFIX, ""); } if (apiLevel == null && hcid != null) { NhinEndpointManager nem = getNhinEndpointManager(); apiLevel = nem.getApiVersion(hcid, serviceName); } if (GATEWAY_API_LEVEL.LEVEL_g0 == apiLevel) { PurposeUseProxy purposeUse = getPurposeUseProxyObjectFactory(); purposeFor = purposeUse.isPurposeForUseEnabled(properties); } if (LOG.isDebugEnabled()) { logPurposeDecision(purposeFor, hcid, serviceName.getUDDIServiceName()); } return purposeFor; }
Source:
<code>private TestWithParameters createTestWithNotNormalizedParameters( String pattern, int index, Object parametersOrSingleParameter) { Object[] parameters = (parametersOrSingleParameter instanceof Object[]) ? (Object[]) parametersOrSingleParameter : new Object[] { parametersOrSingleParameter }; if (parameterCount == null) { parameterCount = parameters.length; <START> } <END> return createTestWithParameters(testClass, pattern, index, parameters); }</code><technical_language>If number of parameters for some parameter sets, get a failure child runner is run</technical_language>

Target:
private TestWithParameters createTestWithNotNormalizedParameters( String pattern, int index, Object parametersOrSingleParameter) { Object[] parameters = normalizeParameters(parametersOrSingleParameter); return createTestWithParameters(testClass, pattern, index, parameters); }
Source:
<code>private void readReplScope(String line) throws IOException { if (line == null) { return; } String[] lineContents = line.split("\t"); replScope = new ReplScope(); for (int idx = 0; idx < lineContents.length; idx++) { String value = lineContents[idx]; switch (idx) { case 0: LOG.info("Read ReplScope: Set Db Name: {}.", value); replScope.setDbName(value); break; case 1: LOG.info("Read ReplScope: Include table name list: {}.", value); replScope.setIncludedTablePatterns(value); break; case 2: LOG.info("Read ReplScope: Exclude table name list: {}.", value); replScope.setExcludedTablePatterns(value); break; default: <START> LOG.warn("Found invalid info " + value + " in the repl dump file while reading ReplScope"); <END> break; } } }</code><technical_language>throw exception here. is point in moving if this is incorrect</technical_language>

Target:
private void readReplScope(String line) throws IOException { if (line == null) { return; } String[] lineContents = line.split("\t"); replScope = new ReplScope(); for (int idx = 0; idx < lineContents.length; idx++) { String value = lineContents[idx]; switch (idx) { case 0: LOG.info("Read ReplScope: Set Db Name: {}.", value); replScope.setDbName(value); break; case 1: LOG.info("Read ReplScope: Include table name list: {}.", value); replScope.setIncludedTablePatterns(value); break; case 2: LOG.info("Read ReplScope: Exclude table name list: {}.", value); replScope.setExcludedTablePatterns(value); break; default: throw new IOException("Invalid repl tables list data in dump metadata file"); } } }
Source:
<code><START> public static Boolean isCorrelationIdAvailable(NHttpConnection connection) { <END> if (connection != null && connection.getContext() != null && connection.getContext().getAttribute(PassThroughConstants.CORRELATION_ID) != null) { return true; } return false; }</code><technical_language>connection context null this point</technical_language>

Target:
public static Boolean isCorrelationIdAvailable(NHttpConnection connection) { if (connection.getContext().getAttribute(PassThroughConstants.CORRELATION_ID) != null) { return true; } return false; }
Source:
<code>public String getPaginationRangeLabel() { int page = this.model.getPage(); int size = this.model.getPageSize(); <START> long index = page * size; <END> long total = this.model.getTotalItems(); long range = index + size; index++; if (index < 0) { index = 0; } if (index > total) { index = total; } if (range < total) { return index + " - " + range; } else { return index + " - " + total; } }</code><technical_language>compose this method smaller methods method name explains</technical_language>

Target:
public String getPaginationRangeLabel() { int page = this.model.getPage(); int size = this.model.getPageSize(); long total = this.model.getTotalItems(); long firstJobIndex = Math.min(Math.max(page * size + 1, 0), total); long lastJobIndex = Math.min((page + 1) * size, total); return firstJobIndex + " - " + lastJobIndex; }
Source:
<code>public void marshal(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception { int len = JSON.writeJSONString(stream, config.getCharset(), graph, config.getSerializeConfig(), config.getSerializeFilters(), config.getDateFormat(), JSON.DEFAULT_GENERATE_FEATURE, config.getSerializerFeatures()); if (contentTypeHeader) { <START> if (exchange.hasOut()) { <END> exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/json"); exchange.getOut().setHeader(Exchange.CONTENT_LENGTH,len); } else { exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/json"); exchange.getIn().setHeader(Exchange.CONTENT_LENGTH,len); } } }</code><technical_language>More NPE safe i Message message = null; if (exchange.hasOut()) { message = exchange.getOut(); } else { message = exchange.getIn(); } if (message != null) { message.setHeader(Exchange.CONTENT_TYPE, "application/json"); message.setHeader(Exchange.CONTENT_LENGTH,len); }</technical_language>

Target:
public void marshal(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception { int len = JSON.writeJSONString(stream, config.getCharset(), graph, config.getSerializeConfig(), config.getSerializeFilters(), config.getDateFormat(), JSON.DEFAULT_GENERATE_FEATURE, config.getSerializerFeatures()); if (contentTypeHeader) { Message message = exchange.hasOut() ? exchange.getOut() : exchange.getIn(); message.setHeader(Exchange.CONTENT_TYPE, "application/json"); message.setHeader(Exchange.CONTENT_LENGTH, len); } }
Source:
<code>public String toString() { <START> ObjectMapper objectMapper = new ObjectMapper(); <END> objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX")); Map<String, Object> map = new HashMap<>(); map.put("id", id); map.put("ibanCode", ibanCode); map.put("accountId", accountId); map.put("currency", currency); map.put("accountHolderName", accountHolderName); map.put("bankInstitutionName", bankInstitutionName); map.put("bankInstitutionAddress", bankInstitutionAddress); map.put("bankInstitutionCountry", bankInstitutionCountry); map.put("bicSwift", bicSwift); map.put("createdAt", createdAt); map.put("updatedAt", updatedAt); try { return objectMapper.writeValueAsString(map); } catch (JsonProcessingException e) { return String.format("{\"error\": \"%s\"}", e.getMessage()); } }</code><technical_language>objectMapper declared "final", map</technical_language>

Target:
public String toString() { final ObjectMapper objectMapper = new ObjectMapper() .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .setDateFormat(new SimpleDateFormat(Utils.dateFormat)); Map<String, Object> map = new HashMap<>(); map.put("id", id); map.put("ibanCode", ibanCode); map.put("accountId", accountId); map.put("currency", currency); map.put("accountHolderName", accountHolderName); map.put("bankInstitutionName", bankInstitutionName); map.put("bankInstitutionAddress", bankInstitutionAddress); map.put("bankInstitutionCountry", bankInstitutionCountry); map.put("bicSwift", bicSwift); map.put("createdAt", createdAt); map.put("updatedAt", updatedAt); try { return objectMapper.writeValueAsString(map); } catch (JsonProcessingException e) { return String.format("{\"error\": \"%s\"}", e.getMessage()); } }
Source:
<code>public static Schema convertToSchema(LogicalType logicalType) { <START> return convertToSchema(logicalType, "row_0"); <END> }</code><technical_language>I this conflict if a field name is "row_0"</technical_language>

Target:
public static Schema convertToSchema(LogicalType logicalType) { return convertToSchema(logicalType, "record"); }
Source:
<code>private String sockFile(IExtractedFileSet exe) throws IOException { <START> String sysTempDir = System.getProperty("java.io.tmpdir"); <END> String pidFile = String.format("%s.pid", exe.generatedBaseDir().getName()); return new File(sysTempDir, pidFile).getAbsolutePath(); }</code><technical_language>File.createTempFile()</technical_language>

Target:
private String sockFile(IExtractedFileSet exe) throws IOException { String sysTempDir = System.getProperty("java.io.tmpdir"); String pidFile = String.format("%s.sock", exe.generatedBaseDir().getName()); return new File(sysTempDir, pidFile).getAbsolutePath(); }
Source:
<code>public Collection<String> getSpoutNames() { <START> getCachedPhysicalPlan(); <END> return getSpoutNames(cachedPhysicalPlan); }</code><technical_language>here. local variable more readable</technical_language>

Target:
public List<String> getSpoutNames() { PhysicalPlan pp = getPhysicalPlan(); return getSpoutNames(pp); }
Source:
<code>public void run() { if (fBreakpoints != null) { for (BreakpointSetElement <START> fBreakpoint : <END> fBreakpoints) { fBreakpoint.container.getOrganizer().removeBreakpoint(fBreakpoint.breakpoint, fBreakpoint.container.getCategory()); } } }</code><technical_language>rename breakpoint</technical_language>

Target:
public void run() { if (fBreakpoints != null) { for (BreakpointSetElement breakpoint : fBreakpoints) { breakpoint.container.getOrganizer().removeBreakpoint(breakpoint.breakpoint, breakpoint.container.getCategory()); } } }
Source:
<code>public StyleEditPage(PageParameters parameters) { String name = parameters.get(NAME).toString(); String workspace = parameters.get(WORKSPACE).toOptionalString(); StyleInfo si = workspace != null ? getCatalog().getStyleByName(workspace, name) : <START> getCatalog().getStyleByName(name); <END> if(si == null) { getSession().error(new ParamResourceModel("StyleEditPage.notFound", this, name).getString()); doReturn(StylePage.class); return; } initUI(si); if (!isAuthenticatedAsAdmin()) { Form f = (Form)get("form"); if (si.getWorkspace() == null) { styleForm.setEnabled(false); nameTextField.setEnabled(false); uploadForm.setEnabled(false); editor.add(new AttributeAppender("class", new Model("disabled"), " ")); get("validate").add(new AttributeAppender("style", new Model("display:none;"), " ")); add(new Behavior() { @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); response.render(OnLoadHeaderItem.forScript( "document.getElementById('mainFormSubmit').style.display = 'none';")); response.render(OnLoadHeaderItem.forScript( "document.getElementById('uploadFormSubmit').style.display = 'none';")); } }); info(new StringResourceModel("globalStyleReadOnly", this, null).getString()); } f.get("workspace").setEnabled(false); } formatChoice.setEnabled(false); formatReadOnlyMessage.setVisible(true); }</code><technical_language>update header 2016</technical_language>

Target:
public StyleEditPage(PageParameters parameters) { String name = parameters.get(NAME).toString(); String workspace = parameters.get(WORKSPACE).toOptionalString(); StyleInfo si = workspace != null ? getCatalog().getStyleByName(workspace, name) : getCatalog().getStyleByName(name); if(si == null) { error(new ParamResourceModel("StyleEditPage.notFound", this, name).getString()); doReturn(StylePage.class); return; } initUI(si); if (!isAuthenticatedAsAdmin()) { Form f = (Form)get("form"); if (si.getWorkspace() == null) { styleForm.setEnabled(false); nameTextField.setEnabled(false); uploadForm.setEnabled(false); editor.add(new AttributeAppender("class", new Model("disabled"), " ")); get("validate").add(new AttributeAppender("style", new Model("display:none;"), " ")); add(new Behavior() { @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); response.render(OnLoadHeaderItem.forScript( "document.getElementById('mainFormSubmit').style.display = 'none';")); response.render(OnLoadHeaderItem.forScript( "document.getElementById('uploadFormSubmit').style.display = 'none';")); } }); info(new StringResourceModel("globalStyleReadOnly", this, null).getString()); } f.get("workspace").setEnabled(false); } formatChoice.setEnabled(false); formatReadOnlyMessage.setVisible(true); }
Source:
<code>public void testValidAuthMgmtKieServerRouter() throws Exception { <START> router = new KieServerRouter(); <END> Throwable thrown = catchThrowable(() -> { router.start("localhost", 1234); }); assertThat(thrown) .isInstanceOf(RuntimeException.class) .hasMessageMatching("Identity Provider .* not found !"); }</code><technical_language>@elguardian this test is failing this constructor needs updated receive identity provider. suggestion router = new KieServerRouter(true, "fake");</technical_language>

Target:
public void testValidAuthMgmtKieServerRouter() throws Exception { router = new KieServerRouter(true, "fake"); Throwable thrown = catchThrowable(() -> { router.start("localhost", 1234); }); assertThat(thrown) .isInstanceOf(RuntimeException.class) .hasMessageMatching("Identity Provider .* not found !"); }
Source:
<code>public String partialUpdate(Request request, Response response) { JsonReader jsonReader = GsonTransformer.getInstance().jsonReaderFrom(request.body()); PatchEnvironmentRequest req = PatchEnvironmentRequestRepresenter.fromJSON(jsonReader); HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); String environmentName = request.params("name"); EnvironmentConfig environmentConfig = fetchEntityFromConfig(environmentName); Optional<EnvironmentVariableConfig> parsingErrors = req.getEnvironmentVariablesToAdd().stream() .filter(envVar -> !envVar.errors().isEmpty()) .findFirst(); if (parsingErrors.isPresent()) { EnvironmentVariablesConfig configs = new EnvironmentVariablesConfig(req.getEnvironmentVariablesToAdd()); String errorMessage = MessageJson.create("Error parsing patch request", writer -> toJSONArray(writer, "environment_variables", configs)); response.status(422); return errorMessage; <START> } <END> List<String> dummyAgentList = new ArrayList<>(); environmentConfigService.patchEnvironment(environmentConfig, req.getPipelineToAdd(), req.getPipelineToRemove(), dummyAgentList, dummyAgentList, req.getEnvironmentVariablesToAdd(), req.getEnvironmentVariablesToRemove(), currentUsername(), result); EnvironmentConfig updateConfigElement = fetchEntityFromConfig(environmentName); setEtagHeader(updateConfigElement, response); return handleCreateOrUpdateResponse(request, response, updateConfigElement, result); }</code><technical_language>this send a string response? MessageJson.create</technical_language>

Target:
public String partialUpdate(Request request, Response response) { JsonReader jsonReader = GsonTransformer.getInstance().jsonReaderFrom(request.body()); PatchEnvironmentRequest req = PatchEnvironmentRequestRepresenter.fromJSON(jsonReader); HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); String environmentName = request.params("name"); EnvironmentConfig environmentConfig = fetchEntityFromConfig(environmentName); Optional<EnvironmentVariableConfig> parsingErrors = req.getEnvironmentVariablesToAdd().stream() .filter(envVar -> !envVar.errors().isEmpty()) .findFirst(); if (parsingErrors.isPresent()) { EnvironmentVariablesConfig configs = new EnvironmentVariablesConfig(req.getEnvironmentVariablesToAdd()); response.status(422); return MessageJson.create("Error parsing patch request", writer -> toJSONArray(writer, "environment_variables", configs)); } environmentConfigService.patchEnvironment(environmentConfig, req.getPipelineToAdd(), req.getPipelineToRemove(), req.getEnvironmentVariablesToAdd(), req.getEnvironmentVariablesToRemove(), currentUsername(), result); EnvironmentConfig updateConfigElement = fetchEntityFromConfig(environmentName); setEtagHeader(updateConfigElement, response); return handleCreateOrUpdateResponse(request, response, updateConfigElement, result); }
Source:
<code>public TemplateModel get(String key) throws TemplateModelException { Object result; try { result = Entities.submit(entity, DependentConfiguration.attributeWhenReady(entity, Sensors.builder(Object.class, key).persistence(AttributeSensor.SensorPersistenceMode.NONE).build())).get(); } catch (Exception e) { <START> throw Exceptions.propagate(e); <END> } if (result == null) { return null; } else { return wrapAsTemplateModel(result); } }</code><technical_language>Do throw new TemplateModelException("Error obtaining sensor data for " + key, e) instead</technical_language>

Target:
public TemplateModel get(String key) throws TemplateModelException { Object result; try { result = Entities.submit(entity, DependentConfiguration.attributeWhenReady(entity, Sensors.builder(Object.class, key).persistence(AttributeSensor.SensorPersistenceMode.NONE).build())).get(); } catch (Exception e) { throw new TemplateModelException("Error obtaining sensor data for " + key, e); } if (result == null) { return null; } else { return wrapAsTemplateModel(result); } }
Source:
<code>private static StudyEmailType parseEmailType(String typeStr) { if (StringUtils.isBlank(typeStr)) { throw new BadRequestException("Email type must be specified"); } try { <START> return StudyEmailType.valueOf(typeStr); <END> } catch (IllegalArgumentException ex) { throw new BadRequestException("Unrecognized type \"" + typeStr + "\""); } }</code><technical_language>enums exposed in API lowercase, I typeStr.toUpperCase()</technical_language>

Target:
private static StudyEmailType parseEmailType(String typeStr) { if (StringUtils.isBlank(typeStr)) { throw new BadRequestException("Email type must be specified"); } try { return StudyEmailType.valueOf(typeStr.toUpperCase()); } catch (IllegalArgumentException ex) { throw new BadRequestException("Unrecognized type \"" + typeStr + "\""); } }
Source:
<code>public String readString() throws IOException { int len = readLength(); if (len == 0) { <START> log.debug("flush-pkt"); <END> return END; } len -= 4; if (len == 0) { log.debug(""); return ""; } byte[] raw; if (len <= lineBuffer.length) raw = lineBuffer; else raw = new byte[len]; IO.readFully(in, raw, 0, len); if (raw[len - 1] == '\n') len--; String decodedBuffer = RawParseUtils.decode(Constants.CHARSET, raw, 0, len); log.debug(decodedBuffer); return decodedBuffer; }</code><technical_language>"0000" consistent git core. (i.e. try close additional output of "GIT_TRACE_PACKET=1 git ls-remote")</technical_language>

Target:
public String readString() throws IOException { int len = readLength(); if (len == 0) { log.debug("git< flush-pkt"); return END; } len -= 4; if (len == 0) { log.debug("git< "); return ""; } byte[] raw; if (len <= lineBuffer.length) raw = lineBuffer; else raw = new byte[len]; IO.readFully(in, raw, 0, len); if (raw[len - 1] == '\n') len--; String ret = RawParseUtils.decode(Constants.CHARSET, raw, 0, len); log.debug("git< " + ret); return ret; }
Source:
<code>static TextAnalyticsException toTextAnalyticsException(com.azure.ai.textanalytics.models.TextAnalyticsError error) { String baseMessage = String.format(Locale.US, "%s: {%s}, %s", <START> "Status Code", HttpURLConnection.HTTP_OK, error.getMessage()); <END> return new TextAnalyticsException(baseMessage, error.getCode().toString(), error.getTarget()); }</code><technical_language>this exception for 200 only? A exception is thrown for 4xx/5xx codes? TA service add another top-level error. this exception type leave room grow if do? Right top-level errors: "enum": [ "invalidRequest", // 400 "invalidArgument", // 200 "internalServerError", // 500 "serviceUnavailable" // 500 ], exception type throw if added another for 200? inherit TextAnalyticsException differentiate another way</technical_language>

Target:
private static TextAnalyticsException toTextAnalyticsException( com.azure.ai.textanalytics.models.TextAnalyticsError error) { return new TextAnalyticsException(error.getMessage(), error.getCode().toString(), error.getTarget()); }
Source:
<code>public void init() { if (env.supports("feature.auth.ldap")) { host = assertValuePresent(LDAP_HOST); port = Integer.parseInt(assertValuePresent(LDAP_PORT)); user = assertValuePresent(LDAP_USER); pass = assertValuePresent(LDAP_PASS); userDn = assertValuePresent(LDAP_USER_DN); emailAttr = assertValuePresent(LDAP_EMAIL); nameAttr = assertValuePresent(LDAP_NAME); surnameAttr = env.get(LDAP_SURNAME, ""); groupAttr = env.get(LDAP_GROUP, ""); moderatorGroup = env.get(LDAP_MODERATOR_GROUP, ""); lookupAttrs = env.get(LDAP_LOOKUP, "").split(","); <START> useSsl = Boolean.parseBoolean(env.get(LDAP_USE_SSL, "false")); <END> } }</code><technical_language>env.supports(LDAP_USE_SSL)</technical_language>

Target:
public void init() { if (env.supports("feature.auth.ldap")) { host = assertValuePresent(LDAP_HOST); port = Integer.parseInt(assertValuePresent(LDAP_PORT)); user = assertValuePresent(LDAP_USER); pass = assertValuePresent(LDAP_PASS); userDn = assertValuePresent(LDAP_USER_DN); emailAttr = assertValuePresent(LDAP_EMAIL); nameAttr = assertValuePresent(LDAP_NAME); surnameAttr = env.get(LDAP_SURNAME, ""); groupAttr = env.get(LDAP_GROUP, ""); moderatorGroup = env.get(LDAP_MODERATOR_GROUP, ""); lookupAttrs = env.get(LDAP_LOOKUP, "").split(","); useSsl = env.supports(LDAP_USE_SSL); } }
Source:
<code>public <T> void initializeEntity(T entity) { if (entity != null) { @SuppressWarnings("unchecked") Initializer<T> initializer = getEntityBinding(entity.getClass()).getInitializer(); if (initializer != null) { initializer.initialize(entity); <START> } else if (injector != null) { <END> injector.initialize(entity); } } }</code><technical_language>@aklish do expect if initializer injector defined</technical_language>

Target:
public <T> void initializeEntity(T entity) { if (entity != null) { @SuppressWarnings("unchecked") Initializer<T> initializer = getEntityBinding(entity.getClass()).getInitializer(); if (initializer != null) { initializer.initialize(entity); } else if (injector != null) { injector.inject(entity); } } }
Source:
<code>public static ToolingApiOperation concat(final ToolingApiOperation op1, final ToolingApiOperation op2) { return new ToolingApiOperation() { @Override public String getName() { return op1.getName() + ", " + op2.getName(); } @Override public void runInToolingApi(CancellationTokenSource tokenSource, IProgressMonitor monitor) throws Exception { SubMonitor progress = SubMonitor.convert(monitor); progress.setWorkRemaining(2); CancellationToken token = tokenSource.token(); op1.runInToolingApi(tokenSource, progress.newChild(1)); if (monitor.isCanceled() && token.isCancellationRequested()) { throw new OperationCanceledException(); } op2.runInToolingApi(tokenSource, progress.newChild(1)); } @Override public ISchedulingRule getRule() { <START> return ResourcesPlugin.getWorkspace().getRoot(); <END> } }; }</code><technical_language>MultiRule returned</technical_language>

Target:
public static ToolingApiOperation concat(final ToolingApiOperation op1, final ToolingApiOperation op2) { return new ToolingApiOperation() { @Override public String getName() { return op1.getName() + ", " + op2.getName(); } @Override public void runInToolingApi(CancellationTokenSource tokenSource, IProgressMonitor monitor) throws Exception { SubMonitor progress = SubMonitor.convert(monitor); progress.setWorkRemaining(2); CancellationToken token = tokenSource.token(); op1.runInToolingApi(tokenSource, progress.newChild(1)); if (monitor.isCanceled() && token.isCancellationRequested()) { throw new OperationCanceledException(); } op2.runInToolingApi(tokenSource, progress.newChild(1)); } @Override public ISchedulingRule getRule() { return new MultiRule(new ISchedulingRule[]{op1.getRule(),op2.getRule()}); } }; }
Source:
<code>public void getPrograms_shouldTestGetProgramsIfCohortIsNotEmpty() { int i = 0; Cohort cohort = new Cohort(); Collection<Program> programs = pws.getAllPrograms(); <START> List<PatientProgram> patientPrograms; <END> cohort.addMember(1); cohort.addMember(2); patientPrograms = dao.getPatientPrograms(cohort, programs); assertEquals(patientPrograms.size(), 2); }</code><technical_language>Is a need for this variable</technical_language>

Target:
public void getPrograms_shouldTestGetProgramsIfCohortIsNotEmpty() { Cohort cohort = new Cohort(); Collection<Program> programs = pws.getAllPrograms(); List<PatientProgram> patientPrograms; cohort.addMember(1); cohort.addMember(2); patientPrograms = dao.getPatientPrograms(cohort, programs); assertEquals(patientPrograms.size(), 2); }
Source:
<code>public EcoreMetaExplorerComposite(final Composite parent, final MenuManager menuManager) { super(parent, SWT.NONE); setLayout(new GridLayout(1, true)); final Label label = new Label(this, SWT.NONE); label.setText(Messages.EcoreMetaExplorerComposite_Metas); this.tree = new TreeViewer(this); this.tree.getControl().setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true)); this.facetManager = IFacetManagerFactory.DEFAULT .getOrCreateDefaultFacetManager(new ResourceSetImpl()); this.customizationMgr = ICustomizationManagerFactory.DEFAULT .createICustomizationManager(this.facetManager); final ILabelProvider labelProvider = IResolvingCustomizedLabelProviderFactory.DEFAULT .createCustomizedLabelProvider(this.customizationMgr); final IContentProvider contentProvider = ICustomizedContentProviderFactory.DEFAULT .createCustomizedTreeContentProvider(this.customizationMgr); this.tree.setContentProvider(contentProvider); this.tree.setLabelProvider(labelProvider); this.tree.setInput(Collections.EMPTY_LIST); final Menu createContextMenu = menuManager.createContextMenu(this.tree .getControl()); this.tree.getControl().setMenu(createContextMenu); <START> this.facetManager.addListener(new IFacetManagerListener() { public void facetManagerChanged() { EcoreMetaExplorerComposite.this.facetManagerChanged(); } }); <END> }</code><technical_language>This listener removed widget is disposed</technical_language>

Target:
public EcoreMetaExplorerComposite(final Composite parent, final MenuManager menuManager) { super(parent, SWT.NONE); setLayout(new GridLayout(1, true)); final Label label = new Label(this, SWT.NONE); label.setText(Messages.EcoreMetaExplorerComposite_Metas); this.tree = new TreeViewer(this); this.tree.getControl().setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true)); this.facetManager = IFacetManagerFactory.DEFAULT .getOrCreateDefaultFacetManager(new ResourceSetImpl()); this.customizationMgr = ICustomizationManagerFactory.DEFAULT .createICustomizationManager(this.facetManager); final ILabelProvider labelProvider = IResolvingCustomizedLabelProviderFactory.DEFAULT .createCustomizedLabelProvider(this.customizationMgr); final IContentProvider contentProvider = ICustomizedContentProviderFactory.DEFAULT .createCustomizedTreeContentProvider(this.customizationMgr); this.tree.setContentProvider(contentProvider); this.tree.setLabelProvider(labelProvider); this.tree.setInput(Collections.EMPTY_LIST); final Menu createContextMenu = menuManager.createContextMenu(this.tree .getControl()); this.tree.getControl().setMenu(createContextMenu); this.facetManager.addListener(this.facetMgrListener); }
Source:
<code>public static String[] getVcsUrls(BuildContext buildContext) { int repoSize = buildContext.getRelevantRepositoryIds().size(); <START> ArrayList<String> urls = new ArrayList<>(); <END> for (int i = 1; i <= repoSize; i++) { String vcsUrl = buildContext.getCurrentResult().getCustomBuildData().get("planRepository." + i + ".repositoryUrl"); if (StringUtils.isBlank(vcsUrl) && StringUtils.isNotBlank( buildContext.getCurrentResult().getCustomBuildData().get("planRepository." + i + ".depot"))) { vcsUrl = "depot:" + buildContext.getCurrentResult().getCustomBuildData().get("planRepository." + i + ".depot") + ",client:" + buildContext.getCurrentResult().getCustomBuildData().get("planRepository." + i + ".client") + ",port:" + buildContext.getCurrentResult().getCustomBuildData().get("planRepository." + i + ".port"); } if (StringUtils.isNotBlank(vcsUrl)) { urls.add(vcsUrl); } } return urls.toArray(new String[0]); }</code><technical_language>I practice declare List<String></technical_language>

Target:
public static String[] getVcsUrls(BuildContext buildContext) { int repoSize = buildContext.getRelevantRepositoryIds().size(); List<String> urls = new ArrayList<>(); for (int i = 1; i <= repoSize; i++) { String vcsUrl = buildContext.getCurrentResult().getCustomBuildData().get("planRepository." + i + ".repositoryUrl"); if (StringUtils.isBlank(vcsUrl) && StringUtils.isNotBlank( buildContext.getCurrentResult().getCustomBuildData().get("planRepository." + i + ".depot"))) { vcsUrl = "depot:" + buildContext.getCurrentResult().getCustomBuildData().get("planRepository." + i + ".depot") + ",client:" + buildContext.getCurrentResult().getCustomBuildData().get("planRepository." + i + ".client") + ",port:" + buildContext.getCurrentResult().getCustomBuildData().get("planRepository." + i + ".port"); } if (StringUtils.isNotBlank(vcsUrl)) { urls.add(vcsUrl); } } return urls.toArray(new String[0]); }
Source:
<code>} catch (ClassNotFoundException e) { <START> e.printStackTrace(); <END> }</code><technical_language>This is printed out class loading? prettify later</technical_language>

Target:
} catch (ClassNotFoundException e) { LOG.debug("Did not find relocated ByteString class from hadoop-thirdparty." + " Assuming this is below Hadoop 3.3.0", e); }
Source:
<code>private static String cleanup(String literalValue) { String result = literalValue; if(result.startsWith("0b") || result.startsWith("0x")) { result = result.substring(2); } <START> if(result.endsWith("L")) { <END> result = result.substring(0, result.length() - 1); } return result; }</code><technical_language>I lowercase l considered</technical_language>

Target:
private static String cleanup(String literalValue) { String result = literalValue.toLowerCase(); if(result.startsWith("0b") || result.startsWith("0x")) { result = result.substring(2); } if(result.endsWith("l")) { result = result.substring(0, result.length() - 1); } return result; }
Source:
<code>public MamFinIQ parse(XmlPullParser parser, int initialDepth) throws Exception { String queryId = parser.getAttributeValue("", "queryid"); boolean complete = Boolean.parseBoolean(parser.getAttributeValue("", "complete")); boolean stable = Boolean.parseBoolean(parser.getAttributeValue("", "stable")); boolean done = false; RSMSet rsmSet = null; <START> while (!done) { <END> int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { if (parser.getName().equals(RSMSet.ELEMENT)) { rsmSet = new RSMSetProvider().parse(parser); } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getName().equals("fin")) { done = true; } } } return new MamFinIQ(queryId, rsmSet, complete, stable); }</code><technical_language>a boolean abort condition for parsers main while loop is a deprecated pattern. Instead replace this line outerloop: while(true) {</technical_language>

Target:
public MamFinIQ parse(XmlPullParser parser, int initialDepth) throws Exception { String queryId = parser.getAttributeValue("", "queryid"); boolean complete = Boolean.parseBoolean(parser.getAttributeValue("", "complete")); boolean stable = Boolean.parseBoolean(parser.getAttributeValue("", "stable")); RSMSet rsmSet = null; outerloop: while (true) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { if (parser.getName().equals(RSMSet.ELEMENT)) { rsmSet = new RSMSetProvider().parse(parser); } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getDepth() == initialDepth) { break outerloop; } } } return new MamFinIQ(queryId, rsmSet, complete, stable); }
Source:
<code>protected void updateResolvedContainers(Account account, Collection<Container> resolvedContainers) throws AccountServiceException { infoMapLock.readLock().lock(); try { if (accountInfoMapRef.get() .hasConflictingContainer(resolvedContainers, account.getId(), config.ignoreVersionMismatch)) { logger.error( "Containers={} under Account={} conflict with the containers in local cache. Cancel the update operation.", <START> account.getAllContainers(), account.getId()); <END> accountServiceMetrics.updateAccountErrorCount.inc(); throw new AccountServiceException("Containers in account " + account.getId() + " conflict with local cache", AccountServiceErrorCode.ResourceConflict); } } finally { infoMapLock.readLock().unlock(); } try { updateContainersWithMySqlStore(account.getId(), resolvedContainers); } catch (SQLException e) { logger.error("Failed updating containers in MySql DB", resolvedContainers, e); handleSQLException(e); } infoMapLock.writeLock().lock(); try { accountInfoMapRef.get().addOrUpdateContainers(resolvedContainers); } finally { infoMapLock.writeLock().unlock(); } }</code><technical_language>minor: print out account name instead of account id? account.getAllContainers() replaced resolvedContainers</technical_language>

Target:
protected void updateResolvedContainers(Account account, Collection<Container> resolvedContainers) throws AccountServiceException { try { updateContainersWithMySqlStore(account.getId(), resolvedContainers); } catch (SQLException e) { logger.error("Failed updating containers in MySql DB", resolvedContainers, e); handleSQLException(e); } infoMapLock.writeLock().lock(); try { accountInfoMapRef.get().addOrUpdateContainers(resolvedContainers); } finally { infoMapLock.writeLock().unlock(); } }
Source:
<code>private Object doGet(final Message<?> requestMessage) { final String remoteFilePath = this.fileNameProcessor.processMessage(requestMessage); final String remoteFilename = getRemoteFilename(remoteFilePath); final String remoteDir = getRemoteDirectory(remoteFilePath, remoteFilename); Session<F> session = null; Object payload; if (this.options.contains(Option.STREAM)) { session = this.remoteFileTemplate.getSessionFactory().getSession(); try { payload = session.readRaw(remoteFilePath); } catch (IOException e) { throw new MessageHandlingException(requestMessage, "Failed to get the remote file [" + remoteFilePath + "] as a stream", e); } } else { payload = this.remoteFileTemplate.execute(new SessionCallback<F, File>() { @Override public File doInSession(Session<F> session) throws IOException { return AbstractRemoteFileOutboundGateway.this.get(requestMessage, session, remoteDir, remoteFilePath, remoteFilename, true); <START> <END> } }); } return getMessageBuilderFactory().withPayload(payload) .setHeader(FileHeaders.REMOTE_DIRECTORY, remoteDir) .setHeader(FileHeaders.REMOTE_FILE, remoteFilename) .setHeader(FileHeaders.REMOTE_SESSION, session) .build(); }</code><technical_language>s/AbstractRemoteFileOutboundGateway.this.//</technical_language>

Target:
private Object doGet(final Message<?> requestMessage) { final String remoteFilePath = this.fileNameProcessor.processMessage(requestMessage); final String remoteFilename = getRemoteFilename(remoteFilePath); final String remoteDir = getRemoteDirectory(remoteFilePath, remoteFilename); Session<F> session = null; Object payload; if (this.options.contains(Option.STREAM)) { session = this.remoteFileTemplate.getSessionFactory().getSession(); try { payload = session.readRaw(remoteFilePath); } catch (IOException e) { throw new MessageHandlingException(requestMessage, "Failed to get the remote file [" + remoteFilePath + "] as a stream", e); } } else { payload = this.remoteFileTemplate.execute(new SessionCallback<F, File>() { @Override public File doInSession(Session<F> session) throws IOException { return get(requestMessage, session, remoteDir, remoteFilePath, remoteFilename, true); } }); } return getMessageBuilderFactory().withPayload(payload) .setHeader(FileHeaders.REMOTE_DIRECTORY, remoteDir) .setHeader(FileHeaders.REMOTE_FILE, remoteFilename) .setHeader(FileHeaders.REMOTE_SESSION, session) .build(); }
Source:
<code>@Override public Map<UUID, Integer> serviceTopology(String name, long timeout) throws IgniteCheckedException { assert timeout >= 0; long startTime = U.currentTimeMillis(); ServiceInfo desc; while (true) { desc = lookupInRegisteredServices(name); if (timeout == 0 && desc == null) return null; synchronized (servicesTopsUpdateMux) { <START> if (desc != null && desc.topologyInitialized()) <END> return desc.topologySnapshot(); long wait = 0; if (timeout != 0) { wait = timeout - (U.currentTimeMillis() - startTime); if (wait <= 0) return desc == null ? null : desc.topologySnapshot(); } try { servicesTopsUpdateMux.wait(wait); } catch (InterruptedException e) { throw new IgniteInterruptedCheckedException(e); } } } }</code><technical_language>This condition moved synchronized block</technical_language>

Target:
@Override public Map<UUID, Integer> serviceTopology(String name, long timeout) throws IgniteCheckedException { assert timeout >= 0; long startTime = U.currentTimeMillis(); ServiceInfo desc; while (true) { synchronized (servicesTopsUpdateMux) { desc = lookupInRegisteredServices(name); if (timeout == 0 && desc == null) return null; if (desc != null && desc.topologyInitialized()) return desc.topologySnapshot(); long wait = 0; if (timeout != 0) { wait = timeout - (U.currentTimeMillis() - startTime); if (wait <= 0) return desc == null ? null : desc.topologySnapshot(); } try { servicesTopsUpdateMux.wait(wait); } catch (InterruptedException e) { throw new IgniteInterruptedCheckedException(e); } } } }
Source:
<code>private StreamTask createStreamsTask(final StreamsConfig streamsConfig, final MockClientSupplier clientSupplier, final ProcessorTopology topology, final TaskId taskId) { final Metrics metrics = new Metrics(); final LogContext logContext = new LogContext("test-stream-task "); final Set<TopicPartition> partitions = Collections.singleton(new TopicPartition(topicName, taskId.partition)); final ProcessorStateManager stateManager = new ProcessorStateManager( taskId, partitions, Task.TaskType.ACTIVE, stateDirectory, topology.storeToChangelogTopic(), new StoreChangelogReader( new MockTime(), streamsConfig, logContext, clientSupplier.restoreConsumer, new MockStateRestoreListener()), logContext); <START> final boolean eosAlphaEnabled = StreamsConfig.EXACTLY_ONCE.equals(streamsConfig.getString(StreamsConfig.PROCESSING_GUARANTEE_CONFIG)); <END> final RecordCollector recordCollector = new RecordCollectorImpl( logContext, taskId, clientSupplier.consumer, eosAlphaEnabled ? new TransactionManager( logContext, clientSupplier.getProducer(new HashMap<>()), streamsConfig.getString(StreamsConfig.APPLICATION_ID_CONFIG), taskId) : new TransactionManager(logContext, clientSupplier.getProducer(new HashMap<>())), streamsConfig.defaultProductionExceptionHandler(), eosAlphaEnabled, new MockStreamsMetrics(metrics)); return new StreamTask( taskId, partitions, topology, clientSupplier.consumer, streamsConfig, new MockStreamsMetrics(metrics), stateDirectory, null, new MockTime(), stateManager, recordCollector); }</code><technical_language>nit: eosEnabled</technical_language>

Target:
private StreamTask createStreamsTask(final StreamsConfig streamsConfig, final MockClientSupplier clientSupplier, final ProcessorTopology topology, final TaskId taskId) { final Metrics metrics = new Metrics(); final LogContext logContext = new LogContext("test-stream-task "); final Set<TopicPartition> partitions = Collections.singleton(new TopicPartition(topicName, taskId.partition)); final ProcessorStateManager stateManager = new ProcessorStateManager( taskId, partitions, Task.TaskType.ACTIVE, stateDirectory, topology.storeToChangelogTopic(), new StoreChangelogReader( new MockTime(), streamsConfig, logContext, clientSupplier.restoreConsumer, new MockStateRestoreListener()), logContext); final boolean eosEnabled = StreamsConfig.EXACTLY_ONCE.equals(streamsConfig.getString(StreamsConfig.PROCESSING_GUARANTEE_CONFIG)); final RecordCollector recordCollector = new RecordCollectorImpl( logContext, taskId, clientSupplier.consumer, eosEnabled ? new StreamsProducer( logContext, clientSupplier.getProducer(new HashMap<>()), streamsConfig.getString(StreamsConfig.APPLICATION_ID_CONFIG), taskId) : new StreamsProducer(logContext, clientSupplier.getProducer(new HashMap<>())), streamsConfig.defaultProductionExceptionHandler(), eosEnabled, new MockStreamsMetrics(metrics)); return new StreamTask( taskId, partitions, topology, clientSupplier.consumer, streamsConfig, new MockStreamsMetrics(metrics), stateDirectory, null, new MockTime(), stateManager, recordCollector); }