auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Sorting convert(Sort sort) { Iterator<Order> order = sort.iterator(); if (order.hasNext()) { Order next = order.next(); String property = next.getProperty(); if (!property.equals(RELEVANCE)) { return new Sorting(JudgmentIndexField.valueOf(property).getFieldName(), convertDirection(next.getDirection())); <START> } <END> } return Sorting.relevanceSorting(); }</code><technical_language>result in java.lang.IllegalArgumentException enum</technical_language>

Target:
public Sorting convert(Sort sort) { Iterator<Order> order = sort.iterator(); if (order.hasNext()) { Order next = order.next(); String property = next.getProperty(); String fieldName = ""; try { fieldName = JudgmentIndexField.valueOf(property).getFieldName(); } catch (IllegalArgumentException e) { return Sorting.relevanceSorting(); } if (!property.equals(RELEVANCE)) { return new Sorting(fieldName, convertDirection(next.getDirection())); } } return Sorting.relevanceSorting(); }
Source:
<code>private static Form flip(Form binaryLogicalOperation) { switch (binaryLogicalOperation) { case AND: return OR; case OR: return AND; } <START> throw new UnsupportedOperationException("Invalid binary logical operation"); <END> }</code><technical_language>nit: do java throw new UnsupportedOperationException("Invalid binary logical operation: " + binaryLogicalOperation);</technical_language>

Target:
private static Form flip(Form binaryLogicalOperation) { switch (binaryLogicalOperation) { case AND: return OR; case OR: return AND; } throw new UnsupportedOperationException("Invalid binary logical operation: " + binaryLogicalOperation); }
Source:
<code>public SqlStatements define(String key, Object value) { <START> synchronized (this) { <END> attributes.put(key, value); } return this; }</code><technical_language>Prefer a private field for a mutex prevent code able hold lock: java private final Object mutex = new Object(); public SqlStatement define(String key, Object value) { synchronized (mutex) { attributes.put(key, value); } return this; }</technical_language>

Target:
public SqlStatements define(String key, Object value) { attributes.put(key, value); return this; }
Source:
<code>private void deliverFailure(@NonNull final Throwable error) { handler.post(new Runnable() { @Override public void run() { if (progressCallback != null) { progressCallback.finishProcess(); } if (errorNotification != null) { if (refreshListener != null) { <START> errorNotification.showError(R.string.reset_no_network_message, <END> FontAwesomeIcons.fa_wifi, R.string.lbl_reload, new View.OnClickListener() { @Override public void onClick(View v) { if (NetworkUtil.isConnected(context)) { refreshListener.onRefresh(); } } }); } else { errorNotification.showError(context, error); } } onFailure(error); } }); }</code><technical_language>un-conditionally showing network message checking is actual of error</technical_language>

Target:
private void deliverFailure(@NonNull final Throwable error) { handler.post(new Runnable() { @Override public void run() { if (progressCallback != null) { progressCallback.finishProcess(); } if (errorNotification != null) { if (refreshListener != null) { errorNotification.showError(context, error, R.string.lbl_reload, new View.OnClickListener() { @Override public void onClick(View v) { if (NetworkUtil.isConnected(context)) { refreshListener.onRefresh(); } } }); } else { errorNotification.showError(context, error); } } onFailure(error); onFinish(); } }); }
Source:
<code>public Vector3f getSpawnPosition(World world, EntityRef clientEntity) { <START> return new Vector3f(new Vector3i(LASUtils.FLOATING_PLATFORM_POSITION) .add(0, 5, 0)); <END> }</code><technical_language>get rid of intermediate Vector3i here? suggestion return new Vector3f(LASUtils.FLOATING_PLATFORM_POSITION).add(0, 5, 0);</technical_language>

Target:
public Vector3f getSpawnPosition(World world, EntityRef clientEntity) { return new Vector3f(LASUtils.FLOATING_PLATFORM_POSITION) .add(0.0f, 5.0f, 0.0f); }
Source:
<code>@Test public void invalidCenterCrop() { try { new RequestBuilder().centerCrop(); fail("Center crop without resize should throw exception."); } catch (IllegalStateException expected) { } try { <START> new RequestBuilder().centerInside().centerCrop(); <END> fail("Calling center crop after center inside should throw exception."); } catch (IllegalStateException expected) { } }</code><technical_language>Need add a resize(10, 10) here. failure is due lack of resize</technical_language>

Target:
@Test public void invalidCenterCrop() { try { new RequestBuilder().centerCrop(); fail("Center crop without resize should throw exception."); } catch (IllegalStateException expected) { } try { new RequestBuilder().resize(10, 10).centerInside().centerCrop(); fail("Calling center crop after center inside should throw exception."); } catch (IllegalStateException expected) { } }
Source:
<code>public ParseGeoPoint getLocation() { <START> return (ParseGeoPoint) getClient().get("location"); <END> }</code><technical_language>Change getParseGeoPoint("location") get rid of this casting stuff</technical_language>

Target:
public ParseGeoPoint getLocation() { return getClient().getLocation(); }
Source:
<code><START> public void shouldCreateRepartitionTopicIfKeyChangingOperationWasNotPerformed() throws ExecutionException, InterruptedException { <END> final String repartitionName = "dummy"; final long timestamp = System.currentTimeMillis(); sendEvents( timestamp, Arrays.asList( new KeyValue<>(1, "A"), new KeyValue<>(2, "B") ) ); final StreamsBuilder builder = new StreamsBuilder(); builder.stream(inputTopic, Consumed.with(Serdes.Integer(), Serdes.String())) .repartition(Repartitioned.as(repartitionName)) .to(outputTopic); startStreams(builder); validateReceivedMessages( new IntegerDeserializer(), new StringDeserializer(), Arrays.asList( new KeyValue<>(1, "A"), new KeyValue<>(2, "B") ) ); final String topology = builder.build().describe().toString(); assertTrue(topicExists(toRepartitionTopicName(repartitionName))); assertEquals(1, countOccurrencesInTopology(topology, "Sink: .*dummy-repartition.*")); }</code><technical_language>Do need integration test for this? Topology#describe(), I verify this a unit test</technical_language>

Target:
public void shouldCreateRepartitionTopicIfKeyChangingOperationWasNotPerformed() throws Exception { final String repartitionName = "dummy"; final long timestamp = System.currentTimeMillis(); sendEvents( timestamp, Arrays.asList( new KeyValue<>(1, "A"), new KeyValue<>(2, "B") ) ); final StreamsBuilder builder = new StreamsBuilder(); builder.stream(inputTopic, Consumed.with(Serdes.Integer(), Serdes.String())) .repartition(Repartitioned.as(repartitionName)) .to(outputTopic); startStreams(builder); validateReceivedMessages( new IntegerDeserializer(), new StringDeserializer(), Arrays.asList( new KeyValue<>(1, "A"), new KeyValue<>(2, "B") ) ); final String topology = builder.build().describe().toString(); assertTrue(topicExists(toRepartitionTopicName(repartitionName))); assertEquals(1, countOccurrencesInTopology(topology, "Sink: .*dummy-repartition.*")); }
Source:
<code>public Pair<List<LongRange>, Map<String, List<LongRange>>> route(final LongRange dataKeyRange) { List<LongRange> localKeyRanges = Collections.EMPTY_LIST; final Map<String, List<LongRange>> remoteKeyRanges = new HashMap<>(); final Map<Integer, SortedSet<Long>> partitionedKeysMap = new HashMap<>(); for (long dataKey = dataKeyRange.getMinimumLong(); dataKey <= dataKeyRange.getMaximumLong(); dataKey++) { final int partitionId = partitionFunc.getPartitionId(dataKey); if (!partitionedKeysMap.containsKey(partitionId)) { partitionedKeysMap.put(partitionId, new TreeSet<Long>()); } final SortedSet<Long> dataKeys = partitionedKeysMap.get(partitionId); dataKeys.add(dataKey); } for (final Map.Entry<Integer, SortedSet<Long>> partitionedKeysEntry : partitionedKeysMap.entrySet()) { final List<LongRange> rangeList = new ArrayList<>(LongRangeUtils.generateDenseLongRanges(partitionedKeysEntry.getValue())); final int partitionId = partitionedKeysEntry.getKey(); final int targetEvalId = partitionIdToEvalId[partitionId]; <START> if (targetEvalId == memoryStoreId) { <END> localKeyRanges = rangeList; } else { remoteKeyRanges.put(evalPrefix + '-' + targetEvalId, rangeList); } } return new Pair<>(localKeyRanges, remoteKeyRanges); }</code><technical_language>explicitly state assume here? confusing compares evalId storeId. issue exist in L174</technical_language>

Target:
public Pair<List<LongRange>, Map<String, List<LongRange>>> route(final LongRange dataKeyRange) { List<LongRange> localKeyRanges = Collections.EMPTY_LIST; final Map<String, List<LongRange>> remoteKeyRanges = new HashMap<>(); final Map<Integer, SortedSet<Long>> partitionedKeysMap = new HashMap<>(); for (long dataKey = dataKeyRange.getMinimumLong(); dataKey <= dataKeyRange.getMaximumLong(); dataKey++) { final int partitionId = partitionFunc.getPartitionId(dataKey); if (!partitionedKeysMap.containsKey(partitionId)) { partitionedKeysMap.put(partitionId, new TreeSet<Long>()); } final SortedSet<Long> dataKeys = partitionedKeysMap.get(partitionId); dataKeys.add(dataKey); } for (final Map.Entry<Integer, SortedSet<Long>> partitionedKeysEntry : partitionedKeysMap.entrySet()) { final List<LongRange> rangeList = new ArrayList<>(LongRangeUtils.generateDenseLongRanges(partitionedKeysEntry.getValue())); final int partitionId = partitionedKeysEntry.getKey(); final int memoryStoreId = pIdToMemoryStoreId[partitionId]; if (memoryStoreId == localMemoryStoreId) { localKeyRanges = rangeList; } else { remoteKeyRanges.put(getEvalId(memoryStoreId), rangeList); } } return new Pair<>(localKeyRanges, remoteKeyRanges); }
Source:
<code><START> private void updateQuota() { <END> Account account = AccountUtils.getCurrentOwnCloudAccount(this); if (account == null) return; UserProfile.UserQuota userQuota = UserProfilesRepository.getUserProfilesRepository().getQuota(account.name); if (userQuota == null) return; ProgressBar accountQuotaBar = findViewById(R.id.account_quota_bar); TextView accountQuotaText = findViewById(R.id.account_quota_text); if (accountQuotaBar!= null && accountQuotaText != null) { if(userQuota.getFree() >= 0) { accountQuotaBar.setProgress((int) Math.ceil(userQuota.getRelative())); accountQuotaText.setText( String.format(getString(R.string.drawer_quota), DisplayUtils.bytesToHumanReadable(userQuota.getUsed(), this), DisplayUtils.bytesToHumanReadable(userQuota.getTotal(), this) ) ); } else { accountQuotaBar.setProgress(0); accountQuotaText.setText( String.format(getString(R.string.drawer_quota), DisplayUtils.bytesToHumanReadable(userQuota.getUsed(), this), getQuotaTotalMsg((int) userQuota.getFree()) ) ); } } }</code><technical_language>I if is empty line new line</technical_language>

Target:
private void updateQuota() { Account account = AccountUtils.getCurrentOwnCloudAccount(this); if (account == null) return; UserProfile.UserQuota userQuota = UserProfilesRepository.getUserProfilesRepository().getQuota(account.name); if (userQuota == null) return; ProgressBar accountQuotaBar = findViewById(R.id.account_quota_bar); TextView accountQuotaText = findViewById(R.id.account_quota_text); if (accountQuotaBar!= null && accountQuotaText != null) { if (userQuota.getFree() < 0) { accountQuotaBar.setVisibility(View.VISIBLE); accountQuotaBar.setProgress(0); accountQuotaText.setText( String.format(getString(R.string.drawer_unavailable_free_storage), DisplayUtils.bytesToHumanReadable(userQuota.getUsed(),this)) ); } else if (userQuota.getFree() == 0) { accountQuotaBar.setVisibility(View.GONE); accountQuotaText.setText(getString(R.string.drawer_unavailable_used_storage)); } else { accountQuotaBar.setVisibility(View.VISIBLE); accountQuotaBar.setProgress((int) Math.ceil(userQuota.getRelative())); accountQuotaText.setText( String.format(getString(R.string.drawer_quota), DisplayUtils.bytesToHumanReadable(userQuota.getUsed(), this), DisplayUtils.bytesToHumanReadable(userQuota.getTotal(), this), userQuota.getRelative() ) ); } } }
Source:
<code>public void pictureConversionsAlwaysHaveExtensions() throws IOException { DocumentModel picture = session.createDocumentModel("/", "picture", "Picture"); Blob blob = Blobs.createBlob(FileUtils.getResourceFileFromContext("images/cat.gif")); blob.setFilename("Cat.gif"); blob.setMimeType("image/gif"); picture.setPropertyValue("file:content", (Serializable) blob); picture = session.createDocument(picture); txFeature.nextTransaction(); eventService.waitForAsyncCompletion(); MultiviewPicture multiviewPicture = picture.getAdapter(MultiviewPicture.class); for (PictureView pictureView : multiviewPicture.getViews()) { <START> assertEquals("jpg", FilenameUtils.getExtension(pictureView.getFilename())); <END> assertTrue(StringUtils.containsIgnoreCase(pictureView.getFilename(), "cat")); } }</code><technical_language>assert number of views, if 0 testing anything</technical_language>

Target:
public void pictureConversionsAlwaysHaveExtensions() throws IOException { DocumentModel picture = session.createDocumentModel("/", "picture", "Picture"); Blob blob = Blobs.createBlob(FileUtils.getResourceFileFromContext("images/cat.gif")); blob.setFilename("Cat.gif"); blob.setMimeType("image/gif"); picture.setPropertyValue("file:content", (Serializable) blob); picture = session.createDocument(picture); txFeature.nextTransaction(); eventService.waitForAsyncCompletion(); MultiviewPicture multiviewPicture = picture.getAdapter(MultiviewPicture.class); assertEquals(5, multiviewPicture.getViews().length); for (PictureView pictureView : multiviewPicture.getViews()) { assertEquals("jpg", FilenameUtils.getExtension(pictureView.getFilename())); assertTrue(StringUtils.containsIgnoreCase(pictureView.getFilename(), "cat")); } }
Source:
<code>protected Integer getGlobalDefaultNfsVersion(){ ConfigurationVO globalNfsVersion = configurationDao.findByName(CapacityManager.ImageStoreNFSVersion.key()); <START> String value = globalNfsVersion.getValue(); <END> return (value != null ? Integer.valueOf(value) : null); }</code><technical_language>if globalNfsVersion is null</technical_language>

Target:
protected Integer getGlobalDefaultNfsVersion(){ ConfigurationVO globalNfsVersion = configurationDao.findByName(CapacityManager.ImageStoreNFSVersion.key()); Preconditions.checkState(globalNfsVersion != null, "Unable to find global NFS version for version key " + CapacityManager.ImageStoreNFSVersion.key()); String value = globalNfsVersion.getValue(); return (value != null ? Integer.valueOf(value) : null); }
Source:
<code>protected String getVirtioIsoPath() { String virtioIsoName = getParameters().getVirtioIsoName(); if (virtioIsoName != null) { DiskImage diskImage; <START> if (!virtioIsoName.contains(".iso") && virtioIsoName.split("-").length == 5 && <END> (diskImage = diskImageDao.getDiskImageByDiskId(Guid.createGuidFromString(virtioIsoName))) != null && diskImage.getContentType() == DiskContentType.ISO) { return vmInfoBuildUtils.getFullyQualifiedPathToImage(diskImage); } else { return new File(getIsoPrefix(getStoragePoolId(), getVdsId()), virtioIsoName).getPath(); } } return null; }</code><technical_language>Is this a workaround for bug <LINK_0> This break bug is fixed. wise fix bug 1721443 first</technical_language>

Target:
protected String getVirtioIsoPath() { String virtioIsoName = getParameters().getVirtioIsoName(); if (virtioIsoName != null) { DiskImage diskImage; if (vmInfoBuildUtils.isValidUUID(virtioIsoName) && (diskImage = diskImageDao.getDiskImageByDiskId(Guid.createGuidFromString(virtioIsoName))) != null && diskImage.getContentType() == DiskContentType.ISO) { return vmInfoBuildUtils.getFullyQualifiedPathToImage(diskImage); } else { return new File(getIsoPrefix(getStoragePoolId(), getVdsId()), virtioIsoName).getPath(); } } return null; }
Source:
<code>private List<UserRepresentation> searchForUser(Map<String, String> attributes, RealmModel realm, UserPermissionEvaluator usersEvaluator, Boolean briefRepresentation, Integer firstResult, Integer maxResults, Boolean includeServiceAccounts) { session.setAttribute(UserModel.INCLUDE_SERVICE_ACCOUNT, includeServiceAccounts); if (!auth.users().canView()) { Set<String> groupModels = auth.groups().getGroupsWithViewPermission(); if (!groupModels.isEmpty()) { try { <START> session.setAttribute(UserModel.GROUPS, JsonSerialization.writeValueAsPrettyString(groupModels)); <END> } catch (IOException cause) { throw new RuntimeException("Failed to create groups filter", cause); } } } List<UserModel> userModels = session.users().searchForUser(attributes, realm, firstResult, maxResults); return toRepresentation(realm, usersEvaluator, briefRepresentation, userModels); }</code><technical_language>Please groupModels directly, serialization</technical_language>

Target:
private List<UserRepresentation> searchForUser(Map<String, String> attributes, RealmModel realm, UserPermissionEvaluator usersEvaluator, Boolean briefRepresentation, Integer firstResult, Integer maxResults, Boolean includeServiceAccounts) { session.setAttribute(UserModel.INCLUDE_SERVICE_ACCOUNT, includeServiceAccounts); if (!auth.users().canView()) { Set<String> groupModels = auth.groups().getGroupsWithViewPermission(); if (!groupModels.isEmpty()) { session.setAttribute(UserModel.GROUPS, groupModels); } } List<UserModel> userModels = session.users().searchForUser(attributes, realm, firstResult, maxResults); return toRepresentation(realm, usersEvaluator, briefRepresentation, userModels); }
Source:
<code>void onPrev(ClickEvent event) { <START> GQuery.console.info("prev"); <END> prev(); }</code><technical_language>Do want remove debug</technical_language>

Target:
void onPrev(ClickEvent event) { prev(); }
Source:
<code>public boolean hasPushTask() { <START> taskLock.lock(); <END> try { if (totalPushCount == 0) { return false; } } finally { taskLock.unlock(); } return true; }</code><technical_language>reading a single field, do need lock</technical_language>

Target:
public boolean hasPushTask() { return totalPushCount != 0; }
Source:
<code>public EList<Widget> renderWidget(Widget w, StringBuilder sb) throws RenderException { Image image = (Image) w; String snippet = (image.getChildren().size() > 0) ? getSnippet("image_link") : getSnippet("image"); if (image.getRefresh() > 0) { snippet = StringUtils.replace(snippet, "%update_interval%", Integer.toString(image.getRefresh())); } else { snippet = StringUtils.replace(snippet, "%update_interval%", "0"); } String widgetId = itemUIRegistry.getWidgetId(w); snippet = StringUtils.replace(snippet, "%id%", widgetId); snippet = preprocessSnippet(snippet, w); String sitemap = w.eResource().getURI().path(); State state = itemUIRegistry.getState(w); String url = (state instanceof RawType) ? state.toFullString() <START> : ("../proxy?sitemap=" + sitemap + "&amp;widgetId=" + widgetId + "&amp;t=" + (new Date()).getTime()); <END> snippet = StringUtils.replace(snippet, "%url%", url); sb.append(snippet); return null; }</code><technical_language>While this works for now, support require adding classes image element handled in javascript</technical_language>

Target:
public EList<Widget> renderWidget(Widget w, StringBuilder sb) throws RenderException { Image image = (Image) w; String snippet = (image.getChildren().size() > 0) ? getSnippet("image_link") : getSnippet("image"); if (image.getRefresh() > 0) { snippet = StringUtils.replace(snippet, "%update_interval%", Integer.toString(image.getRefresh())); } else { snippet = StringUtils.replace(snippet, "%update_interval%", "0"); } String widgetId = itemUIRegistry.getWidgetId(w); snippet = StringUtils.replace(snippet, "%id%", widgetId); snippet = preprocessSnippet(snippet, w); String sitemap = null; if (w.eResource() != null) { sitemap = w.eResource().getURI().path(); } boolean validUrl = false; if (image.getUrl() != null && !image.getUrl().isEmpty()) { try { URI.create(image.getUrl()); validUrl = true; } catch (IllegalArgumentException ex) { } } String proxiedUrl = "../proxy?sitemap=" + sitemap + "&amp;widgetId=" + widgetId; State state = itemUIRegistry.getState(w); String url; if (state instanceof RawType) { url = state.toFullString(); } else if ((sitemap != null) && ((state instanceof StringType) || validUrl)) { url = proxiedUrl + "&amp;t=" + (new Date()).getTime(); } else { url = "images/none.png"; } snippet = StringUtils.replace(snippet, "%valid_url%", validUrl ? "true" : "false"); snippet = StringUtils.replace(snippet, "%proxied_url%", proxiedUrl); snippet = StringUtils.replace(snippet, "%url%", url); sb.append(snippet); return null; }
Source:
<code>public long takeSnapshot() throws IOException { TermIndex ti = getLastAppliedTermIndex(); long startTime = Time.monotonicNow(); <START> SingleFileSnapshotInfo lastSnapshot = storage.findLatestSnapshot(); <END> if (ti != null && ti.getIndex() != RaftLog.INVALID_LOG_INDEX) { final File snapshotFile = storage.getSnapshotFile(ti.getTerm(), ti.getIndex()); LOG.info("{}: Taking a snapshot at:{} file {}", gid, ti, snapshotFile); try (FileOutputStream fos = new FileOutputStream(snapshotFile)) { persistContainerSet(fos); fos.flush(); fos.getFD().sync(); if (lastSnapshot != null && lastSnapshot.getFile() != null) { Path lastSnapshotFile = lastSnapshot.getFile().getPath(); LOG.info("Deleting last snapshot at ", lastSnapshotFile.toString()); FileUtils.deleteQuietly(lastSnapshotFile.toFile()); } } catch (IOException ioe) { LOG.info("{}: Failed to write snapshot at:{} file {}", gid, ti, snapshotFile); throw ioe; } LOG.info("{}: Finished taking a snapshot at:{} file:{} time:{}", gid, ti, snapshotFile, (Time.monotonicNow() - startTime)); return ti.getIndex(); } return -1; }</code><technical_language>this deletes 1 previous snapshot, older latest</technical_language>

Target:
public long takeSnapshot() throws IOException { TermIndex ti = getLastAppliedTermIndex(); long startTime = Time.monotonicNow(); if (!isStateMachineHealthy.get()) { String msg = "Failed to take snapshot " + " for " + gid + " as the stateMachine" + " is unhealthy. The last applied index is at " + ti; StateMachineException sme = new StateMachineException(msg); LOG.error(msg); throw sme; } if (ti != null && ti.getIndex() != RaftLog.INVALID_LOG_INDEX) { final File snapshotFile = storage.getSnapshotFile(ti.getTerm(), ti.getIndex()); LOG.info("{}: Taking a snapshot at:{} file {}", gid, ti, snapshotFile); try (FileOutputStream fos = new FileOutputStream(snapshotFile)) { persistContainerSet(fos); fos.flush(); fos.getFD().sync(); } catch (IOException ioe) { LOG.error("{}: Failed to write snapshot at:{} file {}", gid, ti, snapshotFile); throw ioe; } LOG.info("{}: Finished taking a snapshot at:{} file:{} time:{}", gid, ti, snapshotFile, (Time.monotonicNow() - startTime)); return ti.getIndex(); } return -1; }
Source:
<code>public RebaseOperation(Repository repository, Operation operation) { <START> Assert.isTrue(operation != Operation.BEGIN); <END> this.repository = repository; this.operation = operation; this.ref = null; }</code><technical_language>this ? claim this is a refactoring</technical_language>

Target:
public RebaseOperation(Repository repository, Operation operation) { this.repository = repository; this.operation = operation; this.ref = null; }
Source:
<code>public String getOptionsString() { StringBuilder command = new StringBuilder(); command.append("-a ").append(host); if (logPath != null) { command.append(" -l ").append(logPath); } else { command.append(" -m"); } if (single) { command.append(" -s"); } if (logSizeQuota != null) { <START> command.append(" --log-size-quota-percentage ").append(logSizeQuota); <END> } if (tlsEnabled) { command.append(" -e"); if (keyStore != null) { command.append(" -u ").append(keyStore); } if (keyStorePassword != null) { command.append(" -f ").append(keyStorePassword); } if (trustStore != null) { command.append(" -r ").append(trustStore); } if (trustStorePassword != null) { command.append(" -w ").append(trustStorePassword); } } command.append(" -d ").append(logLevel).append(" ") .append(port); return command.toString(); }</code><technical_language>logSizeQuota -> logSizeLimitPercentage</technical_language>

Target:
public String getOptionsString() { StringBuilder command = new StringBuilder(); command.append("-a ").append(host); if (logPath != null) { command.append(" -l ").append(logPath); } else { command.append(" -m"); } if (single) { command.append(" -s"); } if (logSizeLimitPercentage != null) { command.append(" --log-size-quota-percentage ").append(logSizeLimitPercentage); } if (tlsEnabled) { command.append(" -e"); if (keyStore != null) { command.append(" -u ").append(keyStore); } if (keyStorePassword != null) { command.append(" -f ").append(keyStorePassword); } if (trustStore != null) { command.append(" -r ").append(trustStore); } if (trustStorePassword != null) { command.append(" -w ").append(trustStorePassword); } } command.append(" -d ").append(logLevel).append(" ") .append(port); return command.toString(); }
Source:
<code>public void backfillEvent(EmittedEventEntity event) { try { Optional<ChargeEntity> charge = Optional.empty(); if (ResourceType.valueOf(event.getResourceType().toUpperCase()).equals(ResourceType.PAYMENT)) { charge = Optional.of(chargeService.findChargeByExternalId(event.getResourceExternalId())); } else { Optional<RefundEntity> refundEntity = refundDao.findByExternalId(event.getResourceExternalId()) .stream() .findFirst(); if (refundEntity.isPresent()) { charge = Optional.ofNullable(chargeService.findChargeByExternalId(refundEntity.get().getChargeExternalId())); } } charge.ifPresent(c -> MDC.put("chargeId", c.getExternalId())); charge.ifPresent(historicalEventEmitter::processPaymentAndRefundEvents); event.setEmittedDate(now(ZoneId.of("UTC"))); } catch (Exception e) { <START> logger.error( <END> "Failed to process backfill for event due to [externalId={}] [event_type={}] [event_date={}]", event.getId(), e.getMessage(), event.getResourceExternalId(), event.getEventType(), event.getEventDate() ); } finally { MDC.remove("chargeId"); } }</code><technical_language>fine catching exception means task end HTTP status 200 instead of 500 / else. throw exception send relevant HTTP status if is exception</technical_language>

Target:
public void backfillEvent(EmittedEventEntity event) { try { Optional<ChargeEntity> charge = Optional.empty(); if (ResourceType.valueOf(event.getResourceType().toUpperCase()).equals(ResourceType.PAYMENT)) { charge = Optional.of(chargeService.findChargeByExternalId(event.getResourceExternalId())); } else { Optional<RefundEntity> refundEntity = refundDao.findByExternalId(event.getResourceExternalId()) .stream() .findFirst(); if (refundEntity.isPresent()) { charge = Optional.ofNullable(chargeService.findChargeByExternalId(refundEntity.get().getChargeExternalId())); } } charge.ifPresent(c -> MDC.put("chargeId", c.getExternalId())); charge.ifPresent(historicalEventEmitter::processPaymentAndRefundEvents); event.setEmittedDate(now(ZoneId.of("UTC"))); } catch (Exception e) { logger.error( "Failed to process backfill for event due to [externalId={}] [event_type={}] [event_date={}]", event.getId(), e.getMessage(), event.getResourceExternalId(), event.getEventType(), event.getEventDate() ); throw e; } finally { MDC.remove("chargeId"); } }
Source:
<code>public ParserProperties withUsageWidth(int usageWidth) { if (usageWidth < 0) throw new IllegalArgumentException("Usage width is negative"); if (this.usageWidth == usageWidth) return this; <START> return new ParserProperties(usageWidth, this.shouldSortOptions); <END> }</code><technical_language>This a builder pattern in combination fluent interface some kind of immutable class pattern. immutable class more complicated class grows. setter a big constructor call. Is necessary</technical_language>

Target:
public ParserProperties withUsageWidth(int usageWidth) { if (usageWidth < 0) throw new IllegalArgumentException("Usage width is negative"); this.usageWidth = usageWidth; return this; }
Source:
<code>static Text decode(String s) { Text t = new Text(); byte[] sb = s.getBytes(UTF_8); for (int i = 0; i < sb.length; i++) { if (sb[i] != '%') { t.append(new byte[] {sb[i]}, 0, 1); } else { <START> i++; <END> if (i < sb.length) { byte hex[] = {sb[i], sb[i]}; String hs = new String(hex, UTF_8); int b = Integer.parseInt(hs, 16); t.append(new byte[]{(byte) b}, 0, 1); } } } return t; }</code><technical_language>change equivalent. java int x = ++i; int y = ++i; if (y < sb.length) { byte hex[] = {sb[x], sb[y]}; String hs = new String(hex, UTF_8); int b = Integer.parseInt(hs, 16); t.append(new byte[]{(byte) b}, 0, 1); }</technical_language>

Target:
static Text decode(String s) { Text t = new Text(); byte[] sb = s.getBytes(UTF_8); for (int i = 0; i < sb.length; i++) { if (sb[i] != '%') { t.append(new byte[] {sb[i]}, 0, 1); } else { int x = ++i; int y = ++i; if (y < sb.length) { byte[] hex = {sb[x], sb[y]}; String hs = new String(hex, UTF_8); int b = Integer.parseInt(hs, 16); t.append(new byte[] {(byte) b}, 0, 1); } else { throw new IllegalArgumentException("Invalid characters in encoded string (" + s + ")." + " Expected two characters after '%'"); } } } return t; }
Source:
<code>public static void main(String[] args) { Unit unit = new SoldierUnit("SoldierUnit1"); Unit unit1 = new SergeantUnit("SergeantUnit1"); <START> Unit unit2 = new CommanderUnit("CommanderUnit1"); <END> checkExtensionsForUnit(unit); checkExtensionsForUnit(unit1); checkExtensionsForUnit(unit2); }</code><technical_language>Instead of unit, unit1 unit2 soldierUnit, sergeantUnit commanderUnit</technical_language>

Target:
public static void main(String[] args) { Unit soldierUnit = new SoldierUnit("SoldierUnit1"); Unit sergeantUnit = new SergeantUnit("SergeantUnit1"); Unit commanderUnit = new CommanderUnit("CommanderUnit1"); checkExtensionsForUnit(soldierUnit); checkExtensionsForUnit(sergeantUnit); checkExtensionsForUnit(commanderUnit); }
Source:
<code>public IndexedInts getBitmapIndex(String dimension, int dictId) { final Column column = input.getColumn(dimension); if (column == null) { return new EmptyIndexedInts(); } final BitmapIndex bitmaps = column.getBitmapIndex(); if (bitmaps == null) { return new EmptyIndexedInts(); } if (dictId >= 0) { return new BitmapCompressedIndexedInts(bitmaps.getBitmap(dictId)); } else { <START> return new EmptyIndexedInts(); <END> } }</code><technical_language>I EmptyIndexedInts a singleton, a static final instance, that? arg constructor in class private</technical_language>

Target:
public IndexedInts getBitmapIndex(String dimension, int dictId) { final Column column = input.getColumn(dimension); if (column == null) { return EmptyIndexedInts.EMPTY_INDEXED_INTS; } final BitmapIndex bitmaps = column.getBitmapIndex(); if (bitmaps == null) { return EmptyIndexedInts.EMPTY_INDEXED_INTS; } if (dictId >= 0) { return new BitmapCompressedIndexedInts(bitmaps.getBitmap(dictId)); } else { return EmptyIndexedInts.EMPTY_INDEXED_INTS; } }
Source:
<code>public static String getHostName() throws IOException { Process p = Runtime.getRuntime().exec("hostname"); try { BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); return reader.readLine(); } finally { try { <START> int result = p.waitFor(); <END> if (result != 0) throw new IOException("Non-zero return from hostname process: " + result); } catch (InterruptedException e) { throw new IOException(e); } } }</code><technical_language>do this in finally call readLine? If readling throws exception, want stack trace opposed non-zero return</technical_language>

Target:
public static String getHostName() throws IOException { Process p = Runtime.getRuntime().exec("hostname"); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String result = reader.readLine(); try { int exitCode = p.waitFor(); if (exitCode != 0) { throw new IOException("Non-zero return from hostname process: " + result); } } catch (InterruptedException e) { throw new IOException(e); } return result; }
Source:
<code>public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setOnItemLongClickListener( <START> new LongClickDeleteListener(activity, new LongClickDeleteListener.OnDeleteListener() { <END> @Override public void onDelete(int position) { if (getListView().getItemAtPosition(position) == null) { return; } } @Override public boolean shouldDelete(int position) { return false; }})); }</code><technical_language>this part merged correctly? implementation in master is different</technical_language>

Target:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setOnItemLongClickListener(new LongClickDeleteListener(activity, new LongClickDeleteListener.OnDeleteListener() { @Override public void onDelete(int position) { showDeleteAlertDialog(position); } @Override public boolean shouldDelete(int position) { return true; } })); }
Source:
<code>private boolean pageDenotesContentConsumption(WebrequestData data){ boolean contentConsumption = true; if (data.getRawXAnalyticsHeader().isEmpty()) return contentConsumption; String special = Utilities.getValueForKey(data.getRawXAnalyticsHeader(), "special").trim(); String preview = Utilities.getValueForKey(data.getRawXAnalyticsHeader(), "preview").trim(); if (preview.isEmpty() && special.isEmpty()){ return contentConsumption; } Set<String> specialPagesAccepted = new HashSet<String>(); <START> specialPagesAccepted.add("Search") ; <END> specialPagesAccepted.add("RecentChanges"); specialPagesAccepted.add("Version"); if (preview.equalsIgnoreCase("1")) contentConsumption = false; if ( !special.isEmpty() ) { contentConsumption = false; Iterator it = specialPagesAccepted.iterator(); while (it.hasNext()) { String item = (String) it.next(); if (special.equalsIgnoreCase(item)){ contentConsumption = true; break; } } } return contentConsumption; }</code><technical_language>This static list moved top of class for visibility. If list items created lowercase, get rid of comparison loop instead: if (specialPagesAccepted.contains(special.toLowerCase())) return true;</technical_language>

Target:
private boolean pageDenotesContentConsumption(WebrequestData data){ if (data.getRawXAnalyticsHeader().isEmpty()) return true; String special = Utilities.getValueForKey(data.getRawXAnalyticsHeader(), "special").trim(); String preview = Utilities.getValueForKey(data.getRawXAnalyticsHeader(), "preview").trim(); if (preview.isEmpty() && special.isEmpty()){ return true; } else if (preview.equalsIgnoreCase("1")) { return false; } if ( !special.isEmpty() ) { Iterator it = SPECIAL_PAGES_ACCEPTED.iterator(); while (it.hasNext()) { String item = (String) it.next(); if (item.equals(special.toLowerCase())){ return true; } } } return false; }
Source:
<code>private void adjustStreamStoreScores(TableReference valueTable, @Output Map<TableReference, Double> scores, Map<TableReference, SweepPriority> tableToSweepPriority) { TableReference indexTable = StreamTableType.getIndexTableFromValueTable(valueTable); if (!scores.containsKey(indexTable)) { return; } long lastSweptTimeOfValueTable = getLastSweptTime(valueTable, tableToSweepPriority); long lastSweptTimeOfIndexTable = getLastSweptTime(indexTable, tableToSweepPriority); if (lastSweptTimeOfValueTable >= lastSweptTimeOfIndexTable) { <START> bumpIndexTableAndIgnoreValueTable(valueTable, indexTable, scores); <END> } else if (System.currentTimeMillis() - lastSweptTimeOfIndexTable <= INDEX_TO_VALUE_TABLE_SLEEP_TIME) { doNotSweepTable(valueTable, scores); doNotSweepTable(indexTable, scores); } else { } }</code><technical_language>nit: this reads a awkwardly of parameter ordering (I'd prefer bumpIndexAndIgnoreValue(index, value, scores);)</technical_language>

Target:
private void adjustStreamStoreScores(TableReference valueTable, @Output Map<TableReference, Double> scores, Map<TableReference, SweepPriority> tableToSweepPriority) { TableReference indexTable = StreamTableType.getIndexTableFromValueTable(valueTable); if (!scores.containsKey(indexTable)) { return; } long lastSweptTimeOfValueTable = getLastSweptTime(valueTable, tableToSweepPriority); long lastSweptTimeOfIndexTable = getLastSweptTime(indexTable, tableToSweepPriority); if (lastSweptTimeOfValueTable >= lastSweptTimeOfIndexTable) { scores.put(indexTable, scores.get(valueTable)); doNotSweepTable(valueTable, scores); } else if (System.currentTimeMillis() - lastSweptTimeOfIndexTable <= INDEX_TO_VALUE_TABLE_SLEEP_TIME) { doNotSweepTable(valueTable, scores); doNotSweepTable(indexTable, scores); } else { } }
Source:
<code>public FeatureSelectionDialog(Shell shell, AboutInfo[] features, String primaryFeatureId, String shellTitle, String shellMessage, String helpContextId) { super(shell); if (features == null || features.length == 0) { throw new IllegalArgumentException(); } this.features = features; this.helpContextId = helpContextId; setTitle(shellTitle); setMessage(shellMessage); Arrays.sort(features, new Comparator<AboutInfo>() { Collator coll = Collator.getInstance(Locale.getDefault()); @Override public int compare(AboutInfo i1, AboutInfo i2) { String name1, name2; name1 = i1.getFeatureLabel(); name2 = i2.getFeatureLabel(); if (name1 == null) { name1 = ""; } if (name2 == null) { name2 = ""; } return coll.compare(name1, name2); } }); for (AboutInfo feature : features) { if (feature.getFeatureId().equals(primaryFeatureId)) { setInitialSelection(feature); return; } } <START> setInitialSelection(Collections.emptyList()); <END> }</code><technical_language>Setting empty initial selection is necessary more</technical_language>

Target:
public FeatureSelectionDialog(Shell shell, AboutInfo[] features, String primaryFeatureId, String shellTitle, String shellMessage, String helpContextId) { super(shell); if (features == null || features.length == 0) { throw new IllegalArgumentException(); } this.features = features; this.helpContextId = helpContextId; setTitle(shellTitle); setMessage(shellMessage); Arrays.sort(features, new Comparator<AboutInfo>() { Collator coll = Collator.getInstance(Locale.getDefault()); @Override public int compare(AboutInfo i1, AboutInfo i2) { String name1, name2; name1 = i1.getFeatureLabel(); name2 = i2.getFeatureLabel(); if (name1 == null) { name1 = ""; } if (name2 == null) { name2 = ""; } return coll.compare(name1, name2); } }); for (AboutInfo feature : features) { if (feature.getFeatureId().equals(primaryFeatureId)) { setInitialSelection(feature); return; } } }
Source:
<code>public void testMalformedTopicString () { <START> assertNull(registry.getSchemaNameFromTopic("badTopicName")); <END> }</code><technical_language>This code throw exception is recover a poorly configured topic</technical_language>

Target:
public void testMalformedTopicString () { assertNull(registry.getSchemaNameFromTopic("badTopicName")); registry.getLatestSchemaByTopic("badTopicName"); }
Source:
<code>private void replaceContextParameters(Properties properties) { InterpreterContext interpreterContext = InterpreterContext.get(); if (interpreterContext != null) { String markerTemplate = "#\\{%s\\}"; List<String> skipFields = Arrays.asList("paragraphTitle", "paragraphId", "paragraphText"); List typesToProcess = Arrays.asList(String.class, Double.class, Float.class, Short.class, Byte.class, Character.class, Boolean.class, Integer.class, Long.class); for (String key : properties.stringPropertyNames()) { String p = properties.getProperty(key); if (StringUtils.isNotEmpty(p)) { for (Field field : InterpreterContext.class.getDeclaredFields()) { Class clazz = field.getType(); if (!skipFields.contains(field.getName()) && (typesToProcess.contains(clazz) || clazz.isPrimitive())) { try { Object value = FieldUtils.readField(field, interpreterContext, true); p = p.replaceAll(String.format(markerTemplate, field.getName()), value != null ? value.toString() : StringUtils.EMPTY); } catch (Exception e) { <START> logger.error("Cannot replace context parameter", e); <END> } } } p = p.replaceAll(String.format(markerTemplate, "user"), StringUtils.defaultString(userName, StringUtils.EMPTY)); properties.setProperty(key, p); } } } }</code><technical_language>stop continue #{name} in if find a match</technical_language>

Target:
private void replaceContextParameters(Properties properties) { InterpreterContext interpreterContext = InterpreterContext.get(); if (interpreterContext != null) { String markerTemplate = "#\\{%s\\}"; List<String> skipFields = Arrays.asList("paragraphTitle", "paragraphId", "paragraphText"); List typesToProcess = Arrays.asList(String.class, Double.class, Float.class, Short.class, Byte.class, Character.class, Boolean.class, Integer.class, Long.class); for (String key : properties.stringPropertyNames()) { String p = properties.getProperty(key); if (StringUtils.isNotEmpty(p)) { for (Field field : InterpreterContext.class.getDeclaredFields()) { Class clazz = field.getType(); if (!skipFields.contains(field.getName()) && (typesToProcess.contains(clazz) || clazz.isPrimitive())) { Object value = null; try { value = FieldUtils.readField(field, interpreterContext, true); } catch (Exception e) { logger.error("Cannot read value of field {0}", field.getName()); } p = p.replaceAll(String.format(markerTemplate, field.getName()), value != null ? value.toString() : StringUtils.EMPTY); } } p = p.replaceAll(String.format(markerTemplate, "user"), StringUtils.defaultString(userName, StringUtils.EMPTY)); properties.setProperty(key, p); } } } }
Source:
<code><START> public void testBinaryFunctionsParsingUnsuccessful() throws Exception { <END> for (String function : binaryFunctions) { testFunctionParsingUnsuccessful(function, failingBinaryFunctionExpressions); } }</code><technical_language>Exception is thrown in method</technical_language>

Target:
public void testBinaryFunctionsParsingUnsuccessful() { for (String function : binaryFunctions) { testFunctionParsingUnsuccessful(function, failingBinaryFunctionExpressions); } }
Source:
<code>private void updateFormRelevancies(){ saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); if(!(mCurrentView instanceof ODKView)){ throw new RuntimeException("Tried to update form relevancy not on compound view"); } <START> ODKView oldODKV = (ODKView)mCurrentView; <END> ArrayList<QuestionWidget> oldWidgets = oldODKV.getWidgets(); ArrayList<Vector<SelectChoice>> oldSelectChoices = getOldSelectChoicesForEachWidget(oldWidgets); ArrayList<String> oldQuestionTexts = getOldQuestionTextsForEachWidget(oldWidgets); FormEntryPrompt[] newValidPrompts = mFormController.getQuestionPrompts(); Set<FormEntryPrompt> leftInOldList = new HashSet<>(); ArrayList<Integer> removeList = new ArrayList<>(); for (int i = 0; i < oldWidgets.size(); i++){ FormEntryPrompt oldPrompt = oldWidgets.get(i).getPrompt(); String priorQuestionTextForThisWidget = oldQuestionTexts.get(i); Vector<SelectChoice> priorSelectChoicesForThisWidget = oldSelectChoices.get(i); boolean stillRelevant = false; for (FormEntryPrompt newPrompt : newValidPrompts) { if (newPrompt.getIndex().equals(oldPrompt.getIndex()) && newPrompt.hasSameDisplayContent(priorQuestionTextForThisWidget, priorSelectChoicesForThisWidget)) { stillRelevant = true; leftInOldList.add(newPrompt); break; } } if (!stillRelevant) { removeList.add(i); } } oldODKV.removeQuestionsFromIndex(removeList); for (int i = 0; i < newValidPrompts.length; ++i) { FormEntryPrompt prompt = newValidPrompts[i]; if (!leftInOldList.contains(prompt)) { oldODKV.addQuestionToIndex(prompt, mFormController.getWidgetFactory(), i); } } }</code><technical_language>this variable name feels a misnomer this is current view</technical_language>

Target:
private void updateFormRelevancies(){ saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); if(!(mCurrentView instanceof ODKView)){ throw new RuntimeException("Tried to update form relevancy not on compound view"); } ODKView odkView = (ODKView)mCurrentView; ArrayList<QuestionWidget> oldWidgets = odkView.getWidgets(); ArrayList<Vector<SelectChoice>> oldSelectChoices = getOldSelectChoicesForEachWidget(oldWidgets); ArrayList<String> oldQuestionTexts = getOldQuestionTextsForEachWidget(oldWidgets); FormEntryPrompt[] newValidPrompts = mFormController.getQuestionPrompts(); Set<FormEntryPrompt> promptsLeftInView = new HashSet<>(); ArrayList<Integer> shouldRemoveFromView = new ArrayList<>(); for (int i = 0; i < oldWidgets.size(); i++){ FormEntryPrompt oldPrompt = oldWidgets.get(i).getPrompt(); String priorQuestionTextForThisWidget = oldQuestionTexts.get(i); Vector<SelectChoice> priorSelectChoicesForThisWidget = oldSelectChoices.get(i); FormEntryPrompt equivalentNewPrompt = getEquivalentPromptInNewList(newValidPrompts, oldPrompt, priorQuestionTextForThisWidget, priorSelectChoicesForThisWidget); if (equivalentNewPrompt != null) { promptsLeftInView.add(equivalentNewPrompt); } else { shouldRemoveFromView.add(i); } } odkView.removeQuestionsFromIndex(shouldRemoveFromView); for (int i = 0; i < newValidPrompts.length; ++i) { FormEntryPrompt prompt = newValidPrompts[i]; if (!promptsLeftInView.contains(prompt)) { odkView.addQuestionToIndex(prompt, mFormController.getWidgetFactory(), i); } } }
Source:
<code>protected String getOwnerEmail(InstanceGroup group) { String propEmailGlobalReceiver = String.format("simianarmy.chaos.notification.global.receiverEmail"); <START> if (cfg.getStr(propEmailGlobalReceiver) != null) { <END> return cfg.getStr(propEmailGlobalReceiver); } String prop = String.format("simianarmy.chaos.%s.%s.ownerEmail", group.type(), group.name()); String ownerEmail = cfg.getStr(prop); if (ownerEmail == null) { LOGGER.info(String.format("Property %s is not set, use the default email address %s as" + " the owner email of group %s of type %s", prop, defaultEmail, group.name(), group.type())); return defaultEmail; } else { return ownerEmail; } }</code><technical_language>change '!= null' StringUtils.notBlank()? This prevent accidentally setting global email empty string stops emails sent</technical_language>

Target:
protected String getOwnerEmail(InstanceGroup group) { String prop = String.format("simianarmy.chaos.%s.%s.ownerEmail", group.type(), group.name()); String ownerEmail = cfg.getStr(prop); if (ownerEmail == null) { LOGGER.info(String.format("Property %s is not set, use the default email address %s as" + " the owner email of group %s of type %s", prop, defaultEmail, group.name(), group.type())); return defaultEmail; } else { return ownerEmail; } }
Source:
<code>private String encode(final String value) throws Exception { <START> return URLEncoder.encode(value, "UTF-8"); <END> }</code><technical_language>I recommendation is constant: StandardCharsets.UTF_8</technical_language>

Target:
private String encode(final String value) throws Exception { return URLEncoder.encode(value, StandardCharsets.UTF_8); }