auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Object transform(Message<?> message) { try { HttpHeaders headers = new HttpHeaders(); HttpMethod method = HttpMethod.valueOf(properties.getHttpMethod()); URI uri = new URI(properties.getUrl()); HttpEntity<?> requestEntity = new RequestEntity<Object>(properties.getBody(), headers, method, uri); ResponseEntity<String> httpResponse = restTemplate.exchange( properties.getUrl(), HttpMethod.valueOf(properties.getHttpMethod()), requestEntity, <START> String.class); <END> return httpResponse.getBody(); } catch (Exception e) { LOG.warn("Error in HTTP request", e); return null; } }</code><technical_language>expectedReturnType a configurable property</technical_language>

Target:
public Object transform(Message<?> message) { try { HttpHeaders headers = new HttpHeaders(); if(properties.getHeaders() != null) { Map<String,String> headersMap = properties.getHeaders().getValue(Map.class); for(Entry<String,String> header : headersMap.entrySet()) { headers.add(header.getKey(), header.getValue()); } } Class<?> clazz = String.class; if(properties.getExpectedReturnType() != null) { clazz = properties.getExpectedReturnType().getValue(Class.class); } HttpMethod method = HttpMethod.valueOf(properties.getHttpMethod()); String url = properties.getUrl().getValue(String.class); Object body = properties.getBody() == null ? null : properties.getBody().getValue(message); URI uri = new URI(url); HttpEntity<?> requestEntity = new RequestEntity<Object>(body, headers, method, uri); ResponseEntity<?> httpResponse = restTemplate.exchange( uri, HttpMethod.valueOf(properties.getHttpMethod()), requestEntity, clazz); return httpResponse.getBody(); } catch (Exception e) { LOG.warn("Error in HTTP request", e); return null; } }
Source:
<code>public void replay() { <START> clickElement(String.format(REPLAY_BUTTON_SELECTOR_FORMAT, slot)); <END> playing = true; }</code><technical_language>consistent I add if check if video is playing</technical_language>

Target:
public void replay() { clickElement(String.format(REPLAY_BUTTON_SELECTOR_FORMAT, slot)); muted = false; playing = true; }
Source:
<code><START> private Maybe<User> getUserByEmail(String userEmail) throws NoResultException { <END> User user; try { user = entityManagerProvider.get().createQuery( "SELECT u FROM User u " + "WHERE u.email = :email", User.class) .setParameter("email", userEmail) .getSingleResult(); return Maybe.of(user); } catch (NoResultException e) { return Maybe.notFound(); } }</code><technical_language>java.util.Optional instead of Maybe. type for results *one* of states: visible, forbidden, non-existant,or deleted. user is present not</technical_language>

Target:
private Optional<User> getUserByEmail(String userEmail) { User user; try { user = entityManagerProvider.get().createQuery( "SELECT u FROM User u " + "WHERE u.email = :email", User.class) .setParameter("email", userEmail) .getSingleResult(); return Optional.of(user); } catch (NoResultException e) { return Optional.empty(); } }
Source:
<code>public Profile(final Integer id, final String node, final List<ProfileEntry> profileEntries) { this.id = id; this.node = node; <START> this.profileEntries = profileEntries; <END> }</code><technical_language>For GetDataSystemIdentifier more is done class effectively immutable in Profile some other object classes in this package</technical_language>

Target:
public Profile(final Integer id, final String node, final List<ProfileEntry> profileEntries) { this.id = id; this.node = node; this.profileEntries = new ArrayList<>(profileEntries); }
Source:
<code>private WritableMemory getMemory(final ByteBuffer buffer) { WritableMemory mem = memCache.get(buffer); <START> if (mem == null) { <END> mem = WritableMemory.wrap(buffer); memCache.put(buffer, mem); } return mem; }</code><technical_language>memCache.computeIfAbsent()</technical_language>

Target:
private WritableMemory getMemory(final ByteBuffer buffer) { return memCache.computeIfAbsent(buffer, buf -> WritableMemory.wrap(buf)); }
Source:
<code><START> public PayloadBlobBuilder contentType(MediaType contentType) { <END> String contentTypeString = null; if (contentType != null) { contentTypeString = contentType.toString(); } return contentType(contentTypeString); }</code><technical_language>allow a nullable input here? Users wanting a null content type call String variant, no</technical_language>

Target:
public PayloadBlobBuilder contentType(MediaType contentType) { return contentType(checkNotNull(contentType, "contentType").toString()); }
Source:
<code>private void writeObject(ObjectOutputStream out) throws IOException { writeNotNull(out, commit); writeNotNull(out, into); <START> switch (submitType) { case FAST_FORWARD_ONLY: out.writeChar('F'); <END> break; case MERGE_IF_NECESSARY: out.writeChar('M'); break; case REBASE_IF_NECESSARY: out.writeChar('R'); break; case MERGE_ALWAYS: out.writeChar('A'); break; case CHERRY_PICK: out.writeChar('C'); break; default: throw new IOException("Invalid submit type: " + submitType); } writeString(out, mergeStrategy); }</code><technical_language>gerrit-server access Guava, BiMap. A static BiMap cleaner here</technical_language>

Target:
private void writeObject(ObjectOutputStream out) throws IOException { writeNotNull(out, commit); writeNotNull(out, into); Character c = SUBMIT_TYPES.get(submitType); if (c == null) { throw new IOException("Invalid submit type: " + submitType); } out.writeChar(c); writeString(out, mergeStrategy); }
Source:
<code>public com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.ActualMeterReadsResponse getActualMeterReadsResponse( @OrganisationIdentification final String organisationIdentification, @RequestPayload final ActualMeterReadsAsyncRequest request) throws OsgpException { LOGGER.debug("Incoming ActualMeterReadsAsyncRequest for meter: {}", request.getDeviceIdentification()); try { final MeterResponseData meterResponseData = this.meterResponseDataRepository .findSingleResultByCorrelationUid(request.getCorrelationUid()); if (meterResponseData == null) { throw new FunctionalException(FunctionalExceptionType.UNKNOWN_CORRELATION_UID, ComponentType.WS_SMART_METERING); } if (meterResponseData.getMessageData() instanceof ActualMeterReads) { final com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.ActualMeterReadsResponse response = this.monitoringMapper .map(meterResponseData.getMessageData(), com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.ActualMeterReadsResponse.class); this.meterResponseDataRepository.delete(meterResponseData); return response; } else { LOGGER.warn("Incorrect type of response data: for correlation UID: {}", meterResponseData.getClass() .getName(), request.getCorrelationUid()); } } catch (final Exception e) { this.handleRetrieveException(e, request, organisationIdentification); } <START> return null; <END> }</code><technical_language>I returning null is do here. If good response given, a suitable exception thrown</technical_language>

Target:
public com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.ActualMeterReadsResponse getActualMeterReadsResponse( @OrganisationIdentification final String organisationIdentification, @RequestPayload final ActualMeterReadsAsyncRequest request) throws OsgpException { LOGGER.debug("Incoming ActualMeterReadsAsyncRequest for meter: {}", request.getDeviceIdentification()); try { final MeterResponseData meterResponseData = this.meterResponseDataRepository .findSingleResultByCorrelationUid(request.getCorrelationUid()); if (meterResponseData == null) { throw new FunctionalException(FunctionalExceptionType.UNKNOWN_CORRELATION_UID, ComponentType.WS_SMART_METERING); } if (meterResponseData.getMessageData() instanceof MeterReads) { final com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.ActualMeterReadsResponse response = this.monitoringMapper .map(meterResponseData.getMessageData(), com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.ActualMeterReadsResponse.class); this.meterResponseDataRepository.delete(meterResponseData); return response; } else { LOGGER.warn("Incorrect type of response data: for correlation UID: {}", meterResponseData.getClass() .getName(), request.getCorrelationUid()); } } catch (final Exception e) { this.handleRetrieveException(e, request, organisationIdentification); } return null; }
Source:
<code>public boolean onEvaluateInputViewShown() { Configuration config = getResources().getConfiguration(); <START> return isInputViewShown() || config.keyboard == Configuration.KEYBOARD_NOKEYS <END> || config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES; }</code><technical_language>This risky. availability of hard keyboard changed display rotates (e.g. Droid), in case, software keyboard hidden. fix implemented in InputMethodManagerSerivce.java</technical_language>

Target:
public boolean onEvaluateInputViewShown() { Configuration config = getResources().getConfiguration(); return config.keyboard == Configuration.KEYBOARD_NOKEYS || config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES; }
Source:
<code>public TermCons(String psort, List<Term> contents, Production production) { super(psort); <START> cons = ""; <END> this.contents = contents; this.production = production; }</code><technical_language>nan</technical_language>

Target:
public TermCons(String psort, List<Term> contents, Production production) { super(psort); cons = null; this.contents = contents; this.production = production; }
Source:
<code>public int compareTo(PartitionChunk<T> chunk) { if (chunk instanceof IntegerPartitionChunk) { IntegerPartitionChunk<T> intChunk = (IntegerPartitionChunk<T>) chunk; int retVal = comparator.compare(start, intChunk.start); if (retVal == 0) { retVal = comparator.compare(end, intChunk.end); } return retVal; <START> } else { <END> throw new IllegalArgumentException("Cannot compare against something that is not an IntegerPartitionChunk."); } }</code><technical_language>else</technical_language>

Target:
public int compareTo(PartitionChunk<T> chunk) { if (chunk instanceof IntegerPartitionChunk) { IntegerPartitionChunk<T> intChunk = (IntegerPartitionChunk<T>) chunk; return comparator.compare(chunkNumber, intChunk.chunkNumber); } else { throw new IllegalArgumentException("Cannot compare against something that is not an IntegerPartitionChunk."); } }
Source:
<code>public Builder fetchedValue(FetchedValue fetchedValue) { this.fetchedValue = fetchedValue; <START> errors(fetchedValue.getErrors()); <END> return this; }</code><technical_language>this is great I think, kinda violates expectation for a builder: if I set a new fetchValue ok. error add in constructor in build method imho</technical_language>

Target:
public Builder fetchedValue(FetchedValue fetchedValue) { this.fetchedValue = fetchedValue; return this; }
Source:
<code>private ListenableFuture<Response> authenticateAndRetry(final HeliosRequest request, final Response response) { final ListenableFuture<Response> f = Futures.transform( authProvider.renewAuthorization(response.header(HttpHeaders.WWW_AUTHENTICATE)), new AsyncFunction<String, Response>() { @Override public ListenableFuture<Response> apply(final String authHeader) throws Exception { <START> return delegate.request( <END> request.toBuilder().header(HttpHeaders.AUTHORIZATION, authHeader).build()); } }); return Futures.withFallback(f, new FutureFallback<Response>() { @Override public ListenableFuture<Response> create(final Throwable t) throws Exception { return immediateFuture(response); } }); }</code><technical_language>I if "new" token is previous one, return error / a new request, assuming server continue is valid</technical_language>

Target:
private ListenableFuture<Response> authenticateAndRetry(final HeliosRequest request, final Response response) { final ListenableFuture<Response> f = Futures.transform( authProvider.renewAuthorizationHeader(response.header(HttpHeaders.WWW_AUTHENTICATE)), new AsyncFunction<String, Response>() { @Override public ListenableFuture<Response> apply(final String authHeader) throws Exception { return delegate.request( request.toBuilder().header(HttpHeaders.AUTHORIZATION, authHeader).build()); } }); return Futures.withFallback(f, new FutureFallback<Response>() { @Override public ListenableFuture<Response> create(final Throwable t) throws Exception { return immediateFuture(response); } }); }
Source:
<code>private void updateVersion(Optional<LockWatchVersion> maybeNewVersion) { currentVersion = maybeNewVersion.map(newVersion -> currentVersion .filter(current -> current.id().equals(newVersion.id()) && current.version() > newVersion.version()) <START> .orElse(newVersion)); <END> }</code><technical_language>discussion below: imperative statements here? I find this difficult parse (I read filter a top-level rejects versions unfriendly, case)</technical_language>

Target:
private void updateVersion(Optional<LockWatchVersion> maybeNewVersion) { currentVersion = maybeNewVersion.map(newVersion -> currentVersion .map(current -> { if (current.id().equals(newVersion.id()) && current.version() > newVersion.version()) { return current; } else { return newVersion; } }) .orElse(newVersion)); }
Source:
<code>public Harness(String note) { this.testName = note; <START> System.out.println(testName); <END> }</code><technical_language>Leftover debugging</technical_language>

Target:
public Harness(String note) { this.testName = note; }
Source:
<code>private void parseHostName(NodeList listOfPeers) { for (int i=0; i < listOfPeers.getLength(); i++) { Node firstPeer = listOfPeers.item(i); if(firstPeer.getNodeType() == Node.ELEMENT_NODE){ Element firstHostElement = (Element)firstPeer; int state = getIntValue(firstHostElement, STATE); <START> if (state == 3) { <END> hostNamesOrIp.add(getTextValue(firstHostElement, HOST_NAME)); } } } }</code><technical_language>Please introduce a constant for 3 (PEER_IN_CLUSTER)</technical_language>

Target:
private void parseHostName(NodeList listOfPeers) { for (int i=0; i < listOfPeers.getLength(); i++) { Node firstPeer = listOfPeers.item(i); if(firstPeer.getNodeType() == Node.ELEMENT_NODE){ Element firstHostElement = (Element)firstPeer; int state = getIntValue(firstHostElement, STATE); if (state == PEER_IN_CLUSTER) { hostNamesOrIp.add(getTextValue(firstHostElement, HOST_NAME)); } } } }
Source:
<code>public boolean getBoolean(int columnIndex) throws SQLException { connection.getLogger().log(Level.FINEST, " getBoolean columnIndex: {0}", columnIndex); checkResultSet(columnIndex); if (wasNullFlag) { return false; } int col = columnIndex - 1; if (Oid.BOOL == fields[col].getOID()) { final byte[] v = this_row[col]; return (1 == v.length) && (116 == v[0]); } if (isBinary(columnIndex)) { return BooleanTypeUtil.castToBoolean(readDoubleValue(this_row[col], fields[col].getOID(), "boolean"), <START> Oid.toString(fields[col].getOID())); <END> } return BooleanTypeUtil.castToBoolean(getString(columnIndex), Oid.toString(fields[col].getOID())); }</code><technical_language>implementation of Oid.toString(int) super fast. type is necessary here? enough: cast boolean: "2"</technical_language>

Target:
public boolean getBoolean(int columnIndex) throws SQLException { connection.getLogger().log(Level.FINEST, " getBoolean columnIndex: {0}", columnIndex); checkResultSet(columnIndex); if (wasNullFlag) { return false; } int col = columnIndex - 1; if (Oid.BOOL == fields[col].getOID()) { final byte[] v = this_row[col]; return (1 == v.length) && (116 == v[0]); } if (isBinary(columnIndex)) { return BooleanTypeUtil.castToBoolean(readDoubleValue(this_row[col], fields[col].getOID(), "boolean")); } return BooleanTypeUtil.castToBoolean(getString(columnIndex)); }
Source:
<code>public final JSONArrayBuilder add(JsArrayString value) { if (value == null) return appendNull(); JSONArray array = new JSONArray(); <START> if (value != null) <END> for (int i = 0, n = value.length(); i < n; i++) array.set(i, fromString(value.get(i))); append(array); return this; }</code><technical_language>Is this test superfluous? (looks bailed if null)</technical_language>

Target:
public final JSONArrayBuilder add(JsArrayString value) { if (value == null) return appendNull(); JSONArray array = new JSONArray(); for (int i = 0, n = value.length(); i < n; i++) array.set(i, fromString(value.get(i))); append(array); return this; }
Source:
<code>private CompilationUnitTree parse(String source) { List<File> classpath = Lists.newArrayList(new File("target/test-classes"), new File("target/classes")); <START> return JParser.parse("1.8", "test", source, classpath); <END> }</code><technical_language>Please extract string static constant variables</technical_language>

Target:
private CompilationUnitTree parse(String source) { List<File> classpath = Lists.newArrayList(new File(TEST_CLASSES_FILEPATH), new File(CLASSES_FILEPATH)); return JParser.parse(JAVA_VERSION, UNIT_NAME, source, classpath); }
Source:
<code>private void checkCollectionAssignments(List<IdentifierTree> usages) { for (IdentifierTree usage : usages) { Tree parentTree = usage.parent(); <START> if (parentTree instanceof AssignmentExpressionTree) { <END> AssignmentExpressionTree assignment = (AssignmentExpressionTree) parentTree; ExpressionTree expression = assignment.expression(); if (usage.equals(assignment.variable()) && !expression.is(Tree.Kind.NULL_LITERAL) && implementsCollectionButNotSerializable(expression.symbolType())) { reportIssue(usage); } } } }</code><technical_language>.. I understand this of kinds</technical_language>

Target:
private void checkCollectionAssignments(List<IdentifierTree> usages) { for (IdentifierTree usage : usages) { Tree parentTree = usage.parent(); if (parentTree.is(Tree.Kind.ASSIGNMENT)) { AssignmentExpressionTree assignment = (AssignmentExpressionTree) parentTree; ExpressionTree expression = assignment.expression(); if (usage.equals(assignment.variable()) && !expression.is(Tree.Kind.NULL_LITERAL) && isUnserializableCollection(expression.symbolType())) { reportIssue(usage); } } } }
Source:
<code>private static String buildFullyQualifiedMetricName(String shortName) { <START> return "com.palantir.atlasdb.monitoring.TimestampTracker." + shortName; <END> }</code><technical_language>nit: this is sensitive TimestampTracker moved another package</technical_language>

Target:
private static String buildFullyQualifiedMetricName(String shortName) { return MetricRegistry.name(TimestampTracker.class, shortName); }
Source:
<code>public Date convertDate(Date inDate) { if (inDate == null) { return null; } DateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); String formattedDate = format.format(inDate); try { return format.parse(formattedDate); } catch (Exception ex) { log.error("Error while converting the date to simple date format"); <START> return null; <END> } }</code><technical_language>throw some exception date is convertable? Lets imagine for example endDate String is corrupted (with a single character typo for instance). user intention a job end time. Returning null, I suppose, lift 'stop' condition. I wondering throw some sort of custom 'validation/parsing' exception explicit is error</technical_language>

Target:
public Date convertDate(Date inDate) throws ParseException { if (inDate == null) { return null; } DateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); String formattedDate = format.format(inDate); return format.parse(formattedDate); }
Source:
<code>protected void emitContent(String content) throws IOException { ConfluenceDocumentBuilder.this.emitContent(content); if <START> (content.length() > 1) { <END> ConfluenceDocumentBuilder.this.emitContent(" | "); } if (attributes.getHref() != null) { ConfluenceDocumentBuilder.this.emitContent(attributes.getHref()); } if (!Strings.isNullOrEmpty(attributes.getTitle())) { ConfluenceDocumentBuilder.this.emitContent(" | "); ConfluenceDocumentBuilder.this.emitContent(attributes.getTitle()); } ConfluenceDocumentBuilder.this.emitContent(']'); }</code><technical_language>is reason this changed</technical_language>

Target:
protected void emitContent(String content) throws IOException { ConfluenceDocumentBuilder.this.emitContent(content); if (!Strings.isNullOrEmpty(content)) { ConfluenceDocumentBuilder.this.emitContent(" | "); } if (attributes.getHref() != null) { ConfluenceDocumentBuilder.this.emitContent(attributes.getHref()); } if (!Strings.isNullOrEmpty(attributes.getTitle())) { ConfluenceDocumentBuilder.this.emitContent(" | "); ConfluenceDocumentBuilder.this.emitContent(attributes.getTitle()); } }
Source:
<code>private PageTitle(@Nullable String text, @NonNull WikiSite wiki, @Nullable String thumbUrl, @Nullable PageProperties properties) { if (TextUtils.isEmpty(text)) { text = SiteInfoClient.getMainPageForLang(wiki.languageCode()); } String[] fragParts = text.split("#", -1); text = fragParts[0]; if (fragParts.length > 1) { this.fragment = decodeURL(fragParts[1]).replace(" ", "_"); } else { this.fragment = null; } String[] parts = text.split(":", -1); if (parts.length > 1) { String namespaceOrLanguage = parts[0]; if (Arrays.asList(Locale.getISOLanguages()).contains(namespaceOrLanguage)) { this.wiki = WikiSite.forLanguageCode(namespaceOrLanguage); this.text = TextUtils.join(":", Arrays.copyOfRange(parts, 1, parts.length)); } else { this.wiki = wiki; this.text = text; } } else { this.wiki = wiki; this.text = parts[0]; } <START> this.namespace = null; <END> this.thumbUrl = thumbUrl; this.properties = properties; }</code><technical_language>this means namespace null? this is improvement, I wrong previous logic. Hint: this issue fixed in line of code in LangLinksActivity, combined hint</technical_language>

Target:
private PageTitle(@Nullable String text, @NonNull WikiSite wiki, @Nullable String thumbUrl, @Nullable PageProperties properties) { if (TextUtils.isEmpty(text)) { text = SiteInfoClient.getMainPageForLang(wiki.languageCode()); } String[] fragParts = text.split("#", -1); text = fragParts[0]; if (fragParts.length > 1) { this.fragment = decodeURL(fragParts[1]).replace(" ", "_"); } else { this.fragment = null; } String[] parts = text.split(":", -1); if (parts.length > 1) { String namespaceOrLanguage = parts[0]; if (Arrays.asList(Locale.getISOLanguages()).contains(namespaceOrLanguage)) { this.namespace = null; this.wiki = WikiSite.forLanguageCode(namespaceOrLanguage); } else { this.wiki = wiki; this.namespace = namespaceOrLanguage; } this.text = TextUtils.join(":", Arrays.copyOfRange(parts, 1, parts.length)); } else { this.wiki = wiki; this.namespace = null; this.text = parts[0]; } this.thumbUrl = thumbUrl; this.properties = properties; }
Source:
<code>private static TextSummarizer getLocalSummarizer() throws IOException { Collection<? extends TextSummarizer> summarizers = Lookup.getDefault().lookupAll(TextSummarizer.class ); if (!summarizers.isEmpty()) { summarizerToUse = summarizers.iterator().next(); return summarizerToUse; } <START> throw new IOException("No summarizers found"); <END> }</code><technical_language>return null instead of throwing exception? wrong. need empty catch block</technical_language>

Target:
private static TextSummarizer getLocalSummarizer() { Collection<? extends TextSummarizer> summarizers = Lookup.getDefault().lookupAll(TextSummarizer.class ); if (!summarizers.isEmpty()) { summarizerToUse = summarizers.iterator().next(); return summarizerToUse; } return null; }
Source:
<code>void updateUser(String acceptHeader, String username) { deleteCreatedUser(username); UserForm test = buildUser(username, "password-update", "my-new-security-token"); given().contentType(MediaType.APPLICATION_JSON_VALUE) .accept(acceptHeader) .body(test) .when() .put(getContextBaseUrl()) .peek() .then() .statusCode(HttpStatus.OK.value()) .body(containsString(SUCCESSFUL_CREATE_USER)) .extract() .asString(); User createdUser = retrieveUserByName(test.getUsername()); assertEquals(username, createdUser.getUsername()); <START> logger.info("Users before update: ->>>>>> "); <END> displayAllUsers(); UserForm updatedUser = buildFromUser(createdUser, u -> u.setEnabled(true)); given().contentType(MediaType.APPLICATION_JSON_VALUE) .accept(acceptHeader) .body(updatedUser) .when() .put(getContextBaseUrl() + "/" + username) .peek() .then() .statusCode(HttpStatus.OK.value()) .body(containsString(SUCCESSFUL_UPDATE_USER)); logger.info("Users after update: ->>>>>> "); displayAllUsers(); createdUser = retrieveUserByName(username); assertTrue(createdUser.isEnabled()); assertEquals("my-new-security-token", createdUser.getSecurityTokenKey()); deleteCreatedUser(username); }</code><technical_language>longer need this...? certainly, info..</technical_language>

Target:
void updateUser(String acceptHeader, String username) { deleteCreatedUser(username); UserForm test = buildUser(username, "password-update", "my-new-security-token"); given().contentType(MediaType.APPLICATION_JSON_VALUE) .accept(acceptHeader) .body(test) .when() .put(getContextBaseUrl()) .peek() .then() .statusCode(HttpStatus.OK.value()) .body(containsString(SUCCESSFUL_CREATE_USER)) .extract() .asString(); User createdUser = retrieveUserByName(test.getUsername()); assertEquals(username, createdUser.getUsername()); UserForm updatedUser = buildFromUser(createdUser, u -> u.setEnabled(true)); given().contentType(MediaType.APPLICATION_JSON_VALUE) .accept(acceptHeader) .body(updatedUser) .when() .put(getContextBaseUrl() + "/" + username) .peek() .then() .statusCode(HttpStatus.OK.value()) .body(containsString(SUCCESSFUL_UPDATE_USER)); createdUser = retrieveUserByName(username); assertTrue(createdUser.isEnabled()); assertEquals("my-new-security-token", createdUser.getSecurityTokenKey()); deleteCreatedUser(username); }
Source:
<code>public Map<String, String> getLinks() { Map<String, String> links = new HashMap<String, String>(); <START> if (OpenmrsConstants.OPENMRS_VERSION_SHORT.equals(REQUIRED_OPENMRS_VERSION)) { <END> links.put("module/emrapi/MigrateDiagnosis.form", Context.getMessageSourceService().getMessage(MIGRATE_DIAGNOSIS_LINK_CODE)); } return links; }</code><technical_language>do line</technical_language>

Target:
public Map<String, String> getLinks() { Map<String, String> links = new HashMap<String, String>(); if (ModuleUtil.compareVersion(OpenmrsConstants.OPENMRS_VERSION, DIAGNOSIS_MIGRATION_LEAST_SUPPORTED_VERSION) >= 0) { links.put("module/emrapi/encounterDiagnosisMigrationDashboard.form", "emrapi.migrateDiagnosis.migrateDiagnosisLink.name"); } return links; }
Source:
<code>private TableStatisticsData addPartitionStats(TableStatisticsData left, TableStatisticsData right, TpchColumn<?> partitionColumn) { <START> Map<String, ColumnStatisticsData> combinedColumnStats = left.getColumns().entrySet().stream().collect(toImmutableMap( <END> Map.Entry::getKey, entry -> { String columnName = entry.getKey(); ColumnStatisticsData leftStats = entry.getValue(); ColumnStatisticsData rightStats = right.getColumns().get(columnName); Optional<Long> ndv = addDistinctValuesCount(partitionColumn, columnName, leftStats, rightStats); Optional<Object> min = combine(leftStats.getMin(), rightStats.getMin(), this::min); Optional<Object> max = combine(leftStats.getMax(), rightStats.getMax(), this::max); return new ColumnStatisticsData(ndv, min, max); })); return new TableStatisticsData( left.getRowCount() + right.getRowCount(), combinedColumnStats); }</code><technical_language>methods estimateStats static</technical_language>

Target:
private TableStatisticsData addPartitionStats(TableStatisticsData left, TableStatisticsData right, TpchColumn<?> partitionColumn) { Map<String, ColumnStatisticsData> combinedColumnStats = left.getColumns().entrySet().stream().collect(toImmutableMap( Map.Entry::getKey, entry -> { String columnName = entry.getKey(); ColumnStatisticsData leftStats = entry.getValue(); ColumnStatisticsData rightStats = right.getColumns().get(columnName); Optional<Long> ndv = addDistinctValuesCount(partitionColumn, columnName, leftStats, rightStats); Optional<Object> min = combine(leftStats.getMin(), rightStats.getMin(), this::min); Optional<Object> max = combine(leftStats.getMax(), rightStats.getMax(), this::max); Optional<Long> dataSize = leftStats.getDataSize() .flatMap(leftDataSize -> rightStats.getDataSize().map(rightDataSize -> leftDataSize + rightDataSize)); return new ColumnStatisticsData(ndv, min, max, dataSize); })); return new TableStatisticsData( left.getRowCount() + right.getRowCount(), combinedColumnStats); }
Source:
<code>public ServiceAccountCredentials( String clientId, String clientEmail, PrivateKey privateKey, String privateKeyId, Collection<String> scopes, HttpTransportFactory transportFactory, URI tokenServerUri, <START> String serviceAccountUser) { <END> this.clientId = clientId; this.clientEmail = Preconditions.checkNotNull(clientEmail); this.privateKey = Preconditions.checkNotNull(privateKey); this.privateKeyId = privateKeyId; this.scopes = (scopes == null) ? ImmutableSet.<String>of() : ImmutableSet.copyOf(scopes); this.transportFactory = firstNonNull(transportFactory, getFromServiceLoader(HttpTransportFactory.class, OAuth2Utils.HTTP_TRANSPORT_FACTORY)); this.transportFactoryClassName = this.transportFactory.getClass().getName(); this.tokenServerUri = (tokenServerUri == null) ? OAuth2Utils.TOKEN_SERVER_URI : tokenServerUri; this.serviceAccountUser = serviceAccountUser; }</code><technical_language>I I want avoid explosion of constructors. stuck-ish existing ones, new private want fromPkcs8. Although, explosion of methods name, too. hide - existing fromPkcs8 function call createDelegated result get want</technical_language>

Target:
ServiceAccountCredentials( String clientId, String clientEmail, PrivateKey privateKey, String privateKeyId, Collection<String> scopes, HttpTransportFactory transportFactory, URI tokenServerUri, String serviceAccountUser) { this.clientId = clientId; this.clientEmail = Preconditions.checkNotNull(clientEmail); this.privateKey = Preconditions.checkNotNull(privateKey); this.privateKeyId = privateKeyId; this.scopes = (scopes == null) ? ImmutableSet.<String>of() : ImmutableSet.copyOf(scopes); this.transportFactory = firstNonNull(transportFactory, getFromServiceLoader(HttpTransportFactory.class, OAuth2Utils.HTTP_TRANSPORT_FACTORY)); this.transportFactoryClassName = this.transportFactory.getClass().getName(); this.tokenServerUri = (tokenServerUri == null) ? OAuth2Utils.TOKEN_SERVER_URI : tokenServerUri; this.serviceAccountUser = serviceAccountUser; }
Source:
<code>public List<TmfXmlLocation> getLocations() { <START> return fLocations; <END> }</code><technical_language>expose list. a single getter getLocation(int), Iterable, if needed. Iterable, careful for concurrent accesses. in this case, elements added array in loadXml(), is called constructor. means this method accessible (after constructor run), modifier afterwards. In fact, clean? Putting loadXml() stuff right in constructor, saving fields unmodifiableList/Map's. expose Iterable view, worry locking anywhere. Also, List, in fact operation do is iterate them. If order is important Set/HashSet (or TreeSet if store Integers/Longs), more performant</technical_language>

Target:
public Iterable<TmfXmlLocation> getLocations() { return fLocations; }
Source:
<code>public static Map<String, Set<TestInfo>> getAllTests(File testMappingsDir) { Map<String, Set<TestInfo>> allTests = new HashMap<String, Set<TestInfo>>(); Stream<Path> stream = null; try { Path testMappingsRootPath = Paths.get(testMappingsDir.getAbsolutePath()); stream = Files.walk(testMappingsRootPath, FileVisitOption.FOLLOW_LINKS); stream.filter(path -> path.getFileName().toString().equals(TEST_MAPPING)) .forEach( path -> getAllTests(allTests, path, testMappingsRootPath)); } catch (IOException e) { <START> RuntimeException runtimeException = new RuntimeException( String.format( "IO error (%s) when reading tests from TEST_MAPPING files (%s)", e.getMessage(), testMappingsDir.getAbsolutePath()), e); throw runtimeException; <END> } finally { if (stream != null) { stream.close(); } } return allTests; }</code><technical_language>nit: throw new RuntimeException</technical_language>

Target:
public static Map<String, Set<TestInfo>> getAllTests(File testMappingsDir) { Map<String, Set<TestInfo>> allTests = new HashMap<String, Set<TestInfo>>(); Stream<Path> stream = null; try { Path testMappingsRootPath = Paths.get(testMappingsDir.getAbsolutePath()); stream = Files.walk(testMappingsRootPath, FileVisitOption.FOLLOW_LINKS); stream.filter(path -> path.getFileName().toString().equals(TEST_MAPPING)) .forEach( path -> getAllTests(allTests, path, testMappingsRootPath)); } catch (IOException e) { throw new RuntimeException( String.format( "IO exception (%s) when reading tests from TEST_MAPPING files (%s)", e.getMessage(), testMappingsDir.getAbsolutePath()), e); } finally { if (stream != null) { stream.close(); } } return allTests; }
Source:
<code>public void testEntrySetStreamRemove() { Map<Object, String> values = putValuesInCache(); final Cache<Object, Object> cache = cache(0, CACHE_NAME); cache.getAdvancedCache().addInterceptor(new BaseCustomInterceptor() { @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { assertTrue(command.hasAnyFlag(FlagBitSets.SKIP_CACHE_STORE)); return super.visitRemoveCommand(ctx, command); } }, 0); Iterator<Map.Entry<Object, Object>> it = cache(0, CACHE_NAME).getAdvancedCache().withFlags( <START> Flag.SKIP_CACHE_STORE) <END> .entrySet() .stream() .iterator(); assertTrue(it.hasNext()); Map.Entry<Object, Object> entry = it.next(); Object key = entry.getKey(); assertEquals(values.get(key), entry.getValue()); Exceptions.expectException(UnsupportedOperationException.class, it::remove); }</code><technical_language>advancedCache(0, CACHE_NAME) fit line</technical_language>

Target:
public void testEntrySetStreamRemove() { Map<Object, String> values = putValuesInCache(); final AdvancedCache<Object, Object> cache = advancedCache(0, CACHE_NAME); cache.addInterceptor(new BaseCustomInterceptor() { @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { assertTrue(command.hasAnyFlag(FlagBitSets.SKIP_CACHE_STORE)); return super.visitRemoveCommand(ctx, command); } }, 0); Iterator<Map.Entry<Object, Object>> it = cache.withFlags(Flag.SKIP_CACHE_STORE) .entrySet() .stream() .iterator(); assertTrue(it.hasNext()); Map.Entry<Object, Object> entry = it.next(); Object key = entry.getKey(); assertEquals(values.get(key), entry.getValue()); Exceptions.expectException(UnsupportedOperationException.class, it::remove); }
Source:
<code>private boolean navigate(WebElement dateBox, LocalDate date) throws ParseException { click(dateBox); LocalDate selectedDate = LocalDate.parse( <START> dateBox.getAttribute("value"), DateTimeFormatter.ofPattern("EEE, dd MMM, yyyy")); <END> String month = date.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH); String year = Integer.toString(date.getYear()); if (selectedDate.isAfter(date)) { while (!getDatepickerMonth().equals(month) || !getDatepickerYear().equals(year)) { WebElement previousButton = browser.driver.findElement(By.className("ui-datepicker-prev")); if (previousButton.getAttribute("class").contains("ui-state-disabled")) { return false; } click(previousButton); } } else { while (!getDatepickerMonth().equals(month) || !getDatepickerYear().equals(year)) { WebElement nextButton = browser.driver.findElement(By.className("ui-datepicker-next")); if (nextButton.getAttribute("class").contains("ui-state-disabled")) { return false; } click(nextButton); } } return true; }</code><technical_language>TimeHelper.parseLocalDateTimeForSessionsForm(dateBox.getAttribute("value"), 0, 0) hardcode pattern here? - extract a new method TimeHelper#parseLocalDateForSessionsForm refactor TimeHelper#parseLocalDateTimeForSessionsForm new method for parsing of date part LocalTime#of(int, int) Integer#parseInt for parsing of time part (then combine LocalDateTime#of(LocalDate, LocalTime)). Then, new method TimeHelper#parseLocalDateForSessionsForm here. Similar refactoring done for TimeHelper#combineDateTime - TimeHelper#parseLocalDateForSessionsForm for parsing of date part, custom logic for parsing of time part, LocalDateTime#of(LocalDate, LocalTime) combine two. making changes, constant EEE, dd MMM, yyyy in place, instead of current places (which related sessions form). a new issue for changes if feel in this PR</technical_language>

Target:
private boolean navigate(WebElement dateBox, LocalDate date) throws ParseException { click(dateBox); LocalDate selectedDate = TimeHelper.parseLocalDateForSessionsForm(dateBox.getAttribute("value")); String month = date.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH); String year = Integer.toString(date.getYear()); if (selectedDate.isAfter(date)) { while (!getDatepickerMonth().equals(month) || !getDatepickerYear().equals(year)) { WebElement previousButton = browser.driver.findElement(By.className("ui-datepicker-prev")); if (previousButton.getAttribute("class").contains("ui-state-disabled")) { return false; } click(previousButton); } } else { while (!getDatepickerMonth().equals(month) || !getDatepickerYear().equals(year)) { WebElement nextButton = browser.driver.findElement(By.className("ui-datepicker-next")); if (nextButton.getAttribute("class").contains("ui-state-disabled")) { return false; } click(nextButton); } } return true; }
Source:
<code>public GlowTravelAgent(World world) { if (world.getEnvironment() == World.Environment.THE_END) { <START> throw new UnsupportedOperationException("Not supported yet."); <END> } this.world = world; }</code><technical_language>Change message more descriptive, End portal teleportation is supported yet</technical_language>

Target:
public GlowTravelAgent(World world) { if (world.getEnvironment() == World.Environment.THE_END) { throw new UnsupportedOperationException("End Portals are not supported yet."); } this.world = world; }
Source:
<code>public void writeStringNoTag(final String value) throws IOException { try { final int lengthVarIntSize = computeRawVarint32Size(value.length()); <START> if (lengthVarIntSize == computeRawVarint32Size(value.length() * 3 )) { <END> int oldPosition = buffer.position(); buffer.position(oldPosition + lengthVarIntSize); encode(value, buffer); int newPosition = buffer.position(); buffer.position(oldPosition); writeRawVarint32(newPosition - oldPosition - lengthVarIntSize); buffer.position(newPosition); } else { writeRawVarint32(encodedLength(value)); encode(value, buffer); } } catch (BufferOverflowException e) { throw new OutOfSpaceException(buffer.position(), buffer.limit()); } }</code><technical_language>max bytes char in UTF-8 is 4 bytes (the new standard) [6 bytes in standard]. <LINK_0> Java handle Unicode U+10000 U+10FFFF surrogate pairs. chars require 4 bytes in UTF-8. aware of Protocol Buffer limiting character range U+FFFF, assume</technical_language>

Target:
public void writeStringNoTag(final String value) throws IOException { try { final int minLengthVarIntSize = computeRawVarint32Size(value.length()); final int maxLengthVarIntSize = computeRawVarint32Size(value.length() * MAX_UTF8_EXPANSION); if (minLengthVarIntSize == maxLengthVarIntSize) { int oldPosition = buffer.position(); buffer.position(oldPosition + minLengthVarIntSize); encode(value, buffer); int newPosition = buffer.position(); buffer.position(oldPosition); writeRawVarint32(newPosition - oldPosition - minLengthVarIntSize); buffer.position(newPosition); } else { writeRawVarint32(encodedLength(value)); encode(value, buffer); } } catch (BufferOverflowException e) { throw new OutOfSpaceException(buffer.position(), buffer.limit()); } }
Source:
<code><START> public void testEdit() throws Throwable { <END> final CountDownLatch completionLatch = new CountDownLatch(1); runTestOnUiThread(new Runnable() { @Override public void run() { doSave(completionLatch); } }); assertTrue(completionLatch.await(TASK_COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS)); }</code><technical_language>I need @Test annotations if JUnit 4</technical_language>

Target:
public void testEdit() throws Throwable { final TestLatch completionLatch = new TestLatch(1); InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { doSave(completionLatch); } }); assertThat(completionLatch.await(), is(true)); }
Source:
<code>public FormValidation updateNow() throws IOException { List<JSONObject> jsonList = new ArrayList<>(); boolean toolInstallerMetadataExists = false; for (UpdateSite updatesite : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) { String site = updatesite.getMetadataUrlForDownloadable(url); if (site == null) { <START> return FormValidation.warning("The update site " + updatesite + " does not look like an update center"); <END> } String jsonString; try { jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))); toolInstallerMetadataExists = true; } catch (Exception e) { LOGGER.log(Level.FINE, "Could not load json from " + site, e ); continue; } JSONObject o = JSONObject.fromObject(jsonString); if (signatureCheck) { FormValidation e = updatesite.getJsonSignatureValidator(signatureValidatorPrefix +" '"+id+"'").verifySignature(o); if (e.kind!= Kind.OK) { LOGGER.log(Level.WARNING, "signature check failed for " + site, e ); continue; } } jsonList.add(o); } if (jsonList.size() == 0 && toolInstallerMetadataExists) { return FormValidation.warning("None of the tool installer metadata passed the signature check"); } else if (!toolInstallerMetadataExists) { LOGGER.log(Level.WARNING, "No tool installer metadata found for " + id); return FormValidation.ok(); } JSONObject reducedJson = reduce(jsonList); return load(reducedJson.toString(), System.currentTimeMillis()); }</code><technical_language>please show example of resulting warning</technical_language>

Target:
public FormValidation updateNow() throws IOException { List<JSONObject> jsonList = new ArrayList<>(); boolean toolInstallerMetadataExists = false; for (UpdateSite updatesite : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) { String site = updatesite.getMetadataUrlForDownloadable(url); if (site == null) { return FormValidation.warning("The update site " + updatesite.getId() + " does not look like an update center"); } String jsonString; try { jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))); toolInstallerMetadataExists = true; } catch (Exception e) { LOGGER.log(Level.FINE, "Could not load json from " + site, e ); continue; } JSONObject o = JSONObject.fromObject(jsonString); if (signatureCheck) { FormValidation e = updatesite.getJsonSignatureValidator(signatureValidatorPrefix +" '"+id+"'").verifySignature(o); if (e.kind!= Kind.OK) { LOGGER.log(Level.WARNING, "signature check failed for " + site, e ); continue; } } jsonList.add(o); } if (jsonList.size() == 0 && toolInstallerMetadataExists) { return FormValidation.warning("None of the tool installer metadata passed the signature check"); } else if (!toolInstallerMetadataExists) { LOGGER.log(Level.WARNING, "No tool installer metadata found for " + id); return FormValidation.ok(); } JSONObject reducedJson = reduce(jsonList); return load(reducedJson.toString(), System.currentTimeMillis()); }
Source:
<code>public boolean hasFullValuePrecision( IndexQuery... predicates ) { IndexReader instance = selector.select( instances, predicates ); if ( instance == null ) { <START> assert predicates.length == 1 && predicates[0] instanceof IndexQuery.ExistsPredicate : <END> "Unexpected selector result for predicates " + Arrays.toString( predicates ); return true; } return instance.hasFullValuePrecision( predicates ); }</code><technical_language>Please do assert. If important invariant regular if check throw exception class: IllegalStateException, IllegalArgumentException, fits best</technical_language>

Target:
public boolean hasFullValuePrecision( IndexQuery... predicates ) { IndexReader instance = selector.select( instances, predicates ); if ( instance == null ) { if ( !(predicates.length == 1 && predicates[0] instanceof ExistsPredicate) ) { throw new IllegalStateException( "Selected IndexReader null for predicates " + Arrays.toString( predicates ) ); } return true; } return instance.hasFullValuePrecision( predicates ); }
Source:
<code>public int getSQLType(int oid) throws SQLException { if (oid == Oid.UNSPECIFIED) { return Types.OTHER; } <START> Integer sqlType = _oidToSQLType.get(oid); <END> if (sqlType != null) { return sqlType; } PgType pgType = fetchPgType(oid); if (pgType == null) { return Types.OTHER; } return pgType.sqlType(); }</code><technical_language>this access needs synchronized</technical_language>

Target:
public synchronized int getSQLType(int oid) throws SQLException { if (oid == Oid.UNSPECIFIED) { return Types.OTHER; } Integer sqlType = _oidToSQLType.get(oid); if (sqlType != null) { return sqlType; } PgType pgType = fetchPgType(oid); if (pgType == null) { return Types.OTHER; } return pgType.sqlType(); }
Source:
<code>public boolean isSecretAnswer(User u, String answer) throws DAOException { if (answer == null || answer.equals("")) { return false; } LoginCredential credentials = getLoginCredential(u); String answerOnRecord = credentials.getSecretAnswer(); <START> String hashedAnswer = Security.encodeString(answer + credentials.getSalt()); <END> return (hashedAnswer.equals(answerOnRecord)); }</code><technical_language>I suggest answer.toLowerCase() secret answer validation case insensitive</technical_language>

Target:
public boolean isSecretAnswer(User u, String answer) throws DAOException { if (answer == null || answer.equals("")) { return false; } LoginCredential credentials = getLoginCredential(u); String answerOnRecord = credentials.getSecretAnswer(); String hashedAnswer = Security.encodeString(answer.toLowerCase() + credentials.getSalt()); return (hashedAnswer.equals(answerOnRecord)); }
Source:
<code>public InterpolatedNodalCurve withNode(double x, double y, ParameterMetadata paramMetadata) { <START> throw new IllegalArgumentException("Not well-defined due to unspecified interpolator"); <END> }</code><technical_language>If x == this.x method succeed</technical_language>

Target:
public ConstantNodalCurve withNode(double x, double y, ParameterMetadata paramMetadata) { ArgChecker.isTrue(x == xValue, "x should be equal to the existing x-value"); CurveMetadata md = metadata.withParameterMetadata(ImmutableList.of(paramMetadata)); return new ConstantNodalCurve(md, x, y); }
Source:
<code>private static boolean coordinateInsideBoundary(int coordinate, long maxTileIndex) { <START> return (coordinate >= 0 && coordinate <= maxTileIndex); <END> }</code><technical_language>brackets extra</technical_language>

Target:
private static boolean coordinateInsideBoundary(int coordinate, long maxTileIndex) { return coordinate >= 0 && coordinate <= maxTileIndex; }
Source:
<code>public void run() { ISarosSession session = sessionManager.getSession(); JID jid = getSelectedJID(); if (session != null || jid == null) { return; } <START> if (!discoveryManager.isFeatureSupported(jid, SarosConstants.NAMESPACE_SERVER)) { <END> return; } transmitter.sendPacketExtension( jid, JoinSessionRequestExtension.PROVIDER.create(new JoinSessionRequestExtension())); }</code><technical_language>Is a reason check selected user is a Saros server (here in line 445 of SarosView)? I misunderstanding checks? This check is missing null-check for result of 'discoveryManager.isFeatureSupported(...)</technical_language>

Target:
public void run() { ISarosSession session = sessionManager.getSession(); JID jid = getSelectedJID(); if (session != null || jid == null) { return; } transmitter.sendPacketExtension( jid, JoinSessionRequestExtension.PROVIDER.create(new JoinSessionRequestExtension())); }