auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void findReferences(CompositeChange compositeChange, IProgressMonitor monitor) { String pointId = getId(); IPluginModelBase[] bases = PDECore.getDefault().getExtensionsRegistry().findExtensionPlugins(pointId, true); <START> SubMonitor subMonitor = SubMonitor.convert(monitor, "", bases.length); END> for (int i = 0; i < bases.length; i++) { IFile file = getModificationFile(bases[i]); if (file != null) compositeChange.addAll(PDEModelUtility.changesForModelModication(getExtensionModification(file), subMonitor.newChild(1))); } }</code><technical_language>parameter constructor</technical_language>

Target:
private void findReferences(CompositeChange compositeChange, IProgressMonitor monitor) { String pointId = getId(); IPluginModelBase[] bases = PDECore.getDefault().getExtensionsRegistry().findExtensionPlugins(pointId, true); SubMonitor subMonitor = SubMonitor.convert(monitor, bases.length); for (int i = 0; i < bases.length; i++) { IFile file = getModificationFile(bases[i]); if (file != null) { compositeChange.addAll(PDEModelUtility.changesForModelModication(getExtensionModification(file), subMonitor.newChild(1))); } subMonitor.setWorkRemaining(bases.length - i); } }
Source:
<code>private void setupDefaultSecurityLabels(KeyExtent extent) { if (extent.isMeta()) { defaultSecurityLabel = new byte[0]; } else { try { ColumnVisibility cv = new ColumnVisibility( tableConfiguration.get(Property.TABLE_DEFAULT_SCANTIME_VISIBILITY)); this.defaultSecurityLabel = cv.getExpression(); } catch (Exception e) { <START> log.error("Error setting up default security label " + e.getMessage(), e); <END> this.defaultSecurityLabel = new byte[0]; } } }</code><technical_language>suggestion log.error("Error setting default security label {}", e.getMessage(), e);</technical_language>

Target:
private void setupDefaultSecurityLabels(KeyExtent extent) { if (extent.isMeta()) { defaultSecurityLabel = new byte[0]; } else { try { ColumnVisibility cv = new ColumnVisibility( tableConfiguration.get(Property.TABLE_DEFAULT_SCANTIME_VISIBILITY)); this.defaultSecurityLabel = cv.getExpression(); } catch (Exception e) { log.error("Error setting up default security label {}", e.getMessage(), e); this.defaultSecurityLabel = new byte[0]; } } }
Source:
<code><START> private DocumentMetadata.Builder handleDatasourceIds(OafEntity oafEntity, DocumentMetadata.Builder metaBuilder) { <END> if (CollectionUtils.isNotEmpty(oafEntity.getCollectedfrom())) { List<CharSequence> datasourceIds = new ArrayList<CharSequence>( oafEntity.getCollectedfrom().size()); for (KeyValue currentCollectedFrom : oafEntity.getCollectedfrom()) { datasourceIds.add(currentCollectedFrom.getKey()); } metaBuilder.setDatasourceIds(datasourceIds); } return metaBuilder; }</code><technical_language>return void</technical_language>

Target:
private static void handleDatasourceIds(OafEntity oafEntity, DocumentMetadata.Builder metaBuilder) { if (CollectionUtils.isNotEmpty(oafEntity.getCollectedfrom())) { List<CharSequence> datasourceIds = oafEntity.getCollectedfrom().stream().map(KeyValue::getKey) .collect(Collectors.toList()); if (!datasourceIds.isEmpty()) { metaBuilder.setDatasourceIds(datasourceIds); } } }
Source:
<code>protected void runOneIteration() { final Instant staleBy = Instant.now().minus(BROKER_OFFSETS_FETCH_INTERVAL); final Set<TopicPartition> partitionsNeedingUpdate = new HashSet<>(); _kafkaPositionTracker._ownedKeys.forEach(((topicPartition, key) -> { @Nullable final KafkaPositionValue value = _kafkaPositionTracker._positions.get(key); if (value != null && (value.getLastBrokerQueriedTime() == null || value.getLastBrokerQueriedTime().isBefore(staleBy))) { partitionsNeedingUpdate.add(topicPartition); } })); try { <START> updatePartitionLeadershipMap(); <END> } catch (Exception e) { LOG.warn("Failed to update the partition leadership map. Using stale leadership data. Reason: {}", e.getMessage()); LOG.debug("Failed to update the partition leadership map. Using stale leadership data.", e); } batchPartitionsByLeader(partitionsNeedingUpdate).forEach(partitionLeaderBatch -> { try { _kafkaPositionTracker.queryBrokerForLatestOffsets(_consumer, partitionLeaderBatch, CONSUMER_REQUEST_TIMEOUT); } catch (Exception e) { LOG.warn("Failed to query latest broker offsets for this leader batch via endOffsets() RPC. Reason: {}", e.getMessage()); LOG.debug("Failed to query latest broker offsets for this leader batch via endOffsets() RPC", e); } }); }</code><technical_language>this is a performance optimization potentially negative performance impact , a config enable/disable this</technical_language>

Target:
protected void runOneIteration() { final Instant staleBy = Instant.now().minus(_brokerOffsetsFetchInterval); final Set<TopicPartition> partitionsNeedingUpdate = new HashSet<>(); _kafkaPositionTracker._ownedKeys.forEach(((topicPartition, key) -> { @Nullable final KafkaPositionValue value = _kafkaPositionTracker._positions.get(key); if (value != null && (value.getLastBrokerQueriedTime() == null || value.getLastBrokerQueriedTime().isBefore(staleBy))) { partitionsNeedingUpdate.add(topicPartition); } })); try { if (_enablePartitionLeadershipCalculation) { Instant calculationStaleBy = Optional.ofNullable(_lastPartitionLeadershipCalculation) .map(lastCalculation -> lastCalculation.plus(_partitionLeadershipCalculationFrequency)) .orElse(Instant.MIN); if (Instant.now().isAfter(calculationStaleBy)) { updatePartitionLeadershipMap(); _lastPartitionLeadershipCalculation = Instant.now(); } } } catch (Exception e) { LOG.warn("Failed to update the partition leadership map. Using stale leadership data. Reason: {}", e.getMessage()); LOG.debug("Failed to update the partition leadership map. Using stale leadership data.", e); } batchPartitionsByLeader(partitionsNeedingUpdate).forEach(partitionLeaderBatch -> { try { _kafkaPositionTracker.queryBrokerForLatestOffsets(_consumer, partitionLeaderBatch, _consumerRequestTimeout); } catch (Exception e) { LOG.warn("Failed to query latest broker offsets for this leader batch via endOffsets() RPC. Reason: {}", e.getMessage()); LOG.debug("Failed to query latest broker offsets for this leader batch via endOffsets() RPC", e); } }); }
Source:
<code>private static boolean isValidFieldName(FieldSpec fieldSpec) { String columnName = fieldSpec.getName(); <START> if (SQL_PARSER_METADATA.isReservedWord(columnName.toUpperCase(Locale.ROOT))) { <END> LOGGER.error("Cannot use SQL reserved word as field name in the schema", columnName); return false; } return true; }</code><technical_language>Locale.ROOT? default (columnName.toUpperCase()) else</technical_language>

Target:
private static boolean isValidFieldName(FieldSpec fieldSpec) { String columnName = fieldSpec.getName(); if (SQL_PARSER_METADATA.isReservedWord(columnName.toUpperCase())) { LOGGER.error("Cannot use SQL reserved word as field name in the schema", columnName); return false; } return true; }
Source:
<code>public boolean attemptReceive() throws IOException { boolean received = false; try { <START> InputStream is = buffer.getInputStream(); <END> if (this.fileReceiver != null) { received = this.fileReceiver.receive(is); } else { MessageFormat format = new MessageFormat(); format.deserialize(is); this.receivedMessage = format.getMessage(); if (!isFileMessage(this.receivedMessage)) { received = true; } else { this.fileReceiver = new FileReceiver((IFileMessage) this.receivedMessage, this.tempFolder); if (is.available() > 0) { received = this.fileReceiver.receive(is); } } } buffer.consume(); if (LogUtil.isLogAvailable()) { if (buffer.size() > 0) { Log.v(TAG, "Residual buffer data: " + buffer.size() + " bytes left in buffer"); } } } catch (MessageNotCompleteException e) { } return received; }</code><technical_language>Reminder change is more descriptive</technical_language>

Target:
public boolean attemptReceive() throws IOException { boolean received = false; try { InputStream input = buffer.getInputStream(); if (this.fileReceiver != null) { received = this.fileReceiver.receive(input); } else { MessageFormat format = new MessageFormat(); format.deserialize(input); this.receivedMessage = format.getMessage(); if (!isFileMessage(this.receivedMessage)) { received = true; } else { this.fileReceiver = new FileReceiver((IFileMessage) this.receivedMessage, this.tempFolder); if (input.available() > 0) { received = this.fileReceiver.receive(input); } } } buffer.consume(); if (LogUtil.isLogAvailable()) { if (buffer.size() > 0) { Log.v(TAG, "Residual buffer data: " + buffer.size() + " bytes left in buffer"); } } } catch (MessageNotCompleteException e) { } return received; }
Source:
<code><START> public void replaceUserCredentialsDataInPollRequest( <END> HttpMessage msg, User user, UnaryOperator<String> bodyEncoder) { if (user != null) { AuthenticationCredentials creds = user.getAuthenticationCredentials(); if (creds instanceof UsernamePasswordAuthenticationCredentials) { Map<String, String> kvMap = new HashMap<>(); kvMap.put( PostBasedAuthenticationMethod.MSG_USER_PATTERN, ((UsernamePasswordAuthenticationCredentials) creds).getUsername()); AuthenticationHelper.replaceUserDataInRequest(msg, kvMap, bodyEncoder); } } }</code><technical_language>static</technical_language>

Target:
public static void replaceUserCredentialsDataInPollRequest( HttpMessage msg, User user, UnaryOperator<String> bodyEncoder) { if (user != null) { AuthenticationCredentials creds = user.getAuthenticationCredentials(); if (creds instanceof UsernamePasswordAuthenticationCredentials) { Map<String, String> kvMap = new HashMap<>(); kvMap.put( PostBasedAuthenticationMethod.MSG_USER_PATTERN, ((UsernamePasswordAuthenticationCredentials) creds).getUsername()); AuthenticationHelper.replaceUserDataInRequest(msg, kvMap, bodyEncoder); } } }
Source:
<code>public List<ScheduledActivity> getScheduledActivities(Study study, ScheduleContext context) { checkNotNull(study); checkNotNull(context); Validate.nonEntityThrowingException(VALIDATOR, context); Map<String, DateTime> events = createEventsMap(context); ScheduleContext updatedContext = new ScheduleContext.Builder().withContext(context).withEvents(events).build(); List<ScheduledActivity> scheduledActivities = scheduleActivitiesForPlans(updatedContext); List<ScheduledActivity> dbActivities = activityDao.getActivities(context.getEndsOn().getZone(), scheduledActivities); Map<String, ScheduledActivity> dbMap = Maps.newHashMap(); for (ScheduledActivity dbActivity : dbActivities) { dbMap.put(dbActivity.getGuid(), dbActivity); } List<ScheduledActivity> saves = performMerge(scheduledActivities, dbMap); activityDao.saveActivities(saves); List<ScheduledActivity> orderedActivities = orderActivities(scheduledActivities, V3_FILTER); String healthCode = context.getCriteriaContext().getHealthCode(); <START> activityEventService.publishActivitiesRetrieved(study, healthCode, DateUtils.getCurrentDateTime()); <END> return orderedActivities; }</code><technical_language>need publish event _before_ schedule them, schedule depends this event. (Same V4.)</technical_language>

Target:
public List<ScheduledActivity> getScheduledActivities(Study study, ScheduleContext context) { checkNotNull(study); checkNotNull(context); Validate.nonEntityThrowingException(VALIDATOR, context); String healthCode = context.getCriteriaContext().getHealthCode(); activityEventService.publishActivitiesRetrieved(study, healthCode, DateUtils.getCurrentDateTime()); Map<String, DateTime> events = createEventsMap(context); ScheduleContext updatedContext = new ScheduleContext.Builder().withContext(context).withEvents(events).build(); List<ScheduledActivity> scheduledActivities = scheduleActivitiesForPlans(updatedContext); List<ScheduledActivity> dbActivities = activityDao.getActivities(context.getEndsOn().getZone(), scheduledActivities); Map<String, ScheduledActivity> dbMap = Maps.newHashMap(); for (ScheduledActivity dbActivity : dbActivities) { dbMap.put(dbActivity.getGuid(), dbActivity); } List<ScheduledActivity> saves = performMerge(scheduledActivities, dbMap); activityDao.saveActivities(saves); return orderActivities(scheduledActivities, V3_FILTER); }
Source:
<code>public void rollback(Xid xid) throws XAException { <START> assertIfRecoveryScanWasStarted(); <END> delegate.rollback(xid); }</code><technical_language>RMERR Is great - bad commit compatible</technical_language>

Target:
public void rollback(Xid xid) throws XAException { delegate.rollback(xid); }
Source:
<code>private void writeGrants(JsonWriter writer) throws IOException { for (ApprovedSite site : approvedSiteRepository.getAll()) { writer.beginObject(); writer.name("id").value(site.getId()); writer.name("accessDate").value(DateUtil.toUTCString(site.getAccessDate())); writer.name("clientId").value(site.getClientId()); writer.name("creationDate").value(DateUtil.toUTCString(site.getCreationDate())); writer.name("timeoutDate").value(DateUtil.toUTCString(site.getTimeoutDate())); writer.name("userId").value(site.getUserId()); writer.name("allowedScopes"); writeNullSafeArray(writer, site.getAllowedScopes()); writer.name("whitelistedSiteId").value(site.getIsWhitelisted() ? site.getWhitelistedSite().getId() : null); <START> writer.endObject(); <END> logger.debug("Wrote grant {}", site.getId()); } logger.info("Done writing grants"); }</code><technical_language>Again, above, this is dropping data floor replacing it. need export approved->token links, change export format this. (The export fields added remove fields this breaking version compatibility.)</technical_language>

Target:
private void writeGrants(JsonWriter writer) throws IOException { for (ApprovedSite site : approvedSiteRepository.getAll()) { writer.beginObject(); writer.name("id").value(site.getId()); writer.name("accessDate").value(DateUtil.toUTCString(site.getAccessDate())); writer.name("clientId").value(site.getClientId()); writer.name("creationDate").value(DateUtil.toUTCString(site.getCreationDate())); writer.name("timeoutDate").value(DateUtil.toUTCString(site.getTimeoutDate())); writer.name("userId").value(site.getUserId()); writer.name("allowedScopes"); writeNullSafeArray(writer, site.getAllowedScopes()); writer.name("whitelistedSiteId").value(site.getIsWhitelisted() ? site.getWhitelistedSite().getId() : null); List<OAuth2AccessTokenEntity> tokens = tokenRepository.getAccessTokensForApprovedSite(site); writer.name("approvedAccessTokens"); writer.beginArray(); for (OAuth2AccessTokenEntity token : tokens) { writer.value(token.getId()); } writer.endArray(); writer.endObject(); logger.debug("Wrote grant {}", site.getId()); } logger.info("Done writing grants"); }
Source:
<code>void kotlinTestWithMethodNameContainingSpecialCharacters() { ExecutionsResult executionsResult = executeTestsForClass( ArbitraryNamingKotlinTestCase.class).getExecutionsResult(); <START> assertThat(executionsResult.getTestsStartedCount()).isEqualTo(2); <END> TestDescriptor testDescriptor1 = executionsResult.getEventsFinished(TestExecutionResult.Status.SUCCESSFUL).get( 0).getTestDescriptor(); assertAll( () -> assertEquals(METHOD_NAME + "()", testDescriptor1.getDisplayName()), () -> assertEquals(METHOD_NAME + "()", testDescriptor1.getLegacyReportingName())); TestDescriptor testDescriptor2 = executionsResult.getEventsFinished(TestExecutionResult.Status.SUCCESSFUL).get( 1).getTestDescriptor(); assertAll( () -> assertEquals("test name ends with parentheses()()", testDescriptor2.getDisplayName()), () -> assertEquals("test name ends with parentheses()()", testDescriptor2.getLegacyReportingName())); }</code><technical_language>getTestFinishedCount() .getTestsStartedCount(). numbers reported equal, meaning of _finished_ _started_ interchangeable. Please provide method in ExecutionsResult meaning spelling. This means leave s Test_s_ out for a future commit/PR</technical_language>

Target:
void kotlinTestWithMethodNameContainingSpecialCharacters() { ExecutionsResult executionsResult = executeTestsForClass( ArbitraryNamingKotlinTestCase.class).getExecutionsResult(); assertThat(executionsResult.getTestStartedCount()).isEqualTo(2); TestDescriptor testDescriptor1 = executionsResult.getSuccessfulTestFinishedEvents().get(0).getTestDescriptor(); assertAll( () -> assertEquals(METHOD_NAME + "()", testDescriptor1.getDisplayName()), () -> assertEquals(METHOD_NAME + "()", testDescriptor1.getLegacyReportingName())); TestDescriptor testDescriptor2 = executionsResult.getSuccessfulTestFinishedEvents().get(1).getTestDescriptor(); assertAll( () -> assertEquals("test name ends with parentheses()()", testDescriptor2.getDisplayName()), () -> assertEquals("test name ends with parentheses()()", testDescriptor2.getLegacyReportingName())); }
Source:
<code>private void setDefaults() { <START> this.putClientProperty("html.disable", Boolean.TRUE); <END> this.setEditable(false); this.setCursor(null); this.setBorder(null); this.setBackground(new Color(UIManager.getLookAndFeel().getDefaults().getColor("Label.background").getRGB())); this.setForeground(new Color(UIManager.getLookAndFeel().getDefaults().getColor("Label.foreground").getRGB())); }</code><technical_language>This removed (not needed for this UI component)</technical_language>

Target:
private void setDefaults() { this.setEditable(false); this.setCursor(null); this.setBorder(null); this.setBackground(new Color(UIManager.getLookAndFeel().getDefaults().getColor("Label.background").getRGB())); this.setForeground(new Color(UIManager.getLookAndFeel().getDefaults().getColor("Label.foreground").getRGB())); }
Source:
<code>public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { MqttMessage mqttMessage = (MqttMessage) msg; System.out.println("Received MQTT message: " + mqttMessage); switch (mqttMessage.fixedHeader().messageType()) { case CONNECT: MqttFixedHeader connackFixedHeader = new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttConnAckVariableHeader mqttConnAckVariableHeader = new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_ACCEPTED, false); MqttConnAckMessage connack = new MqttConnAckMessage(connackFixedHeader, mqttConnAckVariableHeader); ctx.channel().writeAndFlush(connack); break; case PINGREQ: MqttFixedHeader pingreqFixedHeader = new MqttFixedHeader(MqttMessageType.PINGRESP, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttMessage pingResp = new MqttMessage(pingreqFixedHeader); <START> ctx.channel().writeAndFlush(pingResp); <END> break; case DISCONNECT: ctx.channel().close(); break; default: System.out.println("Unexpected message type: " + mqttMessage.fixedHeader().messageType()); ctx.channel().close(); } }</code><technical_language>ctx.writeAndFlush(pingresp)</technical_language>

Target:
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { MqttMessage mqttMessage = (MqttMessage) msg; System.out.println("Received MQTT message: " + mqttMessage); switch (mqttMessage.fixedHeader().messageType()) { case CONNECT: MqttFixedHeader connackFixedHeader = new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttConnAckVariableHeader mqttConnAckVariableHeader = new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_ACCEPTED, false); MqttConnAckMessage connack = new MqttConnAckMessage(connackFixedHeader, mqttConnAckVariableHeader); ctx.writeAndFlush(connack); break; case PINGREQ: MqttFixedHeader pingreqFixedHeader = new MqttFixedHeader(MqttMessageType.PINGRESP, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttMessage pingResp = new MqttMessage(pingreqFixedHeader); ctx.writeAndFlush(pingResp); break; case DISCONNECT: ctx.close(); break; default: System.out.println("Unexpected message type: " + mqttMessage.fixedHeader().messageType()); ReferenceCountUtil.release(msg); ctx.close(); } }
Source:
<code>void initialize(BaseDAO baseDAO, List<? extends BaseBean> list) { if (Objects.nonNull(this.id) && !Hibernate.isInitialized(list)) { try { <START> Hibernate.initialize(list); <END> } catch (HibernateException e) { baseDAO.initialize(this, list); } } }</code><technical_language>baseDAO.initialize discussed</technical_language>

Target:
void initialize(BaseDAO baseDAO, List<? extends BaseBean> list) { if (Objects.nonNull(this.id) && !Hibernate.isInitialized(list)) { baseDAO.initialize(this, list); } }
Source:
<code>public AuditEvent buildEvent(ProcessStartedEvent pse) { ProcessInstanceImpl pi = (ProcessInstanceImpl) pse.getProcessInstance(); ProcessInstanceLog log = new ProcessInstanceLog(pi.getId(), pi.getProcessId()); log.setExternalId(""+((KieSession) pse.getKieRuntime()).getIdentifier()); log.setProcessName(pi.getProcess().getName()); log.setProcessVersion(pi.getProcess().getVersion()); log.setStatus(ProcessInstance.STATE_ACTIVE); log.setProcessInstanceDescription( pi.getDescription() ); log.setProcessType(((WorkflowProcess)pi.getProcess()).getProcessType()); CorrelationKey correlationKey = (CorrelationKey) pi.getMetaData().get("CorrelationKey"); if (correlationKey != null) { log.setCorrelationKey(correlationKey.toExternalForm()); } try { Object value = pi.getMetaData().get("ParentProcessInstanceId"); if( value != null ){ long parentProcessInstanceId = (Long) value; log.setParentProcessInstanceId( parentProcessInstanceId ); }else{ log.setParentProcessInstanceId(-1L); <START> } <END> } catch (Exception e) { log.setParentProcessInstanceId(-1L); } return log; }</code><technical_language>this easier a single line instead of checks... long parentProcessInstanceId = (Long) pi.getMetaData().getOrDefault("ParentProcessInstanceId", -1L);</technical_language>

Target:
public AuditEvent buildEvent(ProcessStartedEvent pse) { ProcessInstanceImpl pi = (ProcessInstanceImpl) pse.getProcessInstance(); ProcessInstanceLog log = new ProcessInstanceLog(pi.getId(), pi.getProcessId()); log.setExternalId(""+((KieSession) pse.getKieRuntime()).getIdentifier()); log.setProcessName(pi.getProcess().getName()); log.setProcessVersion(pi.getProcess().getVersion()); log.setStatus(ProcessInstance.STATE_ACTIVE); log.setProcessInstanceDescription( pi.getDescription() ); log.setProcessType(((WorkflowProcess)pi.getProcess()).getProcessType()); CorrelationKey correlationKey = (CorrelationKey) pi.getMetaData().get("CorrelationKey"); if (correlationKey != null) { log.setCorrelationKey(correlationKey.toExternalForm()); } long parentProcessInstanceId = (Long) pi.getMetaData().getOrDefault("ParentProcessInstanceId", -1L); log.setParentProcessInstanceId( parentProcessInstanceId ); return log; }
Source:
<code>public void handleEvent(Event event) { if (event.widget instanceof Control) { Control c = (Control) event.widget; Shell shell = c.getShell(); switch (event.type) { case SWT.MouseDown: if (isHideOnMouseDown()) { toolTipHide(shell, event); } break; case SWT.MouseExit: Rectangle rect = shell.getBounds(); <START> rect.width -= 10; rect.height -= 10; <END> if (!rect.contains(c.getDisplay().getCursorLocation())) { toolTipHide(shell, event); } break; } } }</code><technical_language>Remove</technical_language>

Target:
public void handleEvent(Event event) { if (event.widget instanceof Control) { Control c = (Control) event.widget; Shell shell = c.getShell(); switch (event.type) { case SWT.MouseDown: if (isHideOnMouseDown()) { toolTipHide(shell, event); } break; case SWT.MouseExit: Rectangle rect = shell.getBounds(); if (!rect.contains(c.getDisplay().getCursorLocation())) { toolTipHide(shell, event); } break; } } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = ViewModelProviders.of(this).get(SmartLockHandler.class); mHandler.init(getFlowParams()); Credential credential = getIntent().getParcelableExtra(ExtraConstants.EXTRA_CREDENTIAL); mIdpResponse = getIntent().getParcelableExtra(ExtraConstants.EXTRA_IDP_RESPONSE); <START> mHandler.saveCredentials(credential); <END> mHandler.getSaveOperation().observe(this, new Observer<Resource<Void>>() { @Override public void onChanged(@Nullable Resource<Void> resource) { if (resource == null) { Log.w(TAG, "getSaveOperation:onChanged:null"); return; } onSaveOperation(resource); } }); mHandler.getPendingResolution().observe(this, new Observer<PendingResolution>() { @Override public void onChanged(@Nullable PendingResolution resolution) { if (resolution == null) { Log.w(TAG, "getPendingResolution:onChanged: null"); return; } onPendingResolution(resolution); } }); }</code><technical_language>This guarded a savedInstanceState == null check. (Or activity resilient config changes android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"?)</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = ViewModelProviders.of(this).get(SmartLockHandler.class); mHandler.init(getFlowParams()); Credential credential = getIntent().getParcelableExtra(ExtraConstants.EXTRA_CREDENTIAL); mIdpResponse = getIntent().getParcelableExtra(ExtraConstants.EXTRA_IDP_RESPONSE); mHandler.getSaveOperation().observe(this, new Observer<Resource<Void>>() { @Override public void onChanged(@Nullable Resource<Void> resource) { if (resource == null) { Log.w(TAG, "getSaveOperation:onChanged:null"); return; } onSaveOperation(resource); } }); mHandler.getPendingResolution().observe(this, new Observer<PendingResolution>() { @Override public void onChanged(@Nullable PendingResolution resolution) { if (resolution == null) { Log.w(TAG, "getPendingResolution:onChanged: null"); return; } onPendingResolution(resolution); } }); Resource<Void> currentOp = mHandler.getSaveOperation().getValue(); if (currentOp == null) { mHandler.saveCredentials(credential); } }
Source:
<code>private String getTimestamp() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); try { <START> return URLEncoder.encode(dateFormat.format(new Date()), CHARSET_UTF8); <END> } catch (UnsupportedEncodingException e) { Timber.e(e.getMessage()); return null; } }</code><technical_language>reuse encodeParam() function here</technical_language>

Target:
private String getTimestamp() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); return encodeParam(dateFormat.format(new Date())); }
Source:
<code>protected void populateHiddenFields(EntityInfo ei, Metadata md, String version, Map<String, String> fieldMap, QueryExpression query) throws IOException { LOGGER.info("Starting population of hidden fields due to new or modified indexes."); MongoDataStore ds = (MongoDataStore) ei.getDataStore(); DB entityDB = dbResolver.get(ds); DBCollection coll = entityDB.getCollection(ds.getCollectionName()); DBCursor cursor = null; if (query != null){ MetadataResolver mdResolver = new MetadataResolver() { @Override public EntityMetadata getEntityMetadata(String entityName) { String v = version == null ? ei.getDefaultVersion() : version; return md.getEntityMetadata(entityName, v); } }; Translator trans = new Translator(mdResolver, JsonNodeFactory.instance); DBObject mongoQuery = trans.translate(mdResolver.getEntityMetadata(ei.getName()), query); cursor = coll.find(mongoQuery); } else { cursor = coll.find(); } while (cursor.hasNext()) { DBObject doc = cursor.next(); DBObject original = (DBObject) ((BasicDBObject) doc).copy(); Translator.populateDocHiddenFields(doc, fieldMap); if (!doc.equals(original)) { try { coll.save(doc); } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.debug("Original doc:\n{}", original); LOGGER.debug("Error saving doc:\n{}", doc); } } } <START> cursor.close(); <END> LOGGER.info("Finished population of hidden fields."); }</code><technical_language>cursor iteration block a try-catch-log-finally, errors if read fails</technical_language>

Target:
protected void populateHiddenFields(EntityInfo ei, Metadata md, String version, Map<String, String> fieldMap, QueryExpression query) throws IOException { LOGGER.info("Starting population of hidden fields due to new or modified indexes."); MongoDataStore ds = (MongoDataStore) ei.getDataStore(); DB entityDB = dbResolver.get(ds); DBCollection coll = entityDB.getCollection(ds.getCollectionName()); DBCursor cursor = null; if (query != null) { MetadataResolver mdResolver = new MetadataResolver() { @Override public EntityMetadata getEntityMetadata(String entityName) { String v = version == null ? ei.getDefaultVersion() : version; return md.getEntityMetadata(entityName, v); } }; Translator trans = new Translator(mdResolver, JsonNodeFactory.instance); DBObject mongoQuery = trans.translate(mdResolver.getEntityMetadata(ei.getName()), query); cursor = coll.find(mongoQuery); } else { cursor = coll.find(); } try { while (cursor.hasNext()) { DBObject doc = cursor.next(); DBObject original = (DBObject) ((BasicDBObject) doc).copy(); try { Translator.populateDocHiddenFields(doc, fieldMap); if (!doc.equals(original)) { coll.save(doc); } } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.debug("Original doc:\n{}", original); LOGGER.debug("Error saving doc:\n{}", doc); } } } catch (Exception e) { LOGGER.error("Error during reindexing"); LOGGER.error(e.getMessage()); throw new RuntimeException(e); } finally { cursor.close(); } LOGGER.info("Finished population of hidden fields."); }
Source:
<code>public Future<UpdateCenterJob> deploy(boolean dynamicLoad, @CheckForNull UUID correlationId) { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); UpdateCenter uc = Jenkins.getInstance().getUpdateCenter(); for (Plugin dep : getNeededDependencies()) { UpdateCenter.InstallationJob job = uc.getJob(dep); if (job == null || job.status instanceof UpdateCenter.DownloadJob.Failure) { LOGGER.log(Level.WARNING, "Adding dependent install of " + dep.name + " for plugin " + name); dep.deploy(dynamicLoad); } else { LOGGER.log(Level.WARNING, "Dependent install of " + dep.name + " for plugin " + name + " already added, skipping"); } } PluginWrapper pw = getInstalled(); if(pw != null) { Future<UpdateCenterJob> enableJob = null; <START> if(!pw.isEnabled()) { <END> UpdateCenter.EnableJob job = uc.new EnableJob(UpdateSite.this, this); job.setCorrelationId(correlationId); enableJob = uc.addJob(job); } if(pw.getVersionNumber().equals(new VersionNumber(version))) { return enableJob != null ? enableJob : uc.addJob(uc.new NoOpJob(UpdateSite.this, this)); } } UpdateCenter.InstallationJob job = uc.new InstallationJob(this, UpdateSite.this, Jenkins.getAuthentication(), dynamicLoad); job.setCorrelationId(correlationId); return uc.addJob(job); }</code><technical_language>Is this case a newly installed plugin has, for reason, a .disabled file disk? this happen</technical_language>

Target:
public Future<UpdateCenterJob> deploy(boolean dynamicLoad, @CheckForNull UUID correlationId) { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); UpdateCenter uc = Jenkins.getInstance().getUpdateCenter(); for (Plugin dep : getNeededDependencies()) { UpdateCenter.InstallationJob job = uc.getJob(dep); if (job == null || job.status instanceof UpdateCenter.DownloadJob.Failure) { LOGGER.log(Level.WARNING, "Adding dependent install of " + dep.name + " for plugin " + name); dep.deploy(dynamicLoad); } else { LOGGER.log(Level.WARNING, "Dependent install of " + dep.name + " for plugin " + name + " already added, skipping"); } } PluginWrapper pw = getInstalled(); if(pw != null) { Future<UpdateCenterJob> enableJob = null; if(!pw.isEnabled()) { UpdateCenter.EnableJob job = uc.new EnableJob(UpdateSite.this, null, this, dynamicLoad); job.setCorrelationId(correlationId); enableJob = uc.addJob(job); } if(pw.getVersionNumber().equals(new VersionNumber(version))) { return enableJob != null ? enableJob : uc.addJob(uc.new NoOpJob(UpdateSite.this, null, this)); } } UpdateCenter.InstallationJob job = uc.new InstallationJob(this, UpdateSite.this, Jenkins.getAuthentication(), dynamicLoad); job.setCorrelationId(correlationId); return uc.addJob(job); }
Source:
<code>private void getFavFromPoint(RotatedTileBox tb, List<? super FavouritePoint> res, int r, int ex, int ey, FavouritePoint n) { if (n.isVisible()) { int x = (int) tb.getPixXFromLatLon(n.getLatitude(), n.getLongitude()); int y = (int) tb.getPixYFromLatLon(n.getLatitude(), n.getLongitude()); if (calculateBelongs(ex, ey, x, y, r)) { <START> if (!n.getName().equals(FavouritePoint.PointType.PARKING.getName())) { <END> res.add(n); } } } }</code><technical_language>bad code</technical_language>

Target:
private void getFavFromPoint(RotatedTileBox tb, List<? super FavouritePoint> res, int r, int ex, int ey, FavouritePoint n) { if (n.isVisible()) { int x = (int) tb.getPixXFromLatLon(n.getLatitude(), n.getLongitude()); int y = (int) tb.getPixYFromLatLon(n.getLatitude(), n.getLongitude()); if (calculateBelongs(ex, ey, x, y, r)) { res.add(n); } } }
Source:
<code>public void exceptionsWithRetryAfterBacksOffAfterQueryingAllNodesInTheCluster() { for (int i = 0; i < CLUSTER_SIZE; i++) { simulateRequest(spiedTarget); spiedTarget.continueOrPropagate(EXCEPTION_WITH_RETRY_AFTER); } long bottom = FailoverFeignTarget.BACKOFF_BEFORE_ROUND_ROBIN_RETRY_MILLIS / 2; <START> long cap = (FailoverFeignTarget.BACKOFF_BEFORE_ROUND_ROBIN_RETRY_MILLIS * 3) / 2; <END> verify(spiedTarget, times(1)).pauseForBackoff(any(), longThat(is(both(greaterThanOrEqualTo(bottom)).and(lessThan(cap))))); }</code><technical_language>extract constants. rename more descriptive LOWER_BOUND UPPER_BOUND</technical_language>

Target:
public void exceptionsWithRetryAfterBacksOffAfterQueryingAllNodesInTheCluster() { for (int i = 0; i < CLUSTER_SIZE; i++) { simulateRequest(spiedTarget); spiedTarget.continueOrPropagate(EXCEPTION_WITH_RETRY_AFTER); } verify(spiedTarget, times(1)).pauseForBackoff(any(), longThat(is(both(greaterThanOrEqualTo(LOWER_BACKOFF_BOUND)).and(lessThan(UPPER_BACKOFF_BOUND))))); }
Source:
<code>private static boolean isAffinityAvailable() { try { boolean jnaAvailable = Affinity.isJNAAvailable(); if (!jnaAvailable) { System.err.println("jna is not available"); } return jnaAvailable; } catch (NoClassDefFoundError e) { <START> e.printStackTrace(); <END> System.err.println("Affinity jar isn't available"); return false; } }</code><technical_language>logging instead? logging initialized get here</technical_language>

Target:
private static boolean isAffinityAvailable() { try { boolean jnaAvailable = Affinity.isJNAAvailable(); if (!jnaAvailable) { Logger.getLogger(ThreadAffinity.class).warning("jna is not available"); } return jnaAvailable; } catch (NoClassDefFoundError e) { Logger.getLogger(ThreadAffinity.class).warning("Affinity jar isn't available: " + e.getMessage()); return false; } }
Source:
<code>public void test() throws Exception { ExternalBuildReport report = new ExternalBuildReport("<LINK_0>"); assertEquals("View External Report", report.getDisplayName()); assertEquals("graph.gif", report.getIconFileName()); <START> assertEquals("graph.gif", report.getIconFileName()); <END> assertEquals("<LINK_0>", report.getUrlName()); assertEquals(null, report.getTarget()); }</code><technical_language>duplicate assert</technical_language>

Target:
public void test() throws Exception { ExternalBuildReport report = new ExternalBuildReport("<LINK_0>"); assertEquals("View External Report", report.getDisplayName()); assertEquals("graph.gif", report.getIconFileName()); assertEquals("<LINK_0>", report.getUrlName()); assertEquals(null, report.getTarget()); }
Source:
<code>public void spec113_mustProduceTheSameElementsInTheSameSequenceToAllOfItsSubscribersWhenRequestingManyUpfront() throws Throwable { activePublisherTest(3, new PublisherTestRun<T>() { @Override public void run(Publisher<T> pub) throws Throwable { ManualSubscriber<T> sub1 = env.newManualSubscriber(pub); ManualSubscriber<T> sub2 = env.newManualSubscriber(pub); ManualSubscriber<T> sub3 = env.newManualSubscriber(pub); List<T> received1 = new ArrayList<T>(); List<T> received2 = new ArrayList<T>(); List<T> received3 = new ArrayList<T>(); sub1.request(3); sub2.request(3); sub3.request(3); received1.addAll(sub1.nextElements(3)); received2.addAll(sub2.nextElements(3)); received3.addAll(sub3.nextElements(3)); sub1.nextElementOrEndOfStream(); sub2.nextElementOrEndOfStream(); <START> sub3.nextElementOrEndOfStream(); <END> assertEquals(received1, received2, String.format("Expected elements to be signaled in the same sequence to both subscribers")); assertEquals(received2, received3, String.format("Expected elements to be signaled in the same sequence to both subscribers")); } }); }</code><technical_language>permit nextElement here</technical_language>

Target:
public void spec113_mustProduceTheSameElementsInTheSameSequenceToAllOfItsSubscribersWhenRequestingManyUpfront() throws Throwable { optionalActivePublisherTest(3, new PublisherTestRun<T>() { @Override public void run(Publisher<T> pub) throws Throwable { ManualSubscriber<T> sub1 = env.newManualSubscriber(pub); ManualSubscriber<T> sub2 = env.newManualSubscriber(pub); ManualSubscriber<T> sub3 = env.newManualSubscriber(pub); List<T> received1 = new ArrayList<T>(); List<T> received2 = new ArrayList<T>(); List<T> received3 = new ArrayList<T>(); sub1.request(4); sub2.request(4); sub3.request(4); received1.addAll(sub1.nextElements(3)); received2.addAll(sub2.nextElements(3)); received3.addAll(sub3.nextElements(3)); sub1.expectCompletion(); sub2.expectCompletion(); sub3.expectCompletion(); assertEquals(received1, received2, String.format("Expected elements to be signaled in the same sequence to 1st and 2nd subscribers")); assertEquals(received2, received3, String.format("Expected elements to be signaled in the same sequence to 2nd and 3rd subscribers")); } }); }
Source:
<code>public static String getHeaderField(final URL url, final String name) { URLConnection conn = null; try { conn = openConnection(url); <START> if(conn instanceof HttpURLConnection) { <END> final HttpURLConnection httpConn = HttpURLConnection.class.cast(conn); httpConn.setRequestMethod("HEAD"); } return conn.getHeaderField(name); } catch (final IOException e) { e.printStackTrace(); return null; } finally { if (conn != null && conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).disconnect(); } } }</code><technical_language>need space if</technical_language>

Target:
public static String getHeaderField(final URL url, final String name) { URLConnection conn = null; try { conn = openConnection(url); if (conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).setRequestMethod("HEAD"); } return conn.getHeaderField(name); } catch (final IOException e) { e.printStackTrace(); return null; } finally { if (conn != null && conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).disconnect(); } } }
Source:
<code>public void verifyTappingOnImageEdge (PerformTouchAction touchAction, String edge) { String currentImageSrc = getCurrentImagePath(); String nextImageSrc; int pointX = 25; int duration = 500; int waitAfter = 5000; <START> if (edge == "right") { <END> pointX = 75; } else { edge = "left"; } touchAction.tapOnPointXY(pointX, 50, duration, waitAfter); nextImageSrc = getCurrentImagePath(); if (!nextImageSrc.contains(currentImageSrc)) { PageObjectLogging.log("verifyTappingOnImageEdge", "Tapping on " + edge + " edge works", true); } else { PageObjectLogging.log("verifyTappingOnImageEdge", "Tapping on " + edge + " edge doesn't work", false); } }</code><technical_language>if a String comparison, needs .equals() I suggest putting String left side avoid NullPointerException</technical_language>

Target:
public void verifyTappingOnImageEdge (PerformTouchAction touchAction, String edge) { String currentImageSrc = getCurrentImagePath(); String nextImageSrc; int pointX = 25; int duration = 500; int waitAfter = 5000; if ("right".equals(edge)) { pointX = 75; } else { edge = "left"; } touchAction.tapOnPointXY(pointX, 50, duration, waitAfter); nextImageSrc = getCurrentImagePath(); if (!nextImageSrc.contains(currentImageSrc)) { PageObjectLogging.log("verifyTappingOnImageEdge", "Tapping on " + edge + " edge works", true); } else { PageObjectLogging.log("verifyTappingOnImageEdge", "Tapping on " + edge + " edge doesn't work", false); } }
Source:
<code>public Builder reset() { <START> return rgb(0, 0, 0); <END> }</code><technical_language>A wasteful need do is set fields return this..</technical_language>

Target:
public Builder reset() { this.red = -1; this.green = -1; this.blue = -1; return this; }
Source:
<code>public void testSendPojoReceivePojoKryoWithStreamListener() throws Exception { StreamListenerMessageHandler handler = this.buildStreamListener( AbstractBinderTests.class, "echoStation", Station.class); Binder binder = getBinder(); PP producerProperties = createProducerProperties(); BindingProperties producerBindingProperties = createProducerBindingProperties(producerProperties); DirectChannel moduleOutputChannel = createBindableChannel("output", producerBindingProperties); <START> DirectChannel moduleInputChannel = createBindableChannel("input", producerBindingProperties); <END> Binding<MessageChannel> producerBinding = binder.bindProducer(String.format("bad%s0b", getDestinationNameDelimiter()), moduleOutputChannel, producerProperties); Binding<MessageChannel> consumerBinding = binder.bindConsumer(String.format("bad%s0b", getDestinationNameDelimiter()), "test-2", moduleInputChannel, createConsumerProperties()); Station station = new Station(); Message<?> message = MessageBuilder.withPayload(station).setHeader( MessageHeaders.CONTENT_TYPE, MessageConverterUtils.X_JAVA_OBJECT).build(); moduleInputChannel.subscribe(handler); moduleOutputChannel.send(message); QueueChannel replyChannel = (QueueChannel) handler.getOutputChannel(); Message<?> replyMessage = replyChannel.receive(5000); assertTrue(replyMessage.getPayload() instanceof Station); producerBinding.unbind(); consumerBinding.unbind(); }</code><technical_language>This wrong; input channels consumerBindingProperties. (multiple places)</technical_language>

Target:
public void testSendPojoReceivePojoKryoWithStreamListener() throws Exception { StreamListenerMessageHandler handler = this.buildStreamListener( AbstractBinderTests.class, "echoStation", Station.class); Binder binder = getBinder(); BindingProperties producerBindingProperties = createProducerBindingProperties(createProducerProperties()); DirectChannel moduleOutputChannel = createBindableChannel("output", producerBindingProperties); BindingProperties consumerBindingProperties = createConsumerBindingProperties(createConsumerProperties()); DirectChannel moduleInputChannel = createBindableChannel("input", consumerBindingProperties); Binding<MessageChannel> producerBinding = binder.bindProducer(String.format("bad%s0b", getDestinationNameDelimiter()), moduleOutputChannel, producerBindingProperties.getProducer()); Binding<MessageChannel> consumerBinding = binder.bindConsumer(String.format("bad%s0b", getDestinationNameDelimiter()), "test-2", moduleInputChannel, consumerBindingProperties.getConsumer()); Station station = new Station(); Message<?> message = MessageBuilder.withPayload(station).setHeader( MessageHeaders.CONTENT_TYPE, MessageConverterUtils.X_JAVA_OBJECT).build(); moduleInputChannel.subscribe(handler); moduleOutputChannel.send(message); QueueChannel replyChannel = (QueueChannel) handler.getOutputChannel(); Message<?> replyMessage = replyChannel.receive(5000); assertTrue(replyMessage.getPayload() instanceof Station); producerBinding.unbind(); consumerBinding.unbind(); }
Source:
<code>void shutdown() { <START> log.info( "Shutting down as there is no ping response on port {}", port ); <END> shutdown.run(); }</code><technical_language>this is abnormal shutdown, this warn</technical_language>

Target:
void shutdown() { log.warn( "Shutting down as there is no ping response from on port {}", talker.getHost(), talker.getPort() ); shutdown.run(); }
Source:
<code>public void checkExecutorHealthQuietly() { try { checkExecutorHealth(); <START> } catch (Throwable t) { <END> logger.error("Unexepected error during executor healthcheck. Cause: " + ExceptionUtils.getStackTrace(t)); } }</code><technical_language>nitpick : final Throwable t</technical_language>

Target:
public void checkExecutorHealthQuietly() { try { checkExecutorHealth(); } catch (final RuntimeException e) { logger.error("Unexepected error during executor healthcheck. Cause: " + ExceptionUtils.getStackTrace(e)); } }
Source:
<code>String calculateCommitMessage(Collection<String> paths) { if (commitMessage != null) { return commitMessage; } if (amending) return previousCommitMessage; StringBuilder calculatedCommitMessage = new StringBuilder(); Set<IResource> resources = new HashSet<>(); for (String path : paths) { IFile file = findFile(path); if (file != null) resources.add(file.getProject()); } if (resources.size() == 0 && repository != null) { resources .addAll(Arrays.asList(ProjectUtil.getProjects(repository))); } try { List<ICommitMessageProvider> messageProviders = getCommitMessageProviders(); IResource[] resourcesArray = resources .toArray(new IResource[0]); String providedMessageSeparator = "\n\n"; for (ICommitMessageProvider messageProvider : messageProviders) { String message = null; try { message = messageProvider.getMessage(resourcesArray); } catch (RuntimeException e) { Activator.logError(e.getMessage(), e); } if (message != null && <START> !"".equals(message.trim())) { END> if (calculatedCommitMessage.length() > 0) { calculatedCommitMessage .append(providedMessageSeparator); } calculatedCommitMessage.append((message.trim())); } } } catch (CoreException coreException) { Activator.logError(coreException.getLocalizedMessage(), coreException); } return calculatedCommitMessage.toString(); }</code><technical_language>Please change !message.trim().isEmpty()) {</technical_language>

Target:
String calculateCommitMessage(Collection<String> paths) { if (commitMessage != null) { return commitMessage; } if (amending) return previousCommitMessage; StringBuilder calculatedCommitMessage = new StringBuilder(); Set<IResource> resources = new HashSet<>(); for (String path : paths) { IFile file = findFile(path); if (file != null) resources.add(file.getProject()); } if (resources.size() == 0 && repository != null) { resources .addAll(Arrays.asList(ProjectUtil.getProjects(repository))); } List<ICommitMessageProvider> messageProviders = getCommitMessageProviders(); IResource[] resourcesArray = resources.toArray(new IResource[0]); String providedMessageSeparator = "\n\n"; for (ICommitMessageProvider messageProvider : messageProviders) { String message = null; try { message = messageProvider.getMessage(resourcesArray); } catch (RuntimeException e) { Activator.logError(e.getMessage(), e); } if (message != null && !message.trim().isEmpty()) { if (calculatedCommitMessage.length() > 0) { calculatedCommitMessage.append(providedMessageSeparator); } calculatedCommitMessage.append((message.trim())); } } return calculatedCommitMessage.toString(); }