auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public AdaptiveExercise parseFromJson(String json) { if (json == null) { throw new NullPointerException("Json string is null"); } if (json.trim().isEmpty()) { throw new IllegalArgumentException("Empty input"); } <START> if (json.contains("\"available\":\"false\"")) { <END> logger.info("The exercise is not available."); return null; } try { Gson gson = new GsonBuilder().create(); AdaptiveExercise adaptive = gson.fromJson(json, AdaptiveExercise.class); if (adaptive.getAvailable()) { String parsedUrl = adaptive.getZipUrl().toString(); adaptive.setZipUrl(URI.create("http://" + parsedUrl)); return adaptive; } logger.info("The gson parsed adaptive exercise is not available."); return null; } catch (RuntimeException ex) { logger.warn("Failed to parse an adaptive course from URL", ex); throw new RuntimeException("Failed to parse an adaptive course from URL: " + ex.getMessage(), ex); } }</code><technical_language>This brittle: JSON allows whitespace colon</technical_language>

Target:
public AdaptiveExercise parseFromJson(String json) { if (json == null) { throw new NullPointerException("Json string is null"); } if (json.trim().isEmpty()) { throw new IllegalArgumentException("Empty input"); } try { Gson gson = new GsonBuilder().create(); AdaptiveExercise adaptive = gson.fromJson(json, AdaptiveExercise.class); if (adaptive.getAvailable()) { String parsedUrl = adaptive.getZipUrl().toString(); adaptive.setZipUrl(URI.create("http://" + parsedUrl)); return adaptive; } logger.info("The gson parsed adaptive exercise is not available."); return null; } catch (RuntimeException ex) { logger.warn("Failed to parse an adaptive course from URL", ex); throw new RuntimeException("Failed to parse an adaptive course from URL: " + ex.getMessage(), ex); } }
Source:
<code>public void testReWriteArtifactViaStreamFails() throws Exception { ProvisionException expectedException = null; try { <START> try (OutputStream addSink = subject.getOutputStream(ARTIFACT_A_CANONICAL)) { <END> addSink.write(new byte[1]); } } catch (ProvisionException e) { expectedException = e; } assertThat(expectedException, is(instanceOf(ProvisionException.class))); assertThat(expectedException.getStatus().getCode(), is(ProvisionException.ARTIFACT_EXISTS)); }</code><technical_language>style nit: tabs spaces, inconsistent surrounding code</technical_language>

Target:
public void testReWriteArtifactViaStreamFails() throws Exception { ProvisionException expectedException = null; try (OutputStream addSink = subject.getOutputStream(ARTIFACT_A_CANONICAL)) { addSink.write(new byte[1]); } catch (ProvisionException e) { expectedException = e; } assertThat(expectedException, is(instanceOf(ProvisionException.class))); assertThat(expectedException.getStatus().getCode(), is(ProvisionException.ARTIFACT_EXISTS)); }
Source:
<code>public void tearDown() { <START> tmpFolder.delete(); <END> }</code><technical_language>delete directory. FileUtils.deleteDirectory</technical_language>

Target:
public void tearDown() throws IOException { FileUtils.deleteDirectory(tmpFolder.getRoot()); }
Source:
<code>private void doParseJvmHeapMemByChildOptsTest(String message, List<String> opts, double expected) { Assert.assertEquals( message, <START> expected, Utils.parseJvmHeapMemByChildOpts(opts, 123.0).doubleValue(), 0); <END> }</code><technical_language>doubleValue is redundant</technical_language>

Target:
private void doParseJvmHeapMemByChildOptsTest(String message, List<String> opts, double expected) { Assert.assertEquals(message, expected, Utils.parseJvmHeapMemByChildOpts(opts, 123.0), 0); }
Source:
<code>public static TimeZone getTimeZoneFromDoubleOffset(double sessionTimeZone) { String sign = sessionTimeZone > 0 ? "+" : "-"; int hours = (int) sessionTimeZone; int minutes = (int) ((Math.abs(sessionTimeZone) - Math.floor(Math.abs(sessionTimeZone))) * 60); String offset = Integer.toString(hours); if (minutes != 0) { offset = Integer.toString(hours) + ":" + Integer.toString(minutes); } <START> String customId = TimeZone.getTimeZone("GMT" + sign + offset).getID(); <END> return TimeZone.getTimeZone(customId); }</code><technical_language>[String.format](<LINK_0>,%20java.lang.Object...)) code more concise</technical_language>

Target:
public static TimeZone getTimeZoneFromDoubleOffset(double sessionTimeZone) { int hours = (int) sessionTimeZone; int minutes = (int) ((Math.abs(sessionTimeZone) - Math.floor(Math.abs(sessionTimeZone))) * 60); return TimeZone.getTimeZone(String.format("GMT%+03d:%02d", hours, minutes)); }
Source:
<code>public final void onStart() throws Exception { try { startResourceManagerServices(); } catch (Throwable t) { <START> getTerminationFuture().completeExceptionally(t); <END> final ResourceManagerException exception = new ResourceManagerException(String.format("Could not start the ResourceManager %s", getAddress()), t); onFatalError(exception); throw exception; } }</code><technical_language>needed</technical_language>

Target:
public final void onStart() throws Exception { try { startResourceManagerServices(); } catch (Throwable t) { final ResourceManagerException exception = new ResourceManagerException(String.format("Could not start the ResourceManager %s", getAddress()), t); onFatalError(exception); throw exception; } }
Source:
<code>protected void handleMessage(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessage responseMessage, final OsgpException osgpException) throws FunctionalException { if (responseMessage.getDataObject() instanceof ScanMbusChannelsResponseDto) { <START> @SuppressWarnings("unchecked") <END> final ScanMbusChannelsResponseDto mbusAttributesList = (ScanMbusChannelsResponseDto) responseMessage .getDataObject(); this.adhocService.handleScanMbusChannelsResponse(deviceMessageMetadata, responseMessage.getResult(), osgpException, mbusAttributesList); } else { throw new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR, ComponentType.DOMAIN_SMART_METERING, new OsgpException(ComponentType.DOMAIN_SMART_METERING, "DataObject for response message should be of type MbusAttributesDto")); } }</code><technical_language>I do this is necessary</technical_language>

Target:
protected void handleMessage(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessage responseMessage, final OsgpException osgpException) throws FunctionalException { if (responseMessage.getDataObject() instanceof ScanMbusChannelsResponseDto) { final ScanMbusChannelsResponseDto mbusAttributesList = (ScanMbusChannelsResponseDto) responseMessage .getDataObject(); this.adhocService.handleScanMbusChannelsResponse(deviceMessageMetadata, responseMessage.getResult(), osgpException, mbusAttributesList); } else { throw new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR, ComponentType.DOMAIN_SMART_METERING, new OsgpException(ComponentType.DOMAIN_SMART_METERING, "DataObject for response message should be of type ScanMbusChannelsResponseDto")); } }
Source:
<code>public void serialize(final PhysicalPort port, final JsonGenerator jgen, final SerializerProvider sp) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("dpid", port.getParentSwitch().getSwitchName()); <START> jgen.writeStringField("port", String.valueOf(port.getPortNumber())); <END> jgen.writeEndObject(); }</code><technical_language>string</technical_language>

Target:
public void serialize(final PhysicalPort port, final JsonGenerator jgen, final SerializerProvider sp) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("dpid", port.getParentSwitch().getSwitchName()); jgen.writeNumberField("port", port.getPortNumber()); jgen.writeEndObject(); }
Source:
<code>protected void processAttributesBeforeUpdate(String userName, Map<String, String> userStorePropertyValues, String profileName) { String immutableAttributesProperty = Optional.ofNullable(realmConfig <START> .getUserStoreProperty(UserStoreConfigConstants.immutableAttributes)).orElse(""); <END> String[] immutableAttributes = StringUtils.split(immutableAttributesProperty, ","); if (logger.isDebugEnabled()) { logger.debug("Retrieved user store properties for update: " + userStorePropertyValues); } if (ArrayUtils.isNotEmpty(immutableAttributes)) { if (logger.isDebugEnabled()) { logger.debug("Skipping Active Directory maintained default attributes: " + Arrays.toString(immutableAttributes)); } Arrays.stream(immutableAttributes).map(StringUtils::trim).forEach(userStorePropertyValues::remove); } }</code><technical_language>constant in stringutils</technical_language>

Target:
protected void processAttributesBeforeUpdate(String userName, Map<String, String> userStorePropertyValues, String profileName) { String immutableAttributesProperty = Optional.ofNullable(realmConfig .getUserStoreProperty(UserStoreConfigConstants.immutableAttributes)).orElse(StringUtils.EMPTY); String[] immutableAttributes = StringUtils.split(immutableAttributesProperty, ","); if (logger.isDebugEnabled()) { logger.debug("Retrieved user store properties for update: " + userStorePropertyValues); } if (ArrayUtils.isNotEmpty(immutableAttributes)) { if (logger.isDebugEnabled()) { logger.debug("Skipping Active Directory maintained default attributes: " + Arrays.toString(immutableAttributes)); } Arrays.stream(immutableAttributes).map(StringUtils::trim).forEach(userStorePropertyValues::remove); } }
Source:
<code>public int getVersion() { <START> return (int) version; <END> }</code><technical_language>If cast casted reading data array</technical_language>

Target:
public int getVersion() { return version; }
Source:
<code>private void validate() { boolean isRealmModeSet = _realmMode != null; boolean isShardingKeySet = _zkRealmShardingKey != null && !_zkRealmShardingKey.isEmpty(); <START> switch (isRealmModeSet ? _realmMode : RealmMode.MULTI_REALM) { <END> case MULTI_REALM: if (isShardingKeySet && isRealmModeSet) { throw new IllegalArgumentException( "ZK sharding key cannot be set on multi-realm mode! Sharding key: " + _zkRealmShardingKey); } break; case SINGLE_REALM: if (!isShardingKeySet) { throw new IllegalArgumentException( "ZK sharding key must be set on single-realm mode!"); } break; default: throw new ZkClientException("RealmAwareZkConnectionConfig: Unknown mode!"); } }</code><technical_language>default set realmMode multi realm. set multi realm default in constructor ? if sharding key is set only, allow single realm default? easier check code logic? default: 1. sharding key realm mode set, default is multi realm 2. sharding key is set, single realm 3. Sharding key multi realm set, illegal</technical_language>

Target:
private void validate() { boolean isShardingKeySet = _zkRealmShardingKey != null && !_zkRealmShardingKey.isEmpty(); if (_realmMode == RealmMode.MULTI_REALM && isShardingKeySet) { throw new IllegalArgumentException( "ZK sharding key cannot be set on multi-realm mode! Sharding key: " + _zkRealmShardingKey); } if (_realmMode == RealmMode.SINGLE_REALM && !isShardingKeySet) { throw new IllegalArgumentException("ZK sharding key must be set on single-realm mode!"); } }
Source:
<code>private void populateMetaData(MetaDataStore metaDataStore) { metaDataStore.getModelsToBind() .forEach(model -> { if (!metadataDictionary.isJPAEntity(model) && !metadataDictionary.getRelationships(model).isEmpty()) { throw new InvalidPredicateException( "Non-JPA entities " + model.getSimpleName() + " is not allowed to have relationship."); } }); metaDataStore.getModelsToBind().stream() .map(model -> constructTable(model, metadataDictionary)) .forEach(metaDataStore::addTable); <START> metaDataStore.resolveReference(); <END> metaDataStore.resolveSourceColumn(); }</code><technical_language>QueryEngine needs populate metadata store. metadata store (in constructor) needs resolved. I feel of this logic belongs there</technical_language>

Target:
private void populateMetaData(MetaDataStore metaDataStore) { metaDataStore.getModelsToBind() .forEach(model -> { if (!metadataDictionary.isJPAEntity(model) && !metadataDictionary.getRelationships(model).isEmpty()) { throw new InvalidPredicateException( "Non-JPA entities " + model.getSimpleName() + " is not allowed to have relationship."); } }); metaDataStore.getModelsToBind().stream() .map(model -> constructTable(model, metadataDictionary)) .forEach(metaDataStore::addTable); }
Source:
<code>private boolean acquireLockInternal(EngineLock lock) { boolean checkOnly = true; <START> for (int i = 0; i < 2; i++) { <END> if (lock.getUpdateRegions() != null) { for (Entry<String, Guid> entry : lock.getUpdateRegions().entrySet()) { if (!insertUpdateLock(buildHashMapKey(entry), checkOnly)) { return false; } } } if (lock.getLockedRegions() != null) { for (Entry<String, Guid> entry : lock.getLockedRegions().entrySet()) { if (!insertLockedLock(buildHashMapKey(entry), checkOnly)) { return false; } } } checkOnly = false; } return true; }</code><technical_language>I think, factor method instead for loop, for understand flow, for example this: getLocks(lock,true); getLocks(lock,false);</technical_language>

Target:
private boolean acquireLockInternal(EngineLock lock) { boolean checkOnly = true; for (int i = 0; i < 2; i++) { if (lock.getSemaphoreLocks() != null) { for (Entry<String, Guid> entry : lock.getSemaphoreLocks().entrySet()) { if (!insertSemaphoreLock(buildHashMapKey(entry), checkOnly)) { log.debugFormat("Failed to acquire a lock because of semaphore lock - key :{0} and value {1}", entry.getKey(), entry.getValue()); return false; } } } if (lock.getExclusiveLocks() != null) { for (Entry<String, Guid> entry : lock.getExclusiveLocks().entrySet()) { if (!insertExclusiveLock(buildHashMapKey(entry), checkOnly)) { log.debugFormat("Failed to acquire a lock because of exclusive lock - key :{0} and value {1}", entry.getKey(), entry.getValue()); return false; } } } checkOnly = false; } log.debug("Successed to acquire a lock"); return true; }
Source:
<code>protected DomainEventStream readEvents(String aggregateIdentifier) { DomainEventStream fullStream = eventStore.readEvents(aggregateIdentifier); <START> if (filter != null) { <END> return fullStream.filter(filter); } else { return fullStream; } }</code><technical_language>Nit: find a tertiary operator a cleaner a if-else block this. So: return filter != null ? fullStream.filter(filter) : fullStream; solution here</technical_language>

Target:
protected DomainEventStream readEvents(String aggregateIdentifier) { DomainEventStream fullStream = eventStore.readEvents(aggregateIdentifier); return eventStreamFilter != null ? fullStream.filter(eventStreamFilter) : fullStream; }
Source:
<code>private static List<Entity> fillTransport(AtBScenario scenario, Entity transport, UnitGeneratorParameters params, int skill, Campaign campaign) { List<Entity> transportedUnits = new ArrayList<>(); if(scenario.getTransportLinkages().containsKey(transport.getExternalIdAsString())) { return transportedUnits; } for(Transporter bay : transport.getTransports()) { if(bay instanceof TroopSpace) { double bayCapacity = ((TroopSpace) bay).getUnused(); UnitGeneratorParameters newParams = params.clone(); newParams.clearMovementModes(); newParams.setWeightClass(AtBDynamicScenarioFactory.UNIT_WEIGHT_UNSPECIFIED); Entity transportedUnit = null; int baRoll = Compute.d6(2); if(baRoll >= infantryToBAUpgradeTNs[params.getQuality()]) { transportedUnit = generateTransportedBAUnit(newParams, bayCapacity, skill, campaign); } if(transportedUnit == null) { transportedUnit = generateTransportedInfantryUnit(newParams, bayCapacity, skill, campaign); } <START> transportedUnit.setDeployRound(transport.getDeployRound()); <END> scenario.addTransportRelationship(transport.getExternalIdAsString(), transportedUnit.getExternalIdAsString()); transportedUnits.add(transportedUnit); } } return transportedUnits; }</code><technical_language>Is transportedUnit guaranteed non-null here</technical_language>

Target:
private static List<Entity> fillTransport(AtBScenario scenario, Entity transport, UnitGeneratorParameters params, int skill, Campaign campaign) { List<Entity> transportedUnits = new ArrayList<>(); if(scenario.getTransportLinkages().containsKey(transport.getExternalIdAsString())) { return transportedUnits; } for(Transporter bay : transport.getTransports()) { if(bay instanceof TroopSpace) { double bayCapacity = ((TroopSpace) bay).getUnused(); UnitGeneratorParameters newParams = params.clone(); newParams.clearMovementModes(); newParams.setWeightClass(AtBDynamicScenarioFactory.UNIT_WEIGHT_UNSPECIFIED); Entity transportedUnit = null; int baRoll = Compute.d6(2); if(baRoll >= infantryToBAUpgradeTNs[params.getQuality()]) { transportedUnit = generateTransportedBAUnit(newParams, bayCapacity, skill, campaign); } if(transportedUnit == null) { transportedUnit = generateTransportedInfantryUnit(newParams, bayCapacity, skill, campaign); } if(transportedUnit == null) { continue; } transportedUnit.setDeployRound(transport.getDeployRound()); scenario.addTransportRelationship(transport.getExternalIdAsString(), transportedUnit.getExternalIdAsString()); transportedUnits.add(transportedUnit); } } return transportedUnits; }
Source:
<code>private ColumnStatus getColumnStatus(String colName, Connection connection) throws SQLException { if (hasColumn(connection, colName)) { String sql = String.format("SELECT %s FROM %s FOR UPDATE", colName, prefixedTimestampTableName()); QueryRunner run = new QueryRunner(); return run.query(connection, sql, rs -> { if (rs.next()) { return ColumnStatus.columnStatusWithValue(rs.getLong(colName)); } return ColumnStatus.columnStatusWithoutValue(); }); } else { <START> return ColumnStatus.voidColumnStatus(); <END> } }</code><technical_language>nit: if returns, else needed</technical_language>

Target:
private Optional<ColumnStatus> getColumnStatus(String colName, Connection connection) throws SQLException { if (!PhysicalBoundStoreDatabaseUtils.hasColumn(connection, prefixedTimestampTableName(), colName)) { return Optional.empty(); } String sql = String.format("SELECT %s FROM %s FOR UPDATE", colName, prefixedTimestampTableName()); QueryRunner run = new QueryRunner(); return run.query(connection, sql, rs -> { if (rs.next()) { return ColumnStatus.columnStatusWithValue(rs.getLong(colName)); } return ColumnStatus.columnStatusWithoutValue(); }); }
Source:
<code>@Test public void unusedArgumentsIndexed() { try { CodeBlock.builder().add("$1L $2L", "a", "b", "c"); fail(); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessage("unused arguments are marked as zero: [1, 1, 0]"); } try { CodeBlock.builder().add("$1L $2L $1L", "a", "b", "c"); fail(); } catch (IllegalArgumentException expected) { <START> assertThat(expected).hasMessage("unused arguments are marked as zero: [2, 1, 0]"); <END> } try { CodeBlock.builder().add("$3L $1L $3L $1L $3L", "a", "b", "c"); fail(); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessage("unused arguments are marked as zero: [2, 0, 3]"); } }</code><technical_language>I this messaging is a confusing. say: 'arguments unused"</technical_language>

Target:
@Test public void unusedArgumentsIndexed() { try { CodeBlock.builder().add("$1L $2L", "a", "b", "c"); fail(); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessage("unused argument: $3"); } try { CodeBlock.builder().add("$1L $1L $1L", "a", "b", "c"); fail(); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessage("unused arguments: $2, $3"); } try { CodeBlock.builder().add("$3L $1L $3L $1L $3L", "a", "b", "c", "d"); fail(); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessage("unused arguments: $2, $4"); } }
Source:
<code>public List<Workflow> userWorkflows(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "User ID", required = true) @PathParam("userId") Long userId) { checkUser(user, userId); final User fetchedUser = this.userDAO.findById(userId); <START> List<Workflow> workflows = getWorkflows(fetchedUser); <END> EntryVersionHelper.stripContent(workflows, this.userDAO); return workflows; }</code><technical_language>I need check for a null fetched user; incorrect id</technical_language>

Target:
public List<Workflow> userWorkflows(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "User ID", required = true) @PathParam("userId") Long userId) { checkUser(user, userId); final User fetchedUser = this.userDAO.findById(userId); if (fetchedUser == null) { throw new CustomWebApplicationException("The given user does not exist.", HttpStatus.SC_NOT_FOUND); } List<Workflow> workflows = getWorkflows(fetchedUser); EntryVersionHelper.stripContent(workflows, this.userDAO); return workflows; }
Source:
<code>public BuildStepWithTimeout newInstance(StaplerRequest req, JSONObject formData) throws hudson.model.Descriptor.FormException { BuildStep buildstep = BuildTimeOutUtility.bindJSONWithDescriptor(req, formData, "buildStep", BuildStep.class); BuildTimeOutStrategy strategy = BuildTimeOutUtility.bindJSONWithDescriptor(req, formData, "strategy", BuildTimeOutStrategy.class); <START> if (!(strategy instanceof AbsoluteTimeOutStrategy || strategy instanceof DeadlineTimeOutStrategy)) { <END> throw new IllegalArgumentException("Unsupported strategy"); } List<BuildTimeOutOperation> operationList = newInstancesFromHeteroList(req, formData, "operationList", getOperations()); return new BuildStepWithTimeout(buildstep, strategy, operationList); }</code><technical_language>Add a new method TimeOutStrategy#isApplicableAsBuildStep filter that. a good idea list applicable classes in codes</technical_language>

Target:
public BuildStepWithTimeout newInstance(StaplerRequest req, JSONObject formData) throws hudson.model.Descriptor.FormException { BuildStep buildstep = BuildTimeOutUtility.bindJSONWithDescriptor(req, formData, "buildStep", BuildStep.class); BuildTimeOutStrategy strategy = BuildTimeOutUtility.bindJSONWithDescriptor(req, formData, "strategy", BuildTimeOutStrategy.class); List<BuildTimeOutOperation> operationList = newInstancesFromHeteroList(req, formData, "operationList", getOperations()); return new BuildStepWithTimeout(buildstep, strategy, operationList); }
Source:
<code>public boolean isInRange(int idx) { <START> return find(idx)>-1; <END> }</code><technical_language>This trivial unittest</technical_language>

Target:
public boolean isInRange(int idx) { return 0<=idx && idx<size; }
Source:
<code>private HttpRequestFactory httpRequestFactory(Subscription subscription) { int requestTimeout = subscription.getSerialSubscriptionPolicy().getRequestTimeout(); HttpClient client = subscription.isHttp2Enabled() ? http2Client.orElseGet(() -> { <START> logger.info("Http2 delivery is not enabled on this server. Falling back to http1."); <END> return httpClient; }) : httpClient; return new HttpRequestFactory(http2Client.get(), requestTimeout, metadataAppender, authorizationProviderFactory.create(subscription)); }</code><technical_language>This log subscription refers to. more I log for subscriptions, http/2 http/1.1 client is selected</technical_language>

Target:
private HttpRequestFactory httpRequestFactory(Subscription subscription) { int requestTimeout = subscription.getSerialSubscriptionPolicy().getRequestTimeout(); return new HttpRequestFactory(getHttpClient(subscription), requestTimeout, metadataAppender, authorizationProviderFactory.create(subscription)); }
Source:
<code>private void createList(List<Genome> genomes) { <START> list = new JList(genomes <END> .stream() .map(i -> i.getIdentifier()) .sorted() .toArray()); list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); list.setLayoutOrientation(JList.VERTICAL); list.setVisibleRowCount(-1); }</code><technical_language>Raw type JList</technical_language>

Target:
private void createList(List<Genome> genomes) { list = new JList<>(genomes .stream() .map(Genome::getIdentifier) .sorted() .toArray(String[]::new)); list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); list.setLayoutOrientation(JList.VERTICAL); list.setVisibleRowCount(-1); }
Source:
<code>private boolean sendSlackMessage(RepositoryBuild build, SlackAttachment attachment) { String email = build.getCommitInfo().get().getCurrent().getAuthor().getEmail(); if (!slackSession.isPresent()) { LOG.debug("No slack session present, not sending message to user {}", attachment.toString(), email); return true; } Optional<SlackUser> user = Optional.fromNullable(slackSession.get().findUserByEmail(email)); if (!user.isPresent()) { LOG.error("Could not find user for message about repo build {}", email, build.getId().get()); return false; } SlackMessageHandle<SlackMessageReply> result = slackSession.get().sendMessageToUser(user.get(), "", attachment); <START> if (!result.getReply().isOk()) { <END> LOG.warn("Failed to send slack message to user: message: error: {}", email, attachment.toString(), result.getReply().getErrorMessage()); return false; } return true; }</code><technical_language>if (result ==null || !result.getReply().isOk())</technical_language>

Target:
private boolean sendSlackMessage(RepositoryBuild build, SlackAttachment attachment) { String email = build.getCommitInfo().get().getCurrent().getAuthor().getEmail(); if (!slackSession.isPresent()) { LOG.debug("No slack session present, not sending message to user {}", attachment.toString(), email); return true; } Optional<SlackUser> user = Optional.fromNullable(slackSession.get().findUserByEmail(email)); if (!user.isPresent()) { LOG.error("Could not find user for message about repo build {}", email, build.getId().get()); return false; } SlackMessageHandle<SlackMessageReply> result = slackSession.get().sendMessageToUser(user.get(), "", attachment); if (result == null) { LOG.warn("Failed to send slack message to user: message: slack response was null", email, attachment.toString()); return false; } else if (!result.getReply().isOk()) { LOG.warn("Failed to send slack message to user: message: error: {}", email, attachment.toString(), result.getReply().getErrorMessage()); return false; } return true; }
Source:
<code>private CqlTranslator(NamespaceInfo namespaceInfo, VersionedIdentifier sourceInfo, ANTLRInputStream is, ModelManager modelManager, LibraryManager libraryManager, UcumService ucumService, CqlTranslatorOptions options) { this.sourceInfo = sourceInfo; this.namespaceInfo = namespaceInfo; this.modelManager = modelManager; this.libraryManager = libraryManager; this.ucumService = ucumService; this.errorLevel = options.getErrorLevel(); if (this.sourceInfo == null) { <START> sourceInfo = new VersionedIdentifier().withId("Anonymous").withSystem("text/cql"); <END> } if (this.namespaceInfo != null) { libraryManager.getNamespaceManager().ensureNamespaceRegistered(this.namespaceInfo); } if (libraryManager.getNamespaceManager().hasNamespaces() && libraryManager.getLibrarySourceLoader() instanceof NamespaceAware) { ((NamespaceAware)libraryManager.getLibrarySourceLoader()).setNamespaceManager(libraryManager.getNamespaceManager()); } if (libraryManager.getUcumService() == null) { libraryManager.setUcumService(this.ucumService); } translateToELM(is, options); }</code><technical_language>If translate a library input stream defined as: library ExpressionLibrary define Test: 2+2 define -syntax error! end a source info of "Anonymous" is counter-intuitive. Currently, code filename of CQL source if is available. generally a library identifier present (as SyntaxErrorWithNoLibrary shows). more user friendly attempt parse library name InputStream for cases possible</technical_language>

Target:
private CqlTranslator(NamespaceInfo namespaceInfo, VersionedIdentifier sourceInfo, ANTLRInputStream is, ModelManager modelManager, LibraryManager libraryManager, UcumService ucumService, CqlTranslatorOptions options) { this.sourceInfo = sourceInfo; this.namespaceInfo = namespaceInfo; this.modelManager = modelManager; this.libraryManager = libraryManager; this.ucumService = ucumService; this.errorLevel = options.getErrorLevel(); if (this.sourceInfo == null) { this.sourceInfo = new VersionedIdentifier().withId("Anonymous").withSystem("text/cql"); } if (this.namespaceInfo != null) { libraryManager.getNamespaceManager().ensureNamespaceRegistered(this.namespaceInfo); } if (libraryManager.getNamespaceManager().hasNamespaces() && libraryManager.getLibrarySourceLoader() instanceof NamespaceAware) { ((NamespaceAware)libraryManager.getLibrarySourceLoader()).setNamespaceManager(libraryManager.getNamespaceManager()); } if (libraryManager.getUcumService() == null) { libraryManager.setUcumService(this.ucumService); } translateToELM(is, options); }
Source:
<code>private String codePointToString(int codePoint) { <START> StringBuffer sb = new StringBuffer(); <END> sb.appendCodePoint(codePoint); return sb.toString(); }</code><technical_language>testing if StringBuffer is able produce correct input for StringPrep test ByteStringBuilder.appendUtf8Raw(int codePoint) method. @honza889 check is wrong appendUtf8Raw method in JDK8</technical_language>

Target:
private String codePointToString(int codePoint) { if (codePoint <= 0xFFFF) { return new String(new char[]{(char) codePoint}); } else { ByteStringBuilder b = new ByteStringBuilder(); b.appendUtf8Raw(codePoint); return new String(b.toArray(), StandardCharsets.UTF_8); } }
Source:
<code>public void whenGetThenOK() throws Exception { <START> getCursors().andExpect(status().is(HttpStatus.OK.value())); <END> }</code><technical_language>check this test. I mock cursorsCommitService. getSubscriptionCursors() check in response body get expected</technical_language>

Target:
public void whenGetThenOK() throws Exception { when(cursorsService.getSubscriptionCursors(SUBSCRIPTION_ID)).thenReturn(DUMMY_CURSORS); getCursors() .andExpect(status().is(HttpStatus.OK.value())) .andExpect(content().string("[{\"partition\":\"0\",\"offset\":\"10\"},{\"partition\":\"1\",\"offset\":\"10\"}]")); }
Source:
<code>public static void viewPostPreviewForResult(Activity activity, SiteModel site, PostModel post, boolean isPage) { if (post == null) return; Intent intent = new Intent(activity, PostPreviewActivity.class); <START> intent.putExtra(PostPreviewActivity.ARG_LOCAL_POST_ID, post.getId()); <END> intent.putExtra(WordPress.SITE, site); intent.putExtra(PostPreviewActivity.ARG_IS_PAGE, isPage); activity.startActivityForResult(intent, RequestCodes.PREVIEW_POST); }</code><technical_language>edit PostPreviewActivity a PostModel a parameter avoid unnecessary mLocalPostId mPostStore.getPostByLocalPostId(mLocalPostId); there</technical_language>

Target:
public static void viewPostPreviewForResult(Activity activity, SiteModel site, PostModel post, boolean isPage) { if (post == null) return; Intent intent = new Intent(activity, PostPreviewActivity.class); intent.putExtra(PostPreviewActivity.EXTRA_POST, post); intent.putExtra(WordPress.SITE, site); activity.startActivityForResult(intent, RequestCodes.PREVIEW_POST); }
Source:
<code>public List<BasicDocumentRevision> deleteDocument(final String id) throws ConflictException, DocumentException { Preconditions.checkNotNull(id, "id can not be null"); try { return queue.submitTransaction(new SQLQueueCallable<List<BasicDocumentRevision>>(){ @Override public List<BasicDocumentRevision> call(SQLDatabase db) throws Exception { ArrayList<BasicDocumentRevision> deleted = new ArrayList<BasicDocumentRevision>(); Cursor cursor = null; try { final String sql = "SELECT revs.revid FROM docs,revs " + "WHERE revs.doc_id = docs.doc_id " + "AND docs.docid = ? " + "AND deleted = 0 AND revs.sequence NOT IN " + "(SELECT DISTINCT parent FROM revs WHERE parent NOT NULL) "; cursor = db.rawQuery(sql, new String[]{id}); while (cursor.moveToNext()) { String revId = cursor.getString(0); deleted.add(deleteDocumentInQueue(db, id, revId)); } return deleted; } catch (SQLException sqe) { throw new DocumentException("SQLException in deleteDocument, not deleting revisions", sqe); } finally { DatabaseUtils.closeCursorQuietly(cursor); } } }).get(); } catch (InterruptedException e) { logger.log(Level.SEVERE,"Failed to delete document",e); } catch (ExecutionException e) { <START> throw new DocumentException("Failed to delete document",e); <END> } return null; }</code><technical_language>Worth appending e's message generic messages place? I guess stack trace e's message</technical_language>

Target:
public List<BasicDocumentRevision> deleteDocument(final String id) throws ConflictException, DocumentException { Preconditions.checkNotNull(id, "id can not be null"); try { return queue.submitTransaction(new SQLQueueCallable<List<BasicDocumentRevision>>(){ @Override public List<BasicDocumentRevision> call(SQLDatabase db) throws Exception { ArrayList<BasicDocumentRevision> deleted = new ArrayList<BasicDocumentRevision>(); Cursor cursor = null; try { final String sql = "SELECT revs.revid FROM docs,revs " + "WHERE revs.doc_id = docs.doc_id " + "AND docs.docid = ? " + "AND deleted = 0 AND revs.sequence NOT IN " + "(SELECT DISTINCT parent FROM revs WHERE parent NOT NULL) "; cursor = db.rawQuery(sql, new String[]{id}); while (cursor.moveToNext()) { String revId = cursor.getString(0); deleted.add(deleteDocumentInQueue(db, id, revId)); } return deleted; } catch (SQLException sqe) { throw new DatastoreException("SQLException in deleteDocument, not deleting revisions", sqe); } finally { DatabaseUtils.closeCursorQuietly(cursor); } } }).get(); } catch (InterruptedException e) { logger.log(Level.SEVERE,"Failed to delete document",e); } catch (ExecutionException e) { throw new DocumentException("Failed to delete document",e); } return null; }
Source:
<code>public void setCleanup(List<Runnable> cleanup) { <START> this.cleanup = cleanup; <END> }</code><technical_language>If cleanup list is non-empty, copy elements new cleanup list, simply discard leak</technical_language>

Target:
public void setCleanup(List<Runnable> cleanup) { if (!this.cleanup.isEmpty()) { cleanup.addAll(this.cleanup); } this.cleanup = cleanup; }
Source:
<code>private DeploymentInfoResult(String command, String serverGroup, String output) { this.command = command; this.serverGroup = serverGroup; this.originalOutput = output; if (output != null && !output.isEmpty()) { log.info("Read output:\n" + output); <START> this.rows = Arrays.asList(output.split("\n")); <END> } else { log.info("Read output: " + OUTPUT_EMPTY_MARK); this.rows = new ArrayList<>(); this.rows.add(OUTPUT_EMPTY_MARK); } }</code><technical_language>end of line is multi platform: System.getProperty("line.separator")</technical_language>

Target:
private DeploymentInfoResult(String command, String serverGroup, String output) { this.command = command; this.serverGroup = serverGroup; originalOutput = output; if (originalOutput != null && !originalOutput.isEmpty()) { log.trace("Read output:\n" + output); rows = Arrays.asList(originalOutput.split(LINE_SEPARATOR)); } else { log.trace("Read output: <EMPTY>"); rows = new ArrayList<>(); } }
Source:
<code>public NewApplicationViewImpl(org.eclipse.che.ide.Resources coreResources, OpenshiftResources resources, CellTableResources cellTableResources, OpenshiftLocalizationConstant locale, CoreLocalizationConstant constants) { this.resources = resources; this.locale = locale; ensureDebugId("deployCheProject"); setTitle(locale.deployProjectWindowTitle()); getWidget().getElement().getStyle().setPadding(0, Style.Unit.PX); environmentVariablesProvider = new ListDataProvider<Pair<String, String>>(); environmentVariables = createCellTable(cellTableResources, environmentVariablesProvider); environmentLabelsProvider = new ListDataProvider<Pair<String, String>>(); environmentLabels = createCellTable(cellTableResources, environmentLabelsProvider); setWidget(uiBinder.createAndBindUi(this)); projectsList = createProjectList(coreResources); osProjectListPanel.add(projectsList); deployBtn = createPrimaryButton(locale.deployProjectWindowDeploy(), <START> "deployCodenvyProject-deploy-button", new ClickHandler() { <END> @Override public void onClick(ClickEvent event) { delegate.onDeployClicked(); } }); addButtonToFooter(deployBtn); cancelBtn = createButton(constants.cancel(), "deployCodenvyProject-cancel-button", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onCancelClicked(); } }); addButtonToFooter(cancelBtn); createNewProject.setValue(true); projectName.setEnabled(true); displayName.setEnabled(true); description.setEnabled(true); }</code><technical_language>Replace Codenvy Che</technical_language>

Target:
public NewApplicationViewImpl(org.eclipse.che.ide.Resources coreResources, OpenshiftResources resources, CellTableResources cellTableResources, OpenshiftLocalizationConstant locale, CoreLocalizationConstant constants) { this.resources = resources; this.locale = locale; ensureDebugId("deployCheProject"); setTitle(locale.deployProjectWindowTitle()); getWidget().getElement().getStyle().setPadding(0, Style.Unit.PX); environmentVariablesProvider = new ListDataProvider<Pair<String, String>>(); environmentVariables = createCellTable(cellTableResources, environmentVariablesProvider); environmentLabelsProvider = new ListDataProvider<Pair<String, String>>(); environmentLabels = createCellTable(cellTableResources, environmentLabelsProvider); setWidget(uiBinder.createAndBindUi(this)); projectsList = createProjectList(coreResources); osProjectListPanel.add(projectsList); deployBtn = createPrimaryButton(locale.deployProjectWindowDeploy(), "deployCheProject-deploy-button", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onDeployClicked(); } }); addButtonToFooter(deployBtn); cancelBtn = createButton(constants.cancel(), "deployCheProject-cancel-button", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onCancelClicked(); } }); addButtonToFooter(cancelBtn); createNewProject.setValue(true); projectName.setEnabled(true); displayName.setEnabled(true); description.setEnabled(true); }
Source:
<code>public void close() throws IOException { long totalTimeMillis = currentTimeMillis() - startTime; DataStatistics state = getState( DataStatistics.class ); <START> String additionalInformation = Objects.toString( state, "Data diagnostics is not available." ); <END> executionMonitor.done( totalTimeMillis, format( "%n%s%nPeak memory usage: %s", additionalInformation, bytes( peakMemoryUsage ) ) ); log.info( "Import completed successfully, took " + duration( totalTimeMillis ) + ". " + additionalInformation ); closeAll( nodeRelationshipCache, nodeLabelsCache, idMapper, inputCache ); }</code><technical_language>term diagnostics more of a medical/repair/investigation meaning, it. Data statistics imho</technical_language>

Target:
public void close() throws IOException { long totalTimeMillis = currentTimeMillis() - startTime; DataStatistics state = getState( DataStatistics.class ); String additionalInformation = Objects.toString( state, "Data statistics is not available." ); executionMonitor.done( totalTimeMillis, format( "%n%s%nPeak memory usage: %s", additionalInformation, bytes( peakMemoryUsage ) ) ); log.info( "Import completed successfully, took " + duration( totalTimeMillis ) + ". " + additionalInformation ); closeAll( nodeRelationshipCache, nodeLabelsCache, idMapper, inputCache ); }
Source:
<code>protected void executeVdsBrokerCommand() { httpTask = getBroker().setupNetworks(generateNetworks(), generateBonds(), generateOptions(), <START> true); <END> }</code><technical_language>Do want reset policy here</technical_language>

Target:
protected void executeVdsBrokerCommand() { httpTask = getBroker().setupNetworks(generateNetworks(), generateBonds(), generateOptions(), getParameters().isManagementNetworkChanged()); }
Source:
<code>public BasicDatastore(String dir, String name) throws SQLException, IOException { Preconditions.checkNotNull(dir); Preconditions.checkNotNull(name); this.datastoreDir = dir; this.datastoreName = name; this.extensionsDir = FilenameUtils.concat(this.datastoreDir, "extensions"); final String dbFilename = FilenameUtils.concat(this.datastoreDir, DB_FILE_NAME); queue = new SQLDatabaseQueue(dbFilename); queue.updateSchema(DatastoreConstants.getSchemaVersion3(), 3); queue.updateSchema(DatastoreConstants.getSchemaVersion4(), 4); queue.updateSchema(DatastoreConstants.getSchemaVersion5(), 5); <START> queue.updateSchema(DatastoreConstants.getSchemaVersion6(), 6); <END> dbOpen = true; this.eventBus = new EventBus(); this.attachmentManager = new AttachmentManager(this); }</code><technical_language>Remove this schema upgrades</technical_language>

Target:
public BasicDatastore(String dir, String name) throws SQLException, IOException, DatastoreException { Preconditions.checkNotNull(dir); Preconditions.checkNotNull(name); this.datastoreDir = dir; this.datastoreName = name; this.extensionsDir = FilenameUtils.concat(this.datastoreDir, "extensions"); final String dbFilename = FilenameUtils.concat(this.datastoreDir, DB_FILE_NAME); queue = new SQLDatabaseQueue(dbFilename); int dbVersion = queue.getVersion(); if(dbVersion >= 100){ throw new DatastoreException(String.format("Database version is higher than the version supported " + "by this library, current version %d , highest supported version %d",dbVersion, 99)); } queue.updateSchema(DatastoreConstants.getSchemaVersion3(), 3); queue.updateSchema(DatastoreConstants.getSchemaVersion4(), 4); queue.updateSchema(DatastoreConstants.getSchemaVersion5(), 5); queue.updateSchema(DatastoreConstants.getSchemaVersion6(), 6); dbOpen = true; this.eventBus = new EventBus(); this.attachmentManager = new AttachmentManager(this); }
Source:
<code>private GBPTree.Monitor treeMonitor( ) { return new GBPTree.Monitor.Adaptor() { @Override public void cleanupFinished( long numberOfPagesVisited, long numberOfCleanedCrashPointers, long durationMillis ) { <START> monitor.recoveryCompleted( indexId, descriptor, partName(), map( <END> "Number of pages visited", numberOfPagesVisited, "Number of cleaned crashed pointers", numberOfCleanedCrashPointers, "Time spent", duration( durationMillis ) ) ); } }; }</code><technical_language>partName() "fusion-aware" me. pass absolute file name instead? file convey more information need add partName() method all, implemented populators too, unexpectedly</technical_language>

Target:
private GBPTree.Monitor treeMonitor( ) { return new GBPTree.Monitor.Adaptor() { @Override public void cleanupFinished( long numberOfPagesVisited, long numberOfCleanedCrashPointers, long durationMillis ) { monitor.recoveryCompleted( descriptor, storeFile.getAbsolutePath(), map( "Number of pages visited", numberOfPagesVisited, "Number of cleaned crashed pointers", numberOfCleanedCrashPointers, "Time spent", duration( durationMillis ) ) ); } }; }
Source:
<code>protected void configure() { Collection<Plugin> plugins = pluginLoader.getPlugins(); <START> for (Plugin p : plugins) { <END> Class<PluginCommandModule> c = (Class<PluginCommandModule>) p.moduleClass; try { PluginCommandModule module = c.newInstance(); module.initSshModule(p.name); CommandName cmd = Commands.named(p.name); command(cmd).toProvider(new DispatchCommandProvider(cmd)); install(module); } catch (InstantiationException e) { log.warn("Initialization of plugin module '" + p.name + "' failed"); } catch (IllegalAccessException e) { log.warn("Initialization of plugin module '" + p.name + "' failed"); } } }</code><technical_language>@SuppressWarnings("unchecked") for type safety unchecked cast</technical_language>

Target:
protected void configure() { Collection<Plugin> plugins = pluginLoader.getPlugins(); for (Plugin p : plugins) { if (PluginCommandModule.class.isAssignableFrom(p.moduleClass)) { @SuppressWarnings("unchecked") Class<PluginCommandModule> c = (Class<PluginCommandModule>) p.moduleClass; try { PluginCommandModule module = c.newInstance(); module.initSshModule(p.name); install(module); } catch (InstantiationException e) { log.warn("Initialization of plugin module '" + p.name + "' failed"); } catch (IllegalAccessException e) { log.warn("Initialization of plugin module '" + p.name + "' failed"); } } } }
Source:
<code>public void setUserProperties(final JSONObject userProperties) { if (userProperties == null || userProperties.length() == 0) { return; } runOnLogThread(new Runnable() { @Override public void run() { <START> JSONObject copy = cloneJSONObject(userProperties); <END> if (copy == null) { return; } Identify identify = new Identify(); Iterator<?> keys = copy.keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { identify.set(key, copy.get(key)); } catch (JSONException e) { Log.e(TAG, e.toString()); } } identify(identify); } }); }</code><technical_language>motivation switching deep copy shallow copy</technical_language>

Target:
public void setUserProperties(final JSONObject userProperties) { if (userProperties == null || userProperties.length() == 0) { return; } runOnLogThread(new Runnable() { @Override public void run() { JSONObject copy; try { copy = new JSONObject(userProperties.toString()); } catch (JSONException e) { Log.e(TAG, e.toString()); return; } Identify identify = new Identify(); Iterator<?> keys = copy.keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { identify.set(key, copy.get(key)); } catch (JSONException e) { Log.e(TAG, e.toString()); } } identify(identify); } }); }
Source:
<code>static void truncateTable(String strTable) throws SQLException { LOG.debug("Truncating '" + strTable + "' ..."); try { <START> System.out.println("truncate " + strTable); <END> conn.createStatement().execute("truncate " + strTable); conn.commit(); } catch (SQLException se) { LOG.debug(se.getMessage()); conn.rollback(); } }</code><technical_language>Remove System.out calls</technical_language>

Target:
static void truncateTable(String strTable) throws SQLException { LOG.debug("Truncating '" + strTable + "' ..."); try { conn.createStatement().execute("DELETE FROM " + strTable); conn.commit(); } catch (SQLException se) { LOG.debug(se.getMessage()); conn.rollback(); } }
Source:
<code>public FixNotMavenizedArtifactInfo() { String pomTemplate = null; try { <START> pomTemplate = new BufferedReader(new InputStreamReader(M2ServletContextListener.class.getResourceAsStream("template.pom"))) <END> .lines().collect(Collectors.joining("\n")); final InputStream isNotMavenizedArtifacts = M2ServletContextListener.class.getResourceAsStream("/not-mavenized-artifacts.txt"); if (isNotMavenizedArtifacts != null) { notMavenizedArtifacts.load(isNotMavenizedArtifacts); } } catch (IOException e) { logger.error(e.getMessage(), e); } this.pomTemplate = pomTemplate; }</code><technical_language>reason split immediately join newline? load artifact a string? in this case (since fixed template is small) simplify code include template a private static final String field this class directly</technical_language>

Target:
public FixNotMavenizedArtifactInfo() { final Properties notMavenizedArtifactsProps = new Properties(); try { final InputStream isNotMavenizedArtifacts = M2ServletContextListener.class.getResourceAsStream("/not-mavenized-artifacts.properties"); if (isNotMavenizedArtifacts != null) { notMavenizedArtifactsProps.load(isNotMavenizedArtifacts); } for (Map.Entry<Object, Object> entry : notMavenizedArtifactsProps.entrySet()) { notMavenizedArtifacts.put(entry.getKey().toString() + "-", entry.getValue().toString().split(":")); } } catch (IOException e) { logger.error(e.getMessage(), e); } }
Source:
<code>public void removeDatasourceConfirm() { if ( messageBundle != null ) { XulLabel removeDatasourceConfirmationDialogLabel = (XulLabel) removeDatasourceConfirmationDialog.getElementById( "removeDatasourceConfirmationDialogLabel" ); <START> LogicalModelSummary logicalModelSummary = getDialogResult(); <END> removeDatasourceConfirmationDialogLabel.setValue( messageBundle.getString( REMOVE_DS_MSG_ID, logicalModelSummary.getModelName() ) ); } removeDatasourceConfirmationDialog.show(); }</code><technical_language>This method happily returns null time time. Kaboom? yeah, I know, binding active if is selection. time hurt add a explicit if (datasourceSelectionDialogModel.getSelectedIndex() == -1) return; method protect it</technical_language>

Target:
public void removeDatasourceConfirm() { if ( messageBundle != null ) { XulLabel removeDatasourceConfirmationDialogLabel = (XulLabel) removeDatasourceConfirmationDialog.getElementById( "removeDatasourceConfirmationDialogLabel" ); LogicalModelSummary logicalModelSummary = getDialogResult(); if ( removeDatasourceConfirmationDialogLabel != null && logicalModelSummary != null ) { removeDatasourceConfirmationDialogLabel.setValue( messageBundle.getString( REMOVE_DS_MSG_ID, logicalModelSummary.getModelName() ) ); } } removeDatasourceConfirmationDialog.show(); }