auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private AsyncJobStatus processJobFailure(AsyncJobStatus status, EventSink eventSink, Throwable throwable, boolean retry) throws JobStateManagementException, JobMessageDispatchException { status.setEndTime(new Date()); eventSink.rollback(); Object result = null; if (throwable != null) { if (throwable.getCause() instanceof CandlepinException) { <START> result = ((CandlepinException) throwable.getCause()).message(); <END> } else { result = throwable.toString(); } } if (retry) { status = this.updateJobStatus(status, JobState.FAILED_WITH_RETRY, result); log.warn("Job \"{}\" failed in {}ms; retrying...", status.getName(), this.getJobRuntime(status), throwable); this.postJobStatusMessage(status); } else { status = this.updateJobStatus(status, JobState.FAILED, result); log.error("Job \"{}\" failed in {}ms", status.getName(), this.getJobRuntime(status), throwable); } return status; }</code><technical_language>Maybe. For some context, CandlepinExceptions generally for exceptions passed out of resources end-user RESTeasy. a this a bit closer review</technical_language>

Target:
private AsyncJobStatus processJobFailure(AsyncJobStatus status, EventSink eventSink, Throwable throwable, boolean retry) throws JobStateManagementException, JobMessageDispatchException { status.setEndTime(new Date()); eventSink.rollback(); String result = throwable != null ? throwable.toString() : null; if (retry) { status = this.updateJobStatus(status, JobState.FAILED_WITH_RETRY, result); log.warn("Job \"{}\" failed in {}ms; retrying...", status.getName(), this.getJobRuntime(status), throwable); this.postJobStatusMessage(status); } else { status = this.updateJobStatus(status, JobState.FAILED, result); log.error("Job \"{}\" failed in {}ms", status.getName(), this.getJobRuntime(status), throwable); } return status; }
Source:
<code>public void testSupplierIsPolled() throws Exception { entity = app.addChild(EntitySpec.create(DataEntity.class) .configure(DataEntity.POLL_PERIOD, 100l) .configure(DataEntity.SENSOR_SUPPLIER_MAP, MutableMap.<AttributeSensor<?>, Supplier<?>>of(longSensor, currentTimeMillis))); Entities.startManagement(entity); app.start(ImmutableList.of(loc)); Thread.sleep(200l); Long first = entity.getAttribute(longSensor); Thread.sleep(200l); Long second = entity.getAttribute(longSensor); assertNotNull(first); assertNotNull(second); <START> assertTrue(second.longValue() > first.longValue()); <END> }</code><technical_language>do Asserts.succeedsEventually(...) is greater (so time-sensitive for GC pause times low-spec cloudbees machines</technical_language>

Target:
public void testSupplierIsPolled() throws Exception { entity = app.createAndManageChild(EntitySpec.create(DataEntity.class) .configure(DataEntity.POLL_PERIOD, 50L) .configure(DataEntity.SENSOR_SUPPLIER_MAP, MutableMap.<AttributeSensor<?>, Supplier<?>>of(longSensor, currentTimeMillis))); app.start(ImmutableList.of(loc)); Asserts.eventually(Entities.attributeSupplier(entity, longSensor), Predicates.notNull()); final Long first = entity.getAttribute(longSensor); assertNotNull(first); Asserts.succeedsEventually(new Runnable() { @Override public void run() { Long second = entity.getAttribute(longSensor); assertNotNull(second); assertTrue(second.longValue() > first.longValue()); } }); }
Source:
<code>public void lockDelegatesToLockService() throws InterruptedException { LockRequest legacyRequest = LockRequest.builder(buildLockMap(LockMode.WRITE)).build(); when(lockService.lock(LockClient.ANONYMOUS.getClientId(), legacyRequest)).thenReturn(LOCK_REFRESH_TOKEN); <START> assertEquals(LOCK_REFRESH_TOKEN, timelock.lock(LockRequestV2.of(ImmutableSet.of(LOCK_A, LOCK_B)))); <END> verify(lockService).lock(LockClient.ANONYMOUS.getClientId(), legacyRequest); }</code><technical_language>assertEquals(LOCK_TOKEN_V2, timelock.lock(LockRequestV2.of(ImmutableSet.of(LOCK_A, LOCK_B))));</technical_language>

Target:
public void lockDelegatesToLockService() throws InterruptedException { LockRequest legacyRequest = LockRequest.builder(buildLockMap(LockMode.WRITE)).build(); when(lockService.lock(LockClient.ANONYMOUS.getClientId(), legacyRequest)).thenReturn(LOCK_REFRESH_TOKEN); assertEquals(LOCK_TOKEN_V2, timelock.lock(LockRequestV2.of(ImmutableSet.of(LOCK_A, LOCK_B)))); verify(lockService).lock(LockClient.ANONYMOUS.getClientId(), legacyRequest); }
Source:
<code>public static void tearDown() throws InterruptedException, IOException, TimeoutException { operations.remove(SERVLET_SESSIONS_ADDRESS); administration.reloadIfRequired(); <START> administration.restartIfRequired(); <END> }</code><technical_language>Switch order in other similar cases</technical_language>

Target:
public static void tearDown() throws InterruptedException, IOException, TimeoutException { operations.remove(SERVLET_SESSIONS_ADDRESS); }
Source:
<code>public void testNull() { final AdministrativeStatusType administrativeStatusType = null; final AdministrativeStatusTypeDto administrativeStatusTypeDto = this.configurationMapper.map( administrativeStatusType, AdministrativeStatusTypeDto.class); <START> assertNull(administrativeStatusType); <END> assertNull(administrativeStatusTypeDto); }</code><technical_language>useless check for administrativeStatusType null, assigned line 81</technical_language>

Target:
public void testNull() { final AdministrativeStatusType administrativeStatusType = null; final AdministrativeStatusTypeDto administrativeStatusTypeDto = this.configurationMapper.map( administrativeStatusType, AdministrativeStatusTypeDto.class); assertNull(administrativeStatusTypeDto); }
Source:
<code>public void beginSpan(SpanType type, Attributes attributes) { String elementName = getElementName(type); if (elementName == null) { throw new IllegalStateException(type.name()); } writer.writeStartElement(htmlNsUri, elementName); if (type == SpanType.LINK && attributes instanceof LinkAttributes) { String href = ((LinkAttributes) attributes).getHref(); emitAnchorHref(href); applyLinkAttributes(attributes, href); } else if <START> (!isSubstitutedSpan(type)) { <END> applyAttributes(attributes); } }</code><technical_language>apply attributes in cases</technical_language>

Target:
public void beginSpan(SpanType type, Attributes attributes) { String elementName = spanTypeToElementNameSubstitutions.get(type); if (elementName == null) { throw new IllegalStateException(type.name()); } writer.writeStartElement(htmlNsUri, elementName); if (type == SpanType.LINK && attributes instanceof LinkAttributes) { String href = ((LinkAttributes) attributes).getHref(); emitAnchorHref(href); applyLinkAttributes(attributes, href); } else { applyAttributes(attributes); } }
Source:
<code>public void getMavenLocalRepoDirTest() { String testRepo = MavenUtils.getMavenRepoDir(MavenRepos.LOCAL); File mavenRepository = FileUtils.getFile(testRepo); <START> <END> SoftAssertions.assertSoftly(softly -> { softly.assertThat(mavenRepository).isNotNull(); softly.assertThat(mavenRepository).isDirectory(); softly.assertAll(); }); }</code><technical_language>@domhanak TL;DR: simplify assertThat(mavenRepository).isDirectory(); 3 nitpicks assertj usage: 1. point of SoftAssertions.assertSoftly is calling assertAll end (it [internally for you](<LINK_1> 2. event need soft assertions for multiple asserts object, do java assertThat(x).assertionMethod1() .assertionMethod2()...; 3. assertion isNotNull() is redundant, assertj methods rely object non-null [call automatically](<LINK_0></technical_language>

Target:
public void getMavenLocalRepoDirTest() { String testRepo = MavenUtils.getMavenRepoDir(MavenRepos.LOCAL); assertThat(Files.isDirectory(Paths.get(testRepo))).isTrue(); }
Source:
<code>protected ThingHandler createHandler(Thing thing) { <START> <END> ThingTypeUID thingTypeUID = thing.getThingTypeUID(); if (thingTypeUID.equals(THING_TYPE_SAMPLE)) { return new CoAPConnectedLightingHandler(thing); } return null; }</code><technical_language>empty line</technical_language>

Target:
protected ThingHandler createHandler(Thing thing) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); if (thingTypeUID.equals(THING_TYPE)) { return new CoAPConnectedLightingHandler(thing); } return null; }
Source:
<code>public void buildObject() throws Exception { ProjectToOrganizationConverter converter = new ProjectToOrganizationConverter( defaultApprover, relationColumnFamilyBytes); String projectId = "someProjectId"; String organization1Id = "someOrg1Id"; String organization2Id = "someOrg2Id"; NavigableMap<byte[],byte[]> navigableMap = new TreeMap<byte[],byte[]>( UnsignedBytes.lexicographicalComparator()); navigableMap.put(organization1Id.getBytes(), createOafObject(projectId, organization1Id).toByteArray()); navigableMap.put(organization2Id.getBytes(), createOafObject(projectId, organization2Id).toByteArray()); when(result.getFamilyMap(relationColumnFamilyBytes)).thenReturn(navigableMap); Collection<ProjectToOrganization> projOrgs = converter.buildObject(result, oaf); assertNotNull(projOrgs); assertEquals(2, projOrgs.size()); <START> Iterator<ProjectToOrganization> projOrgIt = projOrgs.iterator(); <END> ProjectToOrganization projOrg = projOrgIt.next(); assertNotNull(projOrg); assertEquals(projectId, projOrg.getProjectId()); assertEquals(organization1Id, projOrg.getOrganizationId()); projOrg = projOrgIt.next(); assertNotNull(projOrg); assertEquals(projectId, projOrg.getProjectId()); assertEquals(organization2Id, projOrg.getOrganizationId()); assertFalse(projOrgIt.hasNext()); }</code><technical_language>If returned list get elements index iterator. a big problem do if necessary</technical_language>

Target:
public void buildObject() throws Exception { ProjectToOrganizationConverter converter = new ProjectToOrganizationConverter(defaultApprover, relationColumnFamilyBytes); String projectId = "someProjectId"; String organization1Id = "someOrg1Id"; String organization2Id = "someOrg2Id"; NavigableMap<byte[], byte[]> navigableMap = new TreeMap<byte[], byte[]>( UnsignedBytes.lexicographicalComparator()); navigableMap.put(organization1Id.getBytes(), createOafObject(projectId, organization1Id).toByteArray()); navigableMap.put(organization2Id.getBytes(), createOafObject(projectId, organization2Id).toByteArray()); when(result.getFamilyMap(relationColumnFamilyBytes)).thenReturn(navigableMap); List<ProjectToOrganization> projOrgs = converter.buildObject(result, oaf); assertNotNull(projOrgs); assertEquals(2, projOrgs.size()); assertNotNull(projOrgs.get(0)); assertEquals(projectId, projOrgs.get(0).getProjectId()); assertEquals(organization1Id, projOrgs.get(0).getOrganizationId()); assertNotNull(projOrgs.get(1)); assertEquals(projectId, projOrgs.get(1).getProjectId()); assertEquals(organization2Id, projOrgs.get(1).getOrganizationId()); }
Source:
<code>public void shouldFindAllByExample() { Party party = new Party(); party.setName("party"); Example<Party> sample = Example.of(party, ExampleMatcher.matching() .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreNullValues().withIgnorePaths("attendees")); Iterable<Party> parties = repository.findAll(sample); int count = 0; for(Party p:parties) { count +=1; } <START> assertTrue(count == 14); <END> }</code><technical_language>prefer Assert.assertEquals assertion a more descriptive message in case of error</technical_language>

Target:
public void shouldFindAllByExample() { Party party = new Party(); party.setName("party"); Example<Party> sample = Example.of(party, ExampleMatcher.matching() .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreNullValues().withIgnorePaths("attendees")); Iterable<Party> parties = repository.findAll(sample); int count = 0; for(Party p:parties) { count +=1; } assertEquals("Count mismatch", 15, count); }
Source:
<code>private void createFBInstance(final ResourceDeploymentData resDepData, final IDeviceManagementInteractor executor) throws DeploymentException { Resource res = resDepData.res; for (FBDeploymentData fb : resDepData.fbs) { if (!fb.fb.isResourceTypeFB()) { executor.createFBInstance(fb, res); curMonitor.worked(1); InterfaceList interfaceList = <START> fb.fb.getInterface(); <END> if (interfaceList != null) { for (VarDeclaration varDecl : interfaceList.getInputVars()) { String val = DeploymentHelper.getVariableValue(varDecl, res.getAutomationSystem()); if (null != val) { executor.writeFBParameter(res, val, fb, varDecl); curMonitor.worked(1); } } } } } }</code><technical_language>strange. is a FB nested in FB</technical_language>

Target:
private void createFBInstance(final ResourceDeploymentData resDepData, final IDeviceManagementInteractor executor) throws DeploymentException { Resource res = resDepData.res; for (FBDeploymentData fbDepData : resDepData.fbs) { if (!fbDepData.fb.isResourceTypeFB()) { executor.createFBInstance(fbDepData, res); curMonitor.worked(1); InterfaceList interfaceList = fbDepData.fb.getInterface(); if (interfaceList != null) { for (VarDeclaration varDecl : interfaceList.getInputVars()) { String val = DeploymentHelper.getVariableValue(varDecl, res.getAutomationSystem()); if (null != val) { executor.writeFBParameter(res, val, fbDepData, varDecl); curMonitor.worked(1); } } } } } }
Source:
<code>int recover() throws URISyntaxException { <START> try (Response response = ClientBuilder.newClient().target(new URI(recoveryUrl)) <END> .request() .get()) { Assert.assertEquals("Unexpected status from reovery call:", 200, response.getStatus()); String recoveringLRAs = response.readEntity(String.class); return recoveringLRAs.length() - recoveringLRAs.replace(".", "").length(); } }</code><technical_language>Is created client closed in try-with-resources</technical_language>

Target:
int recover() throws URISyntaxException { Client client = ClientBuilder.newClient(); try (Response response = client.target(new URI(recoveryUrl)) .request() .get()) { Assert.assertEquals("Unexpected status from reovery call:", 200, response.getStatus()); String recoveringLRAs = response.readEntity(String.class); return recoveringLRAs.length() - recoveringLRAs.replace(".", "").length(); } finally { client.close(); } }
Source:
<code>private static Options parseCommandLineOrExit(List<String> args) { Options options = new Options(); CustomJCommander jCommander = new CustomJCommander("start-tc-server", options); jCommander.parse(args.toArray(new String[0])); if (options.isHelp()) { <START> jCommander.usage(); <END> System.exit(0); } options.process(jCommander); return options; }</code><technical_language>calling System.exit(...) this level... this handled caller somehow</technical_language>

Target:
private static Options parseCommandLineOrExit(List<String> args) { Options options = new Options(); CustomJCommander jCommander = new CustomJCommander(options); jCommander.parse(args.toArray(new String[0])); options.process(jCommander); return options; }
Source:
<code>private void createAndDeployZip(ArtifactoryBuildInfoClient client) throws Exception { <START> String tmpZipPath = path.toString() + File.separator + LOCAL_TMP_ZIP_FILENAME; <END> File tmpZipFile = archiveProjectDir(tmpZipPath); String deploayableZipPath = path.toString() + File.separator + LOCAL_DEPLOYABLE_ZIP_FILENAME; File deployableZipFile = new File(deploayableZipPath); GoZipBallStreamer pkgArchiver = new GoZipBallStreamer(new ZipFile(tmpZipFile), moduleName, version, logger); pkgArchiver.writeDeployableZip(deployableZipFile); Artifact deployedPackage = deploy(client, deployableZipFile, PKG_ZIP_FILE_EXTENSION); artifactList.add(deployedPackage); tmpZipFile.delete(); deployableZipFile.delete(); }</code><technical_language>This done system temp directory: Files.createTempFile()</technical_language>

Target:
private void createAndDeployZip(ArtifactoryBuildInfoClient client) throws Exception { File tmpZipFile = archiveProjectDir(); File deployableZipFile = File.createTempFile(LOCAL_PKG_FILENAME, PKG_ZIP_FILE_EXTENSION, path.toFile()); try (GoZipBallStreamer pkgArchiver = new GoZipBallStreamer(new ZipFile(tmpZipFile), moduleName, version, logger)) { pkgArchiver.writeDeployableZip(deployableZipFile); Artifact deployedPackage = deploy(client, deployableZipFile, PKG_ZIP_FILE_EXTENSION); artifactList.add(deployedPackage); } finally { Files.deleteIfExists(tmpZipFile.toPath()); Files.deleteIfExists(deployableZipFile.toPath()); } }
Source:
<code>public boolean includeMethodFromExpression(String expression, ITestNGMethod tm) { String msg = "Beanshell related classes could not be found in CLASSPATH." <START> + "Please add a dependency to bsh.Interpreter (beanshell jar) to your build file and try again."; <END> throw new TestNGException(msg); }</code><technical_language>giving exact specific Gradle coordinates here, e.g "org.beanshell:bsh:$version"</technical_language>

Target:
public boolean includeMethodFromExpression(String expression, ITestNGMethod tm) { String msg = "Beanshell related classes could not be found in CLASSPATH." + "Please add a compile dependency to 'org.apache-extras.beanshell:bsh:2.0b6' in your build file and try " + "again."; throw new TestNGException(msg); }
Source:
<code>private static String createQueueName(String clientId, String pubId, boolean shared, boolean global, boolean isVolatile) { <START> String queue = clientId == null || clientId.isEmpty() || global ? pubId : clientId + "." + pubId; <END> if (shared) { if (queue.contains("|")) { queue = queue.split("\\|")[0]; } if (isVolatile) { queue += ":shared-volatile"; } } return queue; }</code><technical_language>.. I run testsuite merge this</technical_language>

Target:
private static String createQueueName(String clientId, String pubId, boolean shared, boolean global, boolean isVolatile) { String queue = clientId == null || clientId.isEmpty() || global ? pubId : clientId + "." + pubId; if (shared) { if (queue.contains("|")) { queue = queue.split("\\|")[0]; } if (isVolatile) { queue = "nonDurable" + "." + queue; } } return queue; }
Source:
<code>public void assertCommandForColorChannelBlue() { String expectedReply = "{\"bri\" : 254, \"sat\" : 254, \"hue\" : 43691}"; assertSendCommandForColor(HSBType.BLUE, new HueLightState(), expectedReply); <START> } <END></code><technical_language>I do if access docs account: <LINK_0> | hue | uint16 | Hue of light. This is a wrapping 0 65535. Note, hue/sat values hardware dependent means programming devices garantuee color. Programming 0 65535 light resemble color red, 21845 for green 43690 for blue. | | -- | -- | -- |</technical_language>

Target:
public void assertCommandForColorChannelBlue() { String expectedReply = "{\"bri\" : 254, \"sat\" : 254, \"hue\" : 43690}"; assertSendCommandForColor(HSBType.BLUE, new HueLightState(), expectedReply); }
Source:
<code>public void testIndexSegmentationOnClient() throws Exception { IgniteCache<Object, Object> c1 = ignite(0).cache("org"); IgniteCache<Object, Object> c2 = ignite(0).cache("pers"); c1.put(1, new Organization("o1")); c1.put(2, new Organization("o2")); c2.put(1, new Person2(1, "o1")); c2.put(2, new Person2(2, "o2")); c2.put(3, new Person2(3, "o3")); String select0 = "select o.name n1, p.name n2 from \"pers\".Person2 p join \"org\".Organization o on p.name = o.name"; GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { isClient = true; qryParallelism = 2; Ignite client = startGrid(4); <START> assertEquals(2, client.cache("pers").query(new SqlFieldsQuery(select0)).getAll().size()); <END> qryParallelism = 6; assertEquals(2, client.cache("pers").query(new SqlFieldsQuery(select0)).getAll().size()); return null; } }, IgniteCheckedException .class, "Query parallelism mismatch"); }</code><technical_language>Do need lines expected startGrid() fails</technical_language>

Target:
public void testIndexSegmentationOnClient() throws Exception { IgniteCache<Object, Object> c1 = ignite(0).cache("org"); IgniteCache<Object, Object> c2 = ignite(0).cache("pers"); c1.put(1, new Organization("o1")); c1.put(2, new Organization("o2")); c2.put(1, new Person2(1, "o1")); c2.put(2, new Person2(2, "o2")); c2.put(3, new Person2(3, "o3")); String select0 = "select o.name n1, p.name n2 from \"pers\".Person2 p join \"org\".Organization o on p.name = o.name"; GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { isClient = true; qryParallelism = 2; Ignite client = startGrid(4); return null; } }, IgniteCheckedException .class, "Query parallelism mismatch"); }
Source:
<code>public void mintDepositRecordPidTest() { PID pid = repository.mintDepositRecordPid(); <START> assertTrue(pid.getRepositoryPath().contains(RepositoryPathConstants.DEPOSIT_RECORD_BASE)); <END> }</code><technical_language>do asserting more specific here, say, .startsWith(RepositoryPathConstants.DEPOSIT_RECORD_BASE)</technical_language>

Target:
public void mintDepositRecordPidTest() { PID pid = repository.mintDepositRecordPid(); assertEquals(pid.getQualifier(), RepositoryPathConstants.DEPOSIT_RECORD_BASE); assertTrue(pid.getQualifiedId().startsWith(RepositoryPathConstants.DEPOSIT_RECORD_BASE)); }
Source:
<code>private int md5(String s) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.getBytes()); byte[] digest = md5.digest(); for (int i=0; i<4; i++) digest[i] ^= digest[i+4]+digest[i+8]+digest[i+12]; return (b2i(digest[0])<< 24)|(b2i(digest[1])<<16)|(b2i(digest[2])<< 8)|b2i(digest[3]); } catch (GeneralSecurityException e) { <START> throw new Error("Could not generate MD5 hash", e); <END> } }</code><technical_language>sense throw Error here? kind of extreme</technical_language>

Target:
private int md5(String s) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.getBytes()); byte[] digest = md5.digest(); for (int i=0; i<4; i++) digest[i] ^= digest[i+4]+digest[i+8]+digest[i+12]; return (b2i(digest[0])<< 24)|(b2i(digest[1])<<16)|(b2i(digest[2])<< 8)|b2i(digest[3]); } catch (GeneralSecurityException e) { throw new RuntimeException("Could not generate MD5 hash", e); } }
Source:
<code>private boolean testForEvent(ITmfEvent event, ITmfStateSystem ss) throws AttributeNotFoundException { <START> if (fStateValueList[1] == null) { <END> ITmfXmlStateValue filter = fStateValueList[0]; int quark = IXmlStateSystemContainer.ROOT_QUARK; for (ITmfXmlStateAttribute attribute : filter.getAttributes()) { quark = attribute.getAttributeQuark(event, quark); if (quark == IXmlStateSystemContainer.ERROR_QUARK) { throw new AttributeNotFoundException(ss.getSSID() + " Attribute:" + attribute); } } ITmfStateValue valueXML; valueXML = filter.getValue(event); ITmfStateValue valueState = (quark != IXmlStateSystemContainer.ROOT_QUARK) ? ss.queryOngoingState(quark) : filter.getEventFieldValue(event); if (valueState == null) { throw new IllegalStateException(); } return compare(valueState, valueXML, fConditionOperator); } else if (fStateValueList[1] != null) { ITmfStateValue valuesXML[] = new ITmfStateValue[2]; valuesXML[0] = fStateValueList[0].getValue(event); valuesXML[1] = fStateValueList[1].getValue(event); return valuesXML[0].equals(valuesXML[1]); } throw new IllegalStateException(); }</code><technical_language>if this is a list, this needs updated</technical_language>

Target:
private boolean testForEvent(ITmfEvent event, ITmfStateSystem ss) throws AttributeNotFoundException { if (fStateValues.size() == 1) { ITmfXmlStateValue filter = fStateValues.get(0); int quark = IXmlStateSystemContainer.ROOT_QUARK; for (ITmfXmlStateAttribute attribute : filter.getAttributes()) { quark = attribute.getAttributeQuark(event, quark); if (quark == IXmlStateSystemContainer.ERROR_QUARK) { throw new AttributeNotFoundException(ss.getSSID() + " Attribute:" + attribute); } } ITmfStateValue valueState = (quark != IXmlStateSystemContainer.ROOT_QUARK) ? ss.queryOngoingState(quark) : filter.getEventFieldValue(event); if (valueState == null) { throw new IllegalStateException("TmfXmlCondition : The state value does not exist in the state system"); } ITmfStateValue valueXML; valueXML = filter.getValue(event); return compare(valueState, valueXML, fConditionOperator); } ITmfStateValue valuesXML1 = fStateValues.get(0).getValue(event); ITmfStateValue valuesXML2 = fStateValues.get(1).getValue(event); return valuesXML1.equals(valuesXML2); }
Source:
<code>private MetacardImpl getMetacard(String propertyTypeName, Map<String, Object> properties) throws CatalogTransformerException { if (isEmpty(propertyTypeName) || metacardTypes == null) { LOGGER.debug( "MetacardType specified in input is null or empty. Trying all transformers in order..."); Optional<MetacardImpl> first = inputTransformers == null ? Optional.of(new MetacardImpl()) : inputTransformers .stream() .map( serviceReference -> { try { InputTransformer inputTransformer = (InputTransformer) FrameworkUtil.getBundle(this.getClass()) .getBundleContext() .getService(serviceReference); return new MetacardImpl( inputTransformer.transform( new ByteArrayInputStream( ((String) properties.get("metadata")).getBytes()))); } catch (Exception e) { LOGGER.debug( "Error calling transformer: " + serviceReference.getProperty("id"), e); } return null; }) .filter(Objects::nonNull) .findFirst(); <START> return first.orElse(new MetacardImpl()); <END> } else { MetacardType metacardType = metacardTypes .stream() .filter(type -> type.getName().equals(propertyTypeName)) .findFirst() .orElseThrow( () -> new CatalogTransformerException( "MetacardType specified in input has not been registered with the system." + " Cannot parse input. MetacardType name: " + propertyTypeName)); LOGGER.debug("Found registered MetacardType: {}", propertyTypeName); return new MetacardImpl(metacardType); } }</code><technical_language>Do need this orElse(new MetacardImpl() in addition Optional.of(new MetacardImpl()) line above</technical_language>

Target:
private MetacardImpl getMetacard(String propertyTypeName, Map<String, Object> properties) throws CatalogTransformerException { if (isEmpty(propertyTypeName) || metacardTypes == null) { LOGGER.debug( "MetacardType specified in input is null or empty. Trying all transformers in order..."); Optional<MetacardImpl> first = inputTransformers == null ? Optional.of(new MetacardImpl()) : inputTransformers .stream() .map(service -> tryTransformers(properties, service)) .filter(Objects::nonNull) .findFirst(); return first.orElse(new MetacardImpl()); } else { MetacardType metacardType = metacardTypes .stream() .filter(type -> type.getName().equals(propertyTypeName)) .findFirst() .orElseThrow( () -> new CatalogTransformerException( "MetacardType specified in input has not been registered with the system." + " Cannot parse input. MetacardType name: " + propertyTypeName)); LOGGER.debug("Found registered MetacardType: {}", propertyTypeName); return new MetacardImpl(metacardType); } }
Source:
<code>protected AmqpBrokerConfig createAmqpBrokerConfig(MsbConfig msbConfig) { Config amqpApplicationConfig = msbConfig.getBrokerConfig(); Config amqpLibConfig = ConfigFactory.load("amqp").getConfig("config.amqp"); Config commonConfig = ConfigFactory.defaultOverrides() .withFallback(amqpApplicationConfig) .withFallback(amqpLibConfig); AmqpBrokerConfig brokerConfig = new AmqpBrokerConfig.AmqpBrokerConfigBuilder().withConfig(commonConfig).build(); <START> if (brokerConfig != null && (brokerConfig.getGroupId() == null || !brokerConfig.getGroupId().isPresent())) { <END> brokerConfig.setGroupId(Optional.of(msbConfig.getServiceDetails().getName())); } return brokerConfig; }</code><technical_language>simplify this condition</technical_language>

Target:
protected AmqpBrokerConfig createAmqpBrokerConfig(MsbConfig msbConfig) { Config amqpApplicationConfig = msbConfig.getBrokerConfig(); Config amqpLibConfig = ConfigFactory.load("amqp").getConfig("config.amqp"); Config commonConfig = ConfigFactory.defaultOverrides() .withFallback(amqpApplicationConfig) .withFallback(amqpLibConfig); AmqpBrokerConfig brokerConfig = new AmqpBrokerConfig.AmqpBrokerConfigBuilder().withConfig(commonConfig).build(); if (brokerConfig != null && !brokerConfig.getGroupId().isPresent()) { brokerConfig.setGroupId(Optional.of(msbConfig.getServiceDetails().getName())); } return brokerConfig; }
Source:
<code>public void sendChunk(ByteBuf chunk) throws IOException { if (closed.get()) { throw new IOException("ChunkResponder already closed."); } if (!channel.isActive()) { throw new IOException("Connection already closed."); } channel.write(new DefaultHttpContent(chunk)); <START> if (size.addAndGet(chunk.readableBytes()) >= chunkMemoryLimit) { <END> channel.flush(); } }</code><technical_language>size get reset</technical_language>

Target:
public void sendChunk(ByteBuf chunk) throws IOException { if (closed.get()) { throw new IOException("ChunkResponder already closed."); } if (!channel.isActive()) { throw new IOException("Connection already closed."); } int chunkSize = chunk.readableBytes(); channel.write(new DefaultHttpContent(chunk)); tryFlush(chunkSize); }
Source:
<code>private void downloadAndCopyJars (Set<String> jarsToDownload, Path destinationPath) throws IOException { Set<String> copiedJars = new HashSet<>(); for (String jar: jarsToDownload) { if (!copiedJars.contains(jar)) { Path jarPath = Paths.get(jar); File destPath = null; if (destinationPath != null && jarPath != null) { Path jarFileName = jarPath.getFileName(); <START> if (jarFileName != null) { <END> destPath = Paths.get(destinationPath.toString(), jarFileName.toString()).toFile(); } } if (destPath == null) { throw new RuntimeException("null destPath"); } try (InputStream src = fileStorage.download(jar); FileOutputStream dest = new FileOutputStream(destPath) ) { IOUtils.copy(src, dest); copiedJars.add(jar); LOG.debug("Jar copied to {}", jar, destPath); } } } }</code><technical_language>null? If not, change code block if (destinationPath == null || jarPath == null) { throw new RuntimeException("either destination path jar path is null"); } Path jarFileName = jarPath.getFileName(); File destPath = Paths.get(destinationPath.toString(), jarFileName.toString()).toFile(); throw more specific exception IllegalArgumentException</technical_language>

Target:
private void downloadAndCopyJars (Set<String> jarsToDownload, Path destinationPath) throws IOException { Set<String> copiedJars = new HashSet<>(); for (String jar: jarsToDownload) { if (!copiedJars.contains(jar)) { Path jarPath = Paths.get(jar); if (destinationPath == null || jarPath == null) { throw new IllegalArgumentException("null destinationPath or jarPath"); } Path jarFileName = jarPath.getFileName(); if (jarFileName == null) { throw new IllegalArgumentException("null farFileName"); } File destPath = Paths.get(destinationPath.toString(), jarFileName.toString()).toFile(); try (InputStream src = fileStorage.download(jar); FileOutputStream dest = new FileOutputStream(destPath) ) { IOUtils.copy(src, dest); copiedJars.add(jar); LOG.debug("Jar copied to {}", jar, destPath); } } } }
Source:
<code>public ListenableFuture<Long> writeDirect(final ByteBuffer bb, final InetSocketAddress remoteAddress) { long size = 0; try { size = channel.send(bb, remoteAddress); <START> } catch (IOException e) { <END> return FutureUtils.immediateFailureFuture(e); } return FutureUtils.immediateResultFuture(size); }</code><technical_language>Another case catch Exception</technical_language>

Target:
public ListenableFuture<Long> writeDirect(final ByteBuffer bb, final InetSocketAddress remoteAddress) { long size = 0; try { size = channel.send(bb, remoteAddress); } catch (Exception e) { return FutureUtils.immediateFailureFuture(e); } return FutureUtils.immediateResultFuture(size); }
Source:
<code>private ContrastEnhancementBuilder contrastMethod(String name, Map<String, Expression> constrastParameters) { <START> if ("histogram".equals(name)) { <END> this.method = ContrastMethod.HISTOGRAM; } else if ("normalize".equals(name)) { this.method = ContrastMethod.NORMALIZE; } else if ("logarithmic".equals(name)) { this.method = ContrastMethod.LOGARITHMIC; } else if ("exponential".equals(name)) { this.method = ContrastMethod.EXPONENTIAL; } else { throw new IllegalArgumentException("Unexpected ContrastEnhamcement method " + name); } if(constrastParameters!=null) { options = constrastParameters; } this.unset = false; return this; }</code><technical_language>This is stilly - a method code list name ignoring case</technical_language>

Target:
private ContrastEnhancementBuilder contrastMethod(String name, Map<String, Expression> constrastParameters) { this.method = ContrastMethod.valueOf(name); if(constrastParameters!=null) { options = constrastParameters; } this.unset = false; return this; }
Source:
<code>Map<String, String> fetchAccountMetadataFromZNRecord(ZNRecord record) { if (router.get() == null) { logger.error("Router is not yet initialized"); return null; } List<String> accountBlobIDs = record.getListField(ACCOUNT_METADATA_BLOB_IDS_LIST_KEY); if (accountBlobIDs == null || accountBlobIDs.size() == 0) { <START> logger.debug("ZNRecord={} to read on path={} does not have a simple list with key={}", record, <END> ACCOUNT_METADATA_BLOB_IDS_PATH, ACCOUNT_METADATA_BLOB_IDS_LIST_KEY); return null; } else { BlobIDAndVersion blobIDAndVersion = null; for (String accountBlobIDInJson : accountBlobIDs) { BlobIDAndVersion current = BlobIDAndVersion.fromJson(accountBlobIDInJson); if (blobIDAndVersion == null || blobIDAndVersion.version < current.version) { blobIDAndVersion = current; } } logger.trace("Start reading remote account data from blob and versioned at {}.", blobIDAndVersion.blobID, blobIDAndVersion.version); return readAccountMetadataFromBlobID(blobIDAndVersion.blobID); } }</code><technical_language>here, warn</technical_language>

Target:
Map<String, String> fetchAccountMetadataFromZNRecord(ZNRecord record) { if (router.get() == null) { logger.error("Router is not yet initialized"); return null; } List<String> accountBlobIDs = record.getListField(ACCOUNT_METADATA_BLOB_IDS_LIST_KEY); if (accountBlobIDs == null || accountBlobIDs.size() == 0) { logger.info("ZNRecord={} to read on path={} does not have a simple list with key={}", record, ACCOUNT_METADATA_BLOB_IDS_PATH, ACCOUNT_METADATA_BLOB_IDS_LIST_KEY); return null; } else { BlobIDAndVersion blobIDAndVersion = null; for (String accountBlobIDInJson : accountBlobIDs) { BlobIDAndVersion current = BlobIDAndVersion.fromJson(accountBlobIDInJson); if (blobIDAndVersion == null || blobIDAndVersion.version < current.version) { blobIDAndVersion = current; } } logger.trace("Start reading remote account data from blob and versioned at {}.", blobIDAndVersion.blobID, blobIDAndVersion.version); return readAccountMetadataFromBlobID(blobIDAndVersion.blobID); } }
Source:
<code>public static String getName(String path) { String[] temp; <START> String delimiter = "/"; <END> temp = path.split(delimiter); int size = temp.length; String name = temp[(size - 1)]; System.out.println(name.replaceAll(" ", "_").toLowerCase()); return name.replaceAll(" ", "_").toLowerCase(); }</code><technical_language>this work windows? I File.seperator</technical_language>

Target:
public static String getName(String path) { String[] temp; String delimiter = File.separator; temp = path.split(delimiter); int size = temp.length; String name = temp[(size - 1)]; System.out.println(name.replaceAll(" ", "_").toLowerCase()); return name.replaceAll(" ", "_").toLowerCase(); }
Source:
<code>protected PollingResult compareRemoteRevisionWith(AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState _baseline) throws IOException, InterruptedException { final AbstractBuild lastBuild = project.getLastBuild(); if (lastBuild == null) { return PollingResult.BUILD_NOW; <START> } <END> MercurialTagAction baseline = (MercurialTagAction)_baseline; PrintStream output = listener.getLogger(); Node node = project.getLastBuiltOn(); FilePath repository = workspace2Repo(workspace); pull(launcher, repository, listener, output, node); String revisionToBuild = buildChooser.getRevisionToBuild(lastBuild, launcher, workspace, listener); return "tip".equals(revisionToBuild) ? PollingResult.NO_CHANGES : PollingResult.SIGNIFICANT; }</code><technical_language>Is this block needed? impression this case handled AbstractProject.poll(): java R lb = getLastBuild(); if (lb==null) { listener.getLogger().println(Messages.AbstractProject_NoBuilds()); return isInQueue() ? NO_CHANGES : BUILD_NOW; }</technical_language>

Target:
protected PollingResult compareRemoteRevisionWith(AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState _baseline) throws IOException, InterruptedException { final AbstractBuild lastBuild = project.getLastBuild(); PrintStream output = listener.getLogger(); Node node = project.getLastBuiltOn(); FilePath repository = workspace2Repo(workspace); pull(launcher, repository, listener, output, node); MercurialTagAction revisionToBuild = buildChooser.getRevisionToBuild(lastBuild, launcher, workspace, listener); return revisionToBuild == null ? PollingResult.NO_CHANGES : PollingResult.SIGNIFICANT; }
Source:
<code>protected boolean validate() { if (!canRunActionOnNonManagedVm()) { return false; } if (!isInternalExecution() && !ObjectIdentityChecker.canUpdateField(getVm(), "clusterId", getVm().getStatus())) { addValidationMessage(EngineMessage.VM_STATUS_NOT_VALID_FOR_UPDATE); return false; } ChangeVmClusterValidator validator = ChangeVmClusterValidator.create(this, newClusterId, getParameters().getVmCustomCompatibilityVersion()); if (macPoolChanged()) { ReadMacPool macPoolForTargetCluster = macPoolPerCluster.getMacPoolForCluster(newClusterId); ValidationResult validationResult = <START> validator.validateCanMoveMacs(macPoolForTargetCluster, getMacsToMigrate()); <END> if (!validationResult.isValid()) { return validate(validationResult); } } return validator.validate(); }</code><technical_language>Please reuse 'moveMacs.canMigrateMacsToAnotherMacPool(..)' code</technical_language>

Target:
protected boolean validate() { if (!canRunActionOnNonManagedVm()) { return false; } if (!isInternalExecution() && !ObjectIdentityChecker.canUpdateField(getVm(), "clusterId", getVm().getStatus())) { addValidationMessage(EngineMessage.VM_STATUS_NOT_VALID_FOR_UPDATE); return false; } ChangeVmClusterValidator validator = ChangeVmClusterValidator.create(this, newClusterId, getParameters().getVmCustomCompatibilityVersion()); if (macPoolChanged()) { ReadMacPool macPoolForTargetCluster = macPoolPerCluster.getMacPoolForCluster(newClusterId); ValidationResult validationResult = moveMacs.canMigrateMacsToAnotherMacPool(macPoolForTargetCluster, getMacsToMigrate()); if (!validationResult.isValid()) { return validate(validationResult); } } return validator.validate(); }
Source:
<code>public void createDispoDiscrepancies(BranchId branch, String itemId, List<Discrepancy> discrepancies, String userName) { String <START> idOfNewDiscrepancy = <END> ""; DispoItem dispoItem = getQuery().findDispoItemById(branch, itemId); if (dispoItem != null) { Map<String, Discrepancy> discrepancyList = dispoItem.getDiscrepanciesList(); Collection<DispoItem> dispoItems = new ArrayList<>(); for (Discrepancy discrepancy : discrepancies) { idOfNewDiscrepancy = dataFactory.getNewId(); discrepancy.setId(idOfNewDiscrepancy); if (discrepancy.getLocation() == null) { discrepancy.setLocation(""); } if (discrepancy.getText() == null) { discrepancy.setText(""); } discrepancyList.put(idOfNewDiscrepancy, discrepancy); DispoItemData newItem = new DispoItemData(); newItem.setDiscrepanciesList(discrepancyList); newItem.setStatus(dispoConnector.getItemStatus(newItem)); dispoItems.add(newItem); } ArtifactReadable author = getQuery().findUser(); DispoStorageMetadata metadata = new DispoStorageMetadata(); String operation = String.format("Create Dispo Discrepancies in Program [%s], Item [%s]", branch, itemId); getWriter().updateDispoItems(author, branch, dispoItems, false, operation, metadata); if (!metadata.getIdsOfUpdatedItems().isEmpty()) { updateBroadcaster.broadcastUpdateItems(metadata.getIdsOfUpdatedItems(), singleton(dispoItem), getDispoItemParentSet(branch, itemId)); } } }</code><technical_language>move this for loop</technical_language>

Target:
public void createDispoDiscrepancies(BranchId branch, String itemId, List<Discrepancy> discrepancies, String userName) { DispoItem dispoItem = getQuery().findDispoItemById(branch, itemId); if (dispoItem != null) { Map<String, Discrepancy> discrepancyList = dispoItem.getDiscrepanciesList(); Collection<DispoItem> dispoItems = new ArrayList<>(); for (Discrepancy discrepancy : discrepancies) { String idOfNewDiscrepancy = ""; idOfNewDiscrepancy = dataFactory.getNewId(); discrepancy.setId(idOfNewDiscrepancy); if (discrepancy.getLocation() == null) { discrepancy.setLocation(""); } if (discrepancy.getText() == null) { discrepancy.setText(""); } discrepancyList.put(idOfNewDiscrepancy, discrepancy); DispoItemData newItem = new DispoItemData(); newItem.setDiscrepanciesList(discrepancyList); newItem.setStatus(dispoConnector.getItemStatus(newItem)); dispoItems.add(newItem); } ArtifactReadable author = getQuery().findUser(); DispoStorageMetadata metadata = new DispoStorageMetadata(); String operation = String.format("Create Dispo Discrepancies in Program [%s], Item [%s]", branch, itemId); getWriter().updateDispoItems(author, branch, dispoItems, false, operation, metadata); if (!metadata.getIdsOfUpdatedItems().isEmpty()) { updateBroadcaster.broadcastUpdateItems(metadata.getIdsOfUpdatedItems(), singleton(dispoItem), getDispoItemParentSet(branch, itemId)); } } }
Source:
<code>public Action getActionObject(String uri, String method, String body, Map<String, Part> parts, List<Cookie> cookies, String... params) { try { MockHttpServletRequest req = new MockHttpServletRequest(method, Const.ResourceURIs.URI_PREFIX + uri); for (int i = 0; i < params.length; i = i + 2) { req.addParam(params[i], params[i + 1]); } if (body != null) { req.setBody(body); } if (parts != null) { parts.forEach((key, part) -> { try { req.addPart(key, part); } catch (IOException e) { throw new RuntimeException(e); } }); } if (cookies != null) { for (Cookie cookie : cookies) { <START> req.addCookie(new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, cookie.getValue())); <END> } } MockHttpServletResponse resp = new MockHttpServletResponse(); Action action = new ActionFactory().getAction(req, method, resp); action.setTaskQueuer(new MockTaskQueuer()); action.setEmailSender(new MockEmailSender()); return action; } catch (ActionMappingException e) { throw new RuntimeException(e); } }</code><technical_language>suggestion req.addCookie(cookie);</technical_language>

Target:
public Action getActionObject(String uri, String method, String body, Map<String, Part> parts, List<Cookie> cookies, String... params) { try { MockHttpServletRequest req = new MockHttpServletRequest(method, Const.ResourceURIs.URI_PREFIX + uri); for (int i = 0; i < params.length; i = i + 2) { req.addParam(params[i], params[i + 1]); } if (body != null) { req.setBody(body); } if (parts != null) { parts.forEach((key, part) -> { try { req.addPart(key, part); } catch (IOException e) { throw new RuntimeException(e); } }); } if (cookies != null) { for (Cookie cookie : cookies) { req.addCookie(cookie); } } Action action = new ActionFactory().getAction(req, method); action.setTaskQueuer(new MockTaskQueuer()); action.setEmailSender(new MockEmailSender()); return action; } catch (ActionMappingException e) { throw new RuntimeException(e); } }
Source:
<code>public static Color toColor(RGB rgb) { <START> return new Color(rgb.red / 255, rgb.green / 255, rgb.blue / 255, 1); <END> }</code><technical_language>I division int division (always return 0 1) while willing get double. /255. instead convert a double division</technical_language>

Target:
public static Color toColor(RGB rgb) { return new Color(rgb.red / 255d, rgb.green / 255d, rgb.blue / 255d, 1); }
Source:
<code>public @NotNull Span currentSpan() throws EmptyStackException { <START> if (!hasSpan()) { <END> throw new EmptyStackException(); } else { return scopeManager.activeSpan(); } }</code><technical_language>introducing double retrieval thread local, unnecessary perf hit</technical_language>

Target:
public @NotNull Span currentSpan() throws EmptyStackException { Span span = scopeManager.activeSpan(); if (span == null) { throw new EmptyStackException(); } return span; }
Source:
<code>public void startLdapServer() throws Exception { UnboundIdContainer server = new UnboundIdContainer( validRootDn, validLdifClassPath); server.setApplicationContext(new GenericApplicationContext()); List<Integer> ports = getDefaultPorts(1); server.setPort(ports.get(0)); try { server.afterPropertiesSet(); assertThat(server.getPort()).isEqualTo(ports.get(0)); } finally { server.destroy(); } <START> } <END></code><technical_language>want allow a null for LDIF file, is required for developer provide one</technical_language>

Target:
public void startLdapServer() throws Exception { UnboundIdContainer server = new UnboundIdContainer( validRootDn, validLdifClassPath); createAndRunServer(server); }
Source:
<code>public String deploy(String url, String targetName) { String canonicalTargetName = getFilenameContextMapper().convertDeploymentTargetNameToFilename(targetName); String dest = getDeployDir() + "/" + canonicalTargetName; log.info("{} deploying to {}:{}", new Object[]{entity, url, getHostname(), dest}); getMachine().run(String.format("mv -f %s %s.bak > /dev/null 2>&1", dest, dest)); int result = -1; if (url.toLowerCase().matches("^https?://.*")) { result = getMachine().execCommands("download", ImmutableList.of( CommonCommands.INSTALL_WGET, <START> String.format("wget --no-check-certificate %s -O %s > /dev/null 2>&1", url, dest))); <END> } if (result != 0) { result = getMachine().copyTo(getResource(url), dest); } log.debug("{} deployed to {}:{}: result {}", new Object[]{entity, url, getHostname(), dest, result}); if (result!=0) log.warn("Problem deploying to {}:{} for {}: result {}", new Object[]{url, getHostname(), dest, entity, result}); return getFilenameContextMapper().convertDeploymentTargetNameToContext(canonicalTargetName); }</code><technical_language>Do want redirect stderr /dev/null? useful in debug log? I presume stdout is noisy lots of progress reports downloads..</technical_language>

Target:
public String deploy(String url, String targetName) { String canonicalTargetName = getFilenameContextMapper().convertDeploymentTargetNameToFilename(targetName); String dest = getDeployDir() + "/" + canonicalTargetName; log.info("{} deploying to {}:{}", new Object[]{entity, url, getHostname(), dest}); getMachine().run(String.format("mv -f %s %s.bak > /dev/null 2>&1", dest, dest)); int result = -1; if (url.toLowerCase().matches("^https?://.*")) { result = getMachine().execCommands("download", ImmutableList.of( CommonCommands.INSTALL_CURL, String.format("curl --silent --insecure %s -o %s", url, dest))); } if (result != 0) { result = getMachine().copyTo(getResource(url), dest); } log.debug("{} deployed to {}:{}: result {}", new Object[]{entity, url, getHostname(), dest, result}); if (result!=0) log.warn("Problem deploying to {}:{} for {}: result {}", new Object[]{url, getHostname(), dest, entity, result}); return getFilenameContextMapper().convertDeploymentTargetNameToContext(canonicalTargetName); }