auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Timestep maxTimestep() { ArrayList<ArgSpec> timestepTerms = new ArrayList<ArgSpec>(); <START> selectTerms(new UnaryPredicate() { <END> public boolean evaluate(Object term) { return ((ArgSpec) term).getTimestep() != null; } }, timestepTerms); Timestep result = null; for (ArgSpec spec : timestepTerms) { Timestep timestep = spec.getTimestep(); if (result == null || timestep.compareTo(result) > 0) { result = timestep; } } return result; }</code><technical_language>This implementation sounds complicated. doesnot efficient. Esseentially is a solution prior Java 8</technical_language>

Target:
public Timestep maxTimestep() { ArgSpecMaxReduceTimestep reducer = new ArgSpecMaxReduceTimestep(); applyToTerms(reducer); return reducer.result; }
Source:
<code>public Optional<BibEntry> performSearchById(String identifier) throws FetcherException { if (StringUtil.isBlank(identifier)) { return Optional.empty(); } identifier = NEWLINE_SPACE_PATTERN.matcher(identifier).replaceAll(""); IsbnViaEbookDeFetcher isbnViaEbookDeFetcher = new IsbnViaEbookDeFetcher(importFormatPreferences); Optional<BibEntry> bibEntry = isbnViaEbookDeFetcher.performSearchById(identifier); if (!bibEntry.isPresent()) { LOGGER.debug("No entry found at ebook.de; trying ottobib"); IsbnViaOttoBibFetcher isbnViaOttoBibFetcher = new IsbnViaOttoBibFetcher(importFormatPreferences); bibEntry = isbnViaOttoBibFetcher.performSearchById(identifier); } if (!bibEntry.isPresent()) { <START> FXDialog noEntryFoundDialog = new FXDialog(AlertType.ERROR); <END> noEntryFoundDialog.setContentText("No entry found for ISBN: " + identifier + "."); noEntryFoundDialog.show(); } return bibEntry; }</code><technical_language>I thought throwing a fetcher exception well. other hand optional for cases. I throw exception. @tobiasdiez</technical_language>

Target:
public Optional<BibEntry> performSearchById(String identifier) throws FetcherException { if (StringUtil.isBlank(identifier)) { return Optional.empty(); } identifier = NEWLINE_SPACE_PATTERN.matcher(identifier).replaceAll(""); IsbnViaEbookDeFetcher isbnViaEbookDeFetcher = new IsbnViaEbookDeFetcher(importFormatPreferences); Optional<BibEntry> bibEntry = isbnViaEbookDeFetcher.performSearchById(identifier); if (!bibEntry.isPresent()) { LOGGER.debug("No entry found at ebook.de; trying ottobib"); IsbnViaOttoBibFetcher isbnViaOttoBibFetcher = new IsbnViaOttoBibFetcher(importFormatPreferences); bibEntry = isbnViaOttoBibFetcher.performSearchById(identifier); } return bibEntry; }
Source:
<code>public ValidationResult isOperationAllowedOnDisk(VdcActionType actionType) { List<DiskContentType> allowedTypes = allowedCommandsOnTypes.get(actionType); if (allowedTypes == null) { throw new IllegalArgumentException( String.format("Cannot validate operation on disk for action of type %s as it is not an allowed <START> commands for <END> the disk content type.", actionType)); } if (!allowedTypes.contains(disk.getContentType())) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISK_CONTENT_TYPE_NOT_SUPPORTED_FOR_OPERATION, String.format("$diskContentType %s", disk.getContentType())); } return ValidationResult.VALID; }</code><technical_language>s/commands/command</technical_language>

Target:
public ValidationResult isOperationAllowedOnDisk(VdcActionType actionType) { List<DiskContentType> allowedTypes = allowedCommandsOnTypes.get(actionType); if (allowedTypes == null) { throw new IllegalArgumentException( String.format("Cannot validate operation on disk for action of type %s as it is not an allowed command for the disk content type.", actionType)); } if (!allowedTypes.contains(disk.getContentType())) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISK_CONTENT_TYPE_NOT_SUPPORTED_FOR_OPERATION, String.format("$diskContentType %s", disk.getContentType())); } return ValidationResult.VALID; }
Source:
<code><START> protected void afterConfigureProperties() { <END> getZendesk(); }</code><technical_language>Is this do in doStart instead</technical_language>

Target:
protected void afterConfigureProperties() { }
Source:
<code>private ContentEquivalenceUpdateTask publisherUpdateTask(final Publisher... publishers) { return new ContentEquivalenceUpdateTask( <START> (SelectedContentLister) contentLister, <END> contentResolver, getNewDefaultExecutor(), progressStore(), equivUpdater, ignored ).forPublishers(publishers); }</code><technical_language>This cast feels a bit out of place I a suggestion - this is autowired add a separate bean a return type of SelectedContentLister returns object normal ContentLister bean</technical_language>

Target:
private ContentEquivalenceUpdateTask publisherUpdateTask(final Publisher... publishers) { return new ContentEquivalenceUpdateTask( contentLister, contentResolver, getNewDefaultExecutor(), progressStore(), equivUpdater, ignored ).forPublishers(publishers); }
Source:
<code>private void emitThreadAllocationMetrics(ServiceEmitter emitter) { final ServiceMetricEvent.Builder builder = builder(); MonitorUtils.addDimensionsToBuilder(builder, dimensions); Optional<Long> delta = collector.calculateDelta(); <START> delta.ifPresent((value) -> emitter.emit(builder.build("jvm/heapAlloc/bytes", value))); <END> }</code><technical_language>jvm/heapAlloc/bytes/delta</technical_language>

Target:
private void emitThreadAllocationMetrics(ServiceEmitter emitter) { final ServiceMetricEvent.Builder builder = builder(); MonitorUtils.addDimensionsToBuilder(builder, dimensions); if (collector != null) { long delta = collector.calculateDelta(); emitter.emit(builder.build("jvm/heapAlloc/bytes", delta)); } }
Source:
<code>protected Deployment createDeployment(ResourceLoader resourceLoader, CDI11Bootstrap bootstrap) { final Iterable<Metadata<Extension>> loadedExtensions = loadExtensions(WeldResourceLoader.getClassLoader(), bootstrap); final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(loadedExtensions); Deployment deployment=null; DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, typeDiscoveryConfiguration); Set<WeldBeanDeploymentArchive> discoveredArchives = strategy.performDiscovery(); String isolation = AccessController.doPrivileged(new GetSystemPropertyAction(ARCHIVE_ISOLATION_SYSTEM_PROPERTY)); if (isolation != null && Boolean.valueOf(isolation).equals(Boolean.FALSE)) { WeldBeanDeploymentArchive archive = WeldBeanDeploymentArchive.merge(bootstrap, discoveredArchives); deployment = new WeldDeployment(resourceLoader, bootstrap, Collections.singleton(archive), loadedExtensions); CommonLogger.LOG.archiveIsolationDisabled(); } else { deployment= new WeldDeployment(resourceLoader, bootstrap, discoveredArchives, loadedExtensions); CommonLogger.LOG.archiveIsolationEnabled(); } <START> WeldSELogger.LOG.multipleIsolation(isolation != null && Boolean.valueOf(isolation)); <END> if(strategy.getClassFileServices() != null) { deployment.getServices().add(ClassFileServices.class, strategy.getClassFileServices()); } return deployment; }</code><technical_language>This - replaced CommonLogger.LOG.archiveIsolationEnabled() / CommonLogger.LOG.archiveIsolationDisabled()</technical_language>

Target:
protected Deployment createDeployment(ResourceLoader resourceLoader, CDI11Bootstrap bootstrap) { final Iterable<Metadata<Extension>> loadedExtensions = loadExtensions(WeldResourceLoader.getClassLoader(), bootstrap); final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(loadedExtensions); Deployment deployment=null; DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, typeDiscoveryConfiguration); Set<WeldBeanDeploymentArchive> discoveredArchives = strategy.performDiscovery(); String isolation = AccessController.doPrivileged(new GetSystemPropertyAction(ARCHIVE_ISOLATION_SYSTEM_PROPERTY)); if (isolation != null && Boolean.valueOf(isolation).equals(Boolean.FALSE)) { WeldBeanDeploymentArchive archive = WeldBeanDeploymentArchive.merge(bootstrap, discoveredArchives); deployment = new WeldDeployment(resourceLoader, bootstrap, Collections.singleton(archive), loadedExtensions); CommonLogger.LOG.archiveIsolationDisabled(); } else { deployment= new WeldDeployment(resourceLoader, bootstrap, discoveredArchives, loadedExtensions); CommonLogger.LOG.archiveIsolationEnabled(); } if(strategy.getClassFileServices() != null) { deployment.getServices().add(ClassFileServices.class, strategy.getClassFileServices()); } return deployment; }
Source:
<code>public List<GlusterGeoRepSession> getAllSessions() { <START> return getCallsHandler().executeReadList("GetAllGlusterGeoRepSessions", georepSessionRowMapper, getCustomMapSqlParameterSource().addValue("user_id", null).addValue("is_filtered", false)); <END> }</code><technical_language>user_id is_filtered parameters required</technical_language>

Target:
public List<GlusterGeoRepSession> getAllSessions() { return getCallsHandler().executeReadList("GetAllGlusterGeoRepSessions", georepSessionRowMapper, getCustomMapSqlParameterSource()); }
Source:
<code>public boolean registerIfNew(String name, AsyncHttpClient ahc) { AsyncHttpClient value = asyncHttpClientMap.putIfAbsent(name, ahc); if (value == null) return true; else return false; <START> } <END></code><technical_language>return asyncHttpClientMap.putIfAbsent(name, ahc) == null;</technical_language>

Target:
public boolean registerIfNew(String name, AsyncHttpClient ahc) { return asyncHttpClientMap.putIfAbsent(name, ahc)==null; }
Source:
<code>private void updatePaint() { Bitmap bitmap = getBitmap(); if (mLastBitmap == null || mLastBitmap.get() != bitmap) { mLastBitmap = new WeakReference<Bitmap>(bitmap); mPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); mIsShaderTransformDirty = true; } <START> if (mIsShaderTransformDirty) { <END> if (!mTransform.isIdentity()) { mPaint.getShader().setLocalMatrix(mTransform); } mIsShaderTransformDirty = false; } }</code><technical_language>Do reset matrix otherwise? I.e. this work if switch a complex circular case</technical_language>

Target:
private void updatePaint() { Bitmap bitmap = getBitmap(); if (mLastBitmap == null || mLastBitmap.get() != bitmap) { mLastBitmap = new WeakReference<Bitmap>(bitmap); mPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); mIsShaderTransformDirty = true; } if (mIsShaderTransformDirty) { if (mTransform.isIdentity()) { mPaint.getShader().setLocalMatrix(null); } else { mPaint.getShader().setLocalMatrix(mTransform); } mIsShaderTransformDirty = false; } }
Source:
<code>public void theGetPeriodicMeterReadsRequestIsReceived() throws Throwable { this.correlationUidPattern = Pattern.compile(this.organisationId.getOrganisationId() + "\\|\\|\\|\\S{17}\\|\\|\\|\\S{17}"); this.testCase = this.wsdlProjectFactory.createWsdlTestCase(SOAP_PROJECT_XML, TEST_SUITE_XML, TEST_CASE_XML); final TestCaseResult runTestStepByName = this.testCaseRunner.runWsdlTestCase(this.testCase, <START> this.deviceId.getDeviceId(), this.organisationId.getOrganisationId(), this.correlationUid, <END> TEST_CASE_NAME_REQUEST); final TestStepResult runTestStepByNameResult = runTestStepByName.getRunTestStepByName(); final WsdlTestCaseRunner wsdlTestCaseRunner = runTestStepByName.getResults(); Assert.assertEquals(TestStepStatus.OK, runTestStepByNameResult.getStatus()); for (final TestStepResult tcr : wsdlTestCaseRunner.getResults()) { this.response = ((MessageExchange) tcr).getResponseContent(); this.correlationUidMatcher = this.correlationUidPattern.matcher(this.response); } this.correlationUidMatcher.find(); this.correlationUid = this.correlationUidMatcher.group(); }</code><technical_language>do set correlationId for request. is applicable for reqeust of response</technical_language>

Target:
public void theGetPeriodicMeterReadsRequestIsReceived() throws Throwable { this.correlationUidPattern = Pattern.compile(this.organisationId.getOrganisationId() + "\\|\\|\\|\\S{17}\\|\\|\\|\\S{17}"); this.testCase = this.wsdlProjectFactory.createWsdlTestCase(SOAP_PROJECT_XML, TEST_SUITE_XML, TEST_CASE_XML_225); PROPERTIES_MAP.put("DeviceIdentificationE", this.deviceId.getDeviceId()); PROPERTIES_MAP.put("OrganisationIdentification", this.organisationId.getOrganisationId()); final TestCaseResult runTestStepByName = this.testCaseRunner.runWsdlTestCase(this.testCase, PROPERTIES_MAP, TEST_CASE_NAME_REQUEST); final TestStepResult runTestStepByNameResult = runTestStepByName.getRunTestStepByName(); final WsdlTestCaseRunner wsdlTestCaseRunner = runTestStepByName.getResults(); assertEquals(TestStepStatus.OK, runTestStepByNameResult.getStatus()); for (final TestStepResult tcr : wsdlTestCaseRunner.getResults()) { this.response = ((MessageExchange) tcr).getResponseContent(); this.correlationUidMatcher = this.correlationUidPattern.matcher(this.response); } this.correlationUidMatcher.find(); this.correlationUid = this.correlationUidMatcher.group(); }
Source:
<code>public @Nonnull String inspectRequiredField(@Nonnull EnvVars launchEnv, @Nonnull String objectId, @Nonnull String fieldPath) throws IOException, InterruptedException { final LaunchResult result = launch(launchEnv, true, "inspect", "-f", String.format("{{%s}}", fieldPath), objectId); String fieldValue = result.getStatus() == 0 ? hudson.Util.fixEmpty(result.getOut()) : null; <START> if (fieldValue == null) { <END> throw new IOException("Cannot retrieve " + fieldPath + " for id=" +objectId); } return fieldValue; }</code><technical_language>I expect this defined in terms of inspect, avoid duplicating details of launching command</technical_language>

Target:
public @Nonnull String inspectRequiredField(@Nonnull EnvVars launchEnv, @Nonnull String objectId, @Nonnull String fieldPath) throws IOException, InterruptedException { final String fieldValue = inspect(launchEnv, objectId, fieldPath); if (fieldValue == null) { throw new IOException("Cannot retrieve " + fieldPath + " from 'docker inspect" + objectId + "'"); } return fieldValue; }
Source:
<code>public static JoinOperatorInfo createJoinOperatorInfo(JoinType joinType, long[] logHistogramCounters) { <START> long[] logHistogramProbes = new long[HISTOGRAM_SIZE]; <END> long[] logHistogramOutput = new long[HISTOGRAM_SIZE]; for (int i = 0; i < HISTOGRAM_SIZE; i++) { logHistogramProbes[i] = logHistogramCounters[2 * i]; logHistogramOutput[i] = logHistogramCounters[2 * i + 1]; } return new JoinOperatorInfo(joinType, logHistogramProbes, logHistogramOutput); }</code><technical_language>Inline declaration</technical_language>

Target:
public static JoinOperatorInfo createJoinOperatorInfo(JoinType joinType, long[] logHistogramCounters) { long[] logHistogramProbes = new long[HISTOGRAM_BUCKETS]; long[] logHistogramOutput = new long[HISTOGRAM_BUCKETS]; for (int i = 0; i < HISTOGRAM_BUCKETS; i++) { logHistogramProbes[i] = logHistogramCounters[2 * i]; logHistogramOutput[i] = logHistogramCounters[2 * i + 1]; } return new JoinOperatorInfo(joinType, logHistogramProbes, logHistogramOutput); }
Source:
<code>public void delete(final String evalId, @Nullable final EventHandler<AvroElasticMemoryMessage> callback) { final Set<String> dataTypeSet = partitionManager.getDataTypes(evalId); for (final String dataType : dataTypeSet) { final Set<LongRange> rangeSet = partitionManager.getRangeSet(evalId, dataType); if (!rangeSet.isEmpty()) { if (callback != null) { <START> LOG.log(Level.INFO, "{0}", rangeSet.size()); <END> final AvroElasticMemoryMessage msg = AvroElasticMemoryMessage.newBuilder() .setType(Type.ResultMsg) .setResultMsg(ResultMsg.newBuilder().setResult(Result.FAILURE).build()) .setSrcId(evalId) .setDestId("") .build(); callback.onNext(msg); } return; } } if (callback == null) { deleteExecutor.get().execute(evalId, new EventHandler<AvroElasticMemoryMessage>() { @Override public void onNext(final AvroElasticMemoryMessage msg) { } }); } else { deleteExecutor.get().execute(evalId, callback); } }</code><technical_language>This change is completely unrelated this PR. reason for adding it</technical_language>

Target:
public void delete(final String evalId, @Nullable final EventHandler<AvroElasticMemoryMessage> callback) { final Set<String> dataTypeSet = partitionManager.getDataTypes(evalId); for (final String dataType : dataTypeSet) { final Set<LongRange> rangeSet = partitionManager.getRangeSet(evalId, dataType); if (!rangeSet.isEmpty()) { if (callback != null) { final AvroElasticMemoryMessage msg = AvroElasticMemoryMessage.newBuilder() .setType(Type.ResultMsg) .setResultMsg(ResultMsg.newBuilder().setResult(Result.FAILURE).build()) .setSrcId(evalId) .setDestId("") .build(); callback.onNext(msg); } return; } } if (callback == null) { deleteExecutor.get().execute(evalId, new EventHandler<AvroElasticMemoryMessage>() { @Override public void onNext(final AvroElasticMemoryMessage msg) { } }); } else { deleteExecutor.get().execute(evalId, callback); } }
Source:
<code>public void deleteColumn(int columnIndex) { checkSimulation(); final GridColumn<?> toDelete = getColumns().get(columnIndex); deleteColumn(toDelete); simulation.removeFactMappingByIndex(columnIndex); <START> synchronizeFactMappingsWidths(); <END> }</code><technical_language>@yesamer I removed. synchronizeFactMappingsWidths put current columns widht factmappings, decided happen **only** user saves scenario - rely "status" implementation manage</technical_language>

Target:
public void deleteColumn(int columnIndex) { checkSimulation(); final GridColumn<?> toDelete = getColumns().get(columnIndex); deleteColumn(toDelete); simulation.removeFactMappingByIndex(columnIndex); }
Source:
<code>private void addRootProjection(SelectionSet selectionSet) { List<Selection> selections = selectionSet.getSelections(); Selection rootSelection = selections.get(0); if (!(rootSelection instanceof Field)) { throw new InvalidEntityBodyException("Entity selection must be a graphQL field."); } String entityName = ((Field) rootSelection).getName(); if (SCHEMA.equals(entityName) || TYPE.equals(entityName)) { return; } Class<?> entityType = entityDictionary.getEntityClass(entityName); if (entityType == null) { throw new InvalidEntityBodyException(String.format("Unknown entity {%s}.", entityName)); } rootLocation = rootSelection.getSourceLocation(); Field fields = (Field) rootSelection; selections.stream().skip(1).forEach(selection -> { if (!(selection instanceof Field)) { throw new InvalidEntityBodyException("Entity selection must be a graphQL field."); } <START> if (!entityName.equals(((Field) selection).getName())) { <END> throw new InvalidEntityBodyException("Can't select multiple entities in graphQL QUERY operation."); } fields.getSelectionSet().getSelections().addAll(((Field) selection).getSelectionSet().getSelections()); }); rootProjections.add(createProjection(entityType, fields)); }</code><technical_language>I understand this check is about</technical_language>

Target:
private void addRootProjection(SelectionSet selectionSet) { List<Selection> selections = selectionSet.getSelections(); Selection rootSelection = selections.get(0); if (!(rootSelection instanceof Field)) { throw new InvalidEntityBodyException("Entity selection must be a graphQL field."); } String entityName = ((Field) rootSelection).getName(); if (SCHEMA.equals(entityName) || TYPE.equals(entityName)) { return; } Class<?> entityType = entityDictionary.getEntityClass(entityName); if (entityType == null) { throw new InvalidEntityBodyException(String.format("Unknown entity {%s}.", entityName)); } Field fields = (Field) rootSelection; selections.stream().skip(1).forEach(selection -> { if (!(selection instanceof Field)) { throw new InvalidEntityBodyException("Entity selection must be a graphQL field."); } if (!entityName.equals(((Field) selection).getName())) { throw new InvalidEntityBodyException("Can't select multiple entities in graphQL QUERY operation."); } fields.getSelectionSet().getSelections().addAll(((Field) selection).getSelectionSet().getSelections()); }); rootProjections.add(createProjection(entityType, fields)); }
Source:
<code>private MySQLBasicDataSource(String host, int port, String dbName, String user, String password, int numConnections) { super(); <START> String url = "jdbc:mysql://" + (host + ":" + port + "/" + dbName+"?useUnicode=yes&characterEncoding=UTF-8"); <END> setDriverClassName("com.mysql.jdbc.Driver"); setUsername(user); setPassword(password); setUrl(url); setMaxActive(numConnections); setValidationQuery(" select 1"); setTestOnBorrow(true); if(monitorThread == null) { monitorThread = new MonitorThread(this); monitorThread.start(); } }</code><technical_language>Please add a space +, consistent rest of file</technical_language>

Target:
private MySQLBasicDataSource(String host, int port, String dbName, String user, String password, int numConnections) { super(); String url = "jdbc:mysql://" + (host + ":" + port + "/" + dbName); addConnectionProperty("useUnicode","yes"); addConnectionProperty("characterEncoding","UTF-8"); setDriverClassName("com.mysql.jdbc.Driver"); setUsername(user); setPassword(password); setUrl(url); setMaxActive(numConnections); setValidationQuery(" select 1"); setTestOnBorrow(true); if(monitorThread == null) { monitorThread = new MonitorThread(this); monitorThread.start(); } }
Source:
<code>public void whenReadEventsThenNakadiException() { final ImmutableList<RuntimeException> exceptions = ImmutableList.of(new NoOffsetForPartitionException( new TopicPartition("", 0)), new KafkaException()); int numberOfNakadiExceptions = 0; for (final Exception exception : exceptions) { final KafkaConsumer<String, String> kafkaConsumerMock = mock(KafkaConsumer.class); when(kafkaConsumerMock.poll(POLL_TIMEOUT)).thenThrow(exception); final KafkaFactory kafkaFactoryMock = createKafkaFactoryMock(kafkaConsumerMock); try { final NakadiKafkaConsumer consumer = new NakadiKafkaConsumer(kafkaFactoryMock, TOPIC, ImmutableMap.of(), POLL_TIMEOUT); consumer.readEvent(); <START> fail("The NakadiException should be thrown"); <END> } catch (Exception e) { numberOfNakadiExceptions++; } } assertThat("We should get a NakadiException for every call", numberOfNakadiExceptions, equalTo(exceptions.size())); }</code><technical_language>/NakadiException/Exception/</technical_language>

Target:
public void whenReadEventsThenNakadiException() { final ImmutableList<RuntimeException> exceptions = ImmutableList.of(new NoOffsetForPartitionException( new TopicPartition("", 0)), new KafkaException()); int numberOfNakadiExceptions = 0; for (final Exception exception : exceptions) { final KafkaConsumer<String, String> kafkaConsumerMock = mock(KafkaConsumer.class); when(kafkaConsumerMock.poll(POLL_TIMEOUT)).thenThrow(exception); final KafkaFactory kafkaFactoryMock = createKafkaFactoryMock(kafkaConsumerMock); try { final NakadiKafkaConsumer consumer = new NakadiKafkaConsumer(kafkaFactoryMock, TOPIC, ImmutableMap.of(), POLL_TIMEOUT); consumer.readEvent(); fail("An Exception was expected to be be thrown"); } catch (Exception e) { numberOfNakadiExceptions++; } } assertThat("We should get a NakadiException for every call", numberOfNakadiExceptions, equalTo(exceptions.size())); }
Source:
<code><START> private void scheduleCheckStatus() { <END> scheduledStatusCheckInProgress = true; Scheduler.get().scheduleFixedDelay( new Scheduler.RepeatingCommand() { @Override public boolean execute() { if (retryCount > MAX_RETRY_COUNTS || reportsWebappDeployed) { scheduledStatusCheckInProgress = false; return false; } retryCount++; checkReportsWebAppStatus(); return true; } }, RETRY_INTERVAL); }</code><technical_language>move if here? be- if (scheduledStatusCheckInProgress || retryCount > MAX_RETRY_COUNTS || reportsWebappDeployed) { return; } is if duplicating 'onError' 'Response.SC_NOT_FOUND'</technical_language>

Target:
private void scheduleCheckStatus() { if (scheduledStatusCheckInProgress || retryCount > MAX_RETRY_COUNTS || reportsWebappDeployed) { return; } scheduledStatusCheckInProgress = true; Scheduler.get().scheduleFixedDelay( new Scheduler.RepeatingCommand() { @Override public boolean execute() { if (retryCount > MAX_RETRY_COUNTS || reportsWebappDeployed) { scheduledStatusCheckInProgress = false; return false; } retryCount++; checkReportsWebAppStatus(); return true; } }, RETRY_INTERVAL); }
Source:
<code>public static void parseTimePeriod(Map<Integer, Integer> countOfAreaCodesForYear, JSONObject response) { try { JSONArray data = response.getJSONArray(DATA_KEY); for (int i = 0; i < data.length(); i++) { JSONObject o = (JSONObject) data.get(i); Integer year = getTimeperiodYear(o); <START> if (countOfAreaCodesForYear.containsKey(year)) { <END> Integer count = countOfAreaCodesForYear.get(year); count++; countOfAreaCodesForYear.put(year, count); } else { countOfAreaCodesForYear.put(year, 1); } } } catch (JSONException e) { LOG.error("Error parsing time period selectors for indicator: " + e.getMessage(), e); } }</code><technical_language>This if-else is readable asking change it, for fun curiosity note countOfAreaCodesForYear.merge(year, 1, Integer::sum); would've done thing</technical_language>

Target:
public static void parseTimePeriod(Map<Integer, Integer> countOfAreaCodesForYear, JSONObject response) { try { JSONArray data = response.getJSONArray(DATA_KEY); for (int i = 0; i < data.length(); i++) { JSONObject o = (JSONObject) data.get(i); Integer year = o.getInt(TIME_PERIOD_START_KEY); countOfAreaCodesForYear.merge(year, 1, Integer::sum); } } catch (JSONException e) { LOG.error("Error parsing time period selectors for indicator: " + e.getMessage(), e); } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SettingsFragment.setToChosenLanguage(this); PreferenceManager.setDefaultValues(this, R.xml.preferences, true); ScreenValueHandler.updateScreenWidthAndHeight(this); boolean hasUserAgreedToPrivacyPolicy = PreferenceManager.getDefaultSharedPreferences(this) .getBoolean(AGREED_TO_PRIVACY_POLICY_PREFERENCE_KEY, false); <START> boolean hasUserUpdatedPocketCode = hasUserUpdatedPocketCode(); <END> if (hasUserAgreedToPrivacyPolicy && !hasUserUpdatedPocketCode) { loadContent(); } else { setContentView(R.layout.privacy_policy_view); } }</code><technical_language>unnecessary boolean field. call method inline below, variable doesnt add for reader literally name method</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SettingsFragment.setToChosenLanguage(this); PreferenceManager.setDefaultValues(this, R.xml.preferences, true); ScreenValueHandler.updateScreenWidthAndHeight(this); int oldPrivacyPolicyHash = PreferenceManager.getDefaultSharedPreferences(this) .getInt(AGREED_TO_PRIVACY_POLICY_VERSION, 0); int currentPrivacyPolicyHash = getResources().getString(R.string.dialog_privacy_policy_text) .hashCode(); if (oldPrivacyPolicyHash == currentPrivacyPolicyHash) { loadContent(); } else { setContentView(R.layout.privacy_policy_view); } }
Source:
<code>public void zoomIn() { if (!zoomOutEnabled) { zoomOutEnabled = true; <START> } <END> double maxRange = layoutPanel.getFirstChild().getPlotRepresentation().getMaxRange(); for (PlotContainer pc : layoutPanel.getAllChildren()) { SimplePlot plot = pc.getPlotRepresentation().getSimplePlot(); Zoom zoom = Zoom.create().setAmount(1.1); plot.zoom(zoom); pc.getPlotRepresentation().calculateScrollWidth(); } PlotRepresentation plotRepresentation = layoutPanel.getFirstChild().getPlotRepresentation(); double percent; double minVisible = plotRepresentation.getSimplePlot().getAxes().getX().getMinimumValue(); double maxVisible = plotRepresentation.getSimplePlot().getAxes().getX().getMaximumValue(); percent = minVisible / (maxRange - maxVisible + minVisible); plotRepresentation.panToPercent(percent); }</code><technical_language>zoomOutEnabled = true; if do</technical_language>

Target:
public void zoomIn() { zoom(false); }
Source:
<code>protected void handleMissingToken( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException { <START> sendError(response, 401, "Authorization token is missed"); <END> }</code><technical_language>Authorization token is missing</technical_language>

Target:
protected void handleMissingToken( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException { sendError(response, 401, "Authorization token is missing"); }
Source:
<code>public Double arrayZero(String sampleName, Integer n ){ double[] sample=null; Integer i=null; try{ Preconditions.checkNotNull(sampleName, "sampleName"); Preconditions.checkNotNull(n, "n"); sample = (double[]) m_context.get("__"+sampleName); if(sample==null) throw new RuntimeException("not in jexl context: __"+sampleName); i = (Integer) m_context.get("__i"); if(i==null) throw new RuntimeException("not in jexl context: __i"); if(i-n < 0) return Double.valueOf(0); return sample[i-n]; } catch (Exception ex){ <START> LOG.error("problem retrieving prior sample "+sampleName+" (i - n) ("+i+"-"+n+")",ex); <END> } return Double.NaN; }</code><technical_language>need print full stack trace if catching exception threw in this function. prefer blocks like: if(sample==null) { LOG.warn("{} is in JEXL context. A NaN used.", sampleName); return Double.NaN; } instead of throwing/catching new exceptions</technical_language>

Target:
public Double arrayZero(String sampleName, Integer n ){ double[] sample=null; Integer i=null; try{ Preconditions.checkNotNull(sampleName, "sampleName"); Preconditions.checkNotNull(n, "n"); sample = (double[]) m_context.get("__"+sampleName); if(sample==null) { LOG.warn("fn:arrayZero attribute not in jexl context: __"+sampleName); return Double.NaN; } i = (Integer) m_context.get("__i"); Preconditions.checkNotNull(i, "sample index __i"); if(i-n < 0) return Double.valueOf(0); return sample[i-n]; } catch (Exception ex){ LOG.error("fn:arrayZero problem retrieving prior attribute sample "+sampleName+" (i - n) ("+i+"-"+n+")",ex); } return Double.NaN; }
Source:
<code>private static void copyAssetFileIfNeeded(RealmConfiguration configuration) { if (configuration.hasAssetFile()) { File realmFile = new File(configuration.getRealmDirectory(), configuration.getRealmFileName()); copyFileIfNeeded(configuration.getAssetFilePath(), realmFile); } <START> <END> String syncServerCertificateAssetName = ObjectServerFacade.getFacade(configuration.isSyncConfiguration()).getSyncServerCertificateAssetName(configuration); if (!TextUtils.isEmpty(syncServerCertificateAssetName)) { String syncServerCertificateFilePath = ObjectServerFacade.getFacade(configuration.isSyncConfiguration()).getSyncServerCertificateFilePath(configuration); File certificateFile = new File(syncServerCertificateFilePath); copyFileIfNeeded(syncServerCertificateAssetName, certificateFile); } }</code><technical_language>Unnecessary whitespace</technical_language>

Target:
private static void copyAssetFileIfNeeded(RealmConfiguration configuration) { if (configuration.hasAssetFile()) { File realmFile = new File(configuration.getRealmDirectory(), configuration.getRealmFileName()); copyFileIfNeeded(configuration.getAssetFilePath(), realmFile); } String syncServerCertificateAssetName = ObjectServerFacade.getFacade(configuration.isSyncConfiguration()).getSyncServerCertificateAssetName(configuration); if (!Util.isEmptyString(syncServerCertificateAssetName)) { String syncServerCertificateFilePath = ObjectServerFacade.getFacade(configuration.isSyncConfiguration()).getSyncServerCertificateFilePath(configuration); File certificateFile = new File(syncServerCertificateFilePath); copyFileIfNeeded(syncServerCertificateAssetName, certificateFile); } }
Source:
<code>protected void handleDelete(URL requestUrl, long gracePeriodSeconds, DeletionPropagation propagationPolicy, boolean cascading) throws ExecutionException, InterruptedException, KubernetesClientException, IOException { RequestBody requestBody = null; DeleteOptions deleteOptions = new DeleteOptions(); if (gracePeriodSeconds >= 0) { deleteOptions.setGracePeriodSeconds(gracePeriodSeconds); } if (propagationPolicy != null) { <START> if (Arrays.stream(DeletionPropagation.values()).noneMatch(deletionPropagation -> deletionPropagation.name().equals(propagationPolicy))) { logger.warn("Unknown DeletionPropagation policy used for deletion: {}", propagationPolicy); } <END> deleteOptions.setPropagationPolicy(propagationPolicy.toString()); } else { deleteOptions.setOrphanDependents(!cascading); } requestBody = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(deleteOptions)); Request.Builder requestBuilder = new Request.Builder().delete(requestBody).url(requestUrl); handleResponse(requestBuilder, null, Collections.<String, String>emptyMap()); }</code><technical_language>This check necessary more enum</technical_language>

Target:
protected void handleDelete(URL requestUrl, long gracePeriodSeconds, DeletionPropagation propagationPolicy, boolean cascading) throws ExecutionException, InterruptedException, IOException { RequestBody requestBody = null; DeleteOptions deleteOptions = new DeleteOptions(); if (gracePeriodSeconds >= 0) { deleteOptions.setGracePeriodSeconds(gracePeriodSeconds); } if (propagationPolicy != null) { deleteOptions.setPropagationPolicy(propagationPolicy.toString()); } else { deleteOptions.setOrphanDependents(!cascading); } requestBody = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(deleteOptions)); Request.Builder requestBuilder = new Request.Builder().delete(requestBody).url(requestUrl); handleResponse(requestBuilder, null, Collections.<String, String>emptyMap()); }
Source:
<code>private void doGetNextBatch() { if (splitsProduced >= totalSplits) { switch (atSplitDepletion) { case FAIL: nextBatchFuture.setException(new IllegalStateException("Mock failure")); break; case FINISH: nextBatchFuture.set(ImmutableList.of()); break; case DO_NOTHING: break; default: <START> throw new UnsupportedOperationException(); <END> } } int splits = Math.min(Math.min(batchSize, nextBatchMaxSize), totalSplits - splitsProduced); if (splits != 0) { splitsProduced += splits; nextBatchFuture.set(Collections.nCopies(splits, SPLIT)); } }</code><technical_language>purpose of FAIL? I in tests checks for this exception occur. confused fact IllegalStateException (vs a specific exception tested) generic message</technical_language>

Target:
private void doGetNextBatch() { checkState(splitsProduced <= totalSplits); if (splitsProduced == totalSplits) { switch (atSplitDepletion) { case FAIL: nextBatchFuture.setException(new IllegalStateException("Mock failure")); break; case FINISH: nextBatchFuture.set(ImmutableList.of()); break; case DO_NOTHING: break; default: throw new UnsupportedOperationException(); } } int splits = Math.min(Math.min(batchSize, nextBatchMaxSize), totalSplits - splitsProduced); if (splits != 0) { splitsProduced += splits; nextBatchFuture.set(Collections.nCopies(splits, SPLIT)); } }
Source:
<code>public void deserialize(String name, String value, boolean isSecure, String encryptedValue) throws InvalidCipherTextException { setName(name); setIsSecure(isSecure); if (isSecure) { if (isNotBlank(value) && isNotBlank(encryptedValue)) { <START> System.out.println("lo = "); <END> addError("value", "You may only specify `value` or `encrypted_value`, not both!"); addError("encryptedValue", "You may only specify `value` or `encrypted_value`, not both!"); } if (isNotBlank(value)) { setEncryptedValue(new EncryptedVariableValueConfig(new GoCipher().encrypt(value))); } if (isNotBlank(encryptedValue)) { setEncryptedValue(new EncryptedVariableValueConfig(encryptedValue)); } } else { setValue(new VariableValueConfig(value)); } }</code><technical_language>missed this</technical_language>

Target:
public void deserialize(String name, String value, boolean isSecure, String encryptedValue) throws InvalidCipherTextException { setName(name); setIsSecure(isSecure); if (isSecure) { if (isNotBlank(value) && isNotBlank(encryptedValue)) { addError("value", "You may only specify `value` or `encrypted_value`, not both!"); addError("encryptedValue", "You may only specify `value` or `encrypted_value`, not both!"); } if (isNotBlank(value)) { setEncryptedValue(new EncryptedVariableValueConfig(new GoCipher().encrypt(value))); } if (isNotBlank(encryptedValue)) { setEncryptedValue(new EncryptedVariableValueConfig(encryptedValue)); } } else { setValue(new VariableValueConfig(value)); } }
Source:
<code><START> public DataCenterInfoResponseHandler(DateCodecFactory dateCodecFactory) { <END> super(dateCodecFactory); }</code><technical_language>here, this package private</technical_language>

Target:
DataCenterInfoResponseHandler(DateCodecFactory dateCodecFactory) { super(dateCodecFactory); }
Source:
<code>public void testOpenJavaEditor() throws Exception { <START> <END> ICompilationUnit unit= createTestCU(); EditorUtility.openInEditor(unit); Set set= new HashSet(); set.addAll(Arrays.asList(inactiveBundles)); checkNotLoaded(set); }</code><technical_language>2 lines removed</technical_language>

Target:
public void testOpenJavaEditor() throws Exception { ICompilationUnit unit= createTestCU(); EditorUtility.openInEditor(unit); Set<String> set= new HashSet<>(Arrays.asList(inactiveTestBundles)); checkNotLoaded(set); }
Source:
<code>public void logPendingDeletion(String classTag, String reason) { String logMessage = String.format( <START> "Wiping form record with id %1$s and submission ordering number %2$s " + <END> "in class %3$s because %4$s", getInstanceID(), getSubmissionOrderingNumber(), classTag, reason); Logger.log(AndroidLogger.TYPE_FORM_DELETION, logMessage); }</code><technical_language>%s instead of %[*]$s for</technical_language>

Target:
public void logPendingDeletion(String classTag, String reason) { String logMessage = String.format( "Wiping form record with id %s and submission ordering number %s " + "in class %s because %s", getInstanceID(), getSubmissionOrderingNumber(), classTag, reason); Logger.log(AndroidLogger.TYPE_FORM_DELETION, logMessage); }
Source:
<code>public static void main(String[] args) { final String key = "your key"; final String secret = "your secret"; Token token = new Token("", ""); <START> OAuthService service = new ServiceBuilder().apiKey(key).apiSecret(secret).provider(ECHOApi.class).build(); <END> System.out.println("Now we're going to access a protected resource..."); OAuthRequest request = new OAuthRequest(Verb.POST, PROTECTED_RESOURCE_URL); request.addBodyParameter("content", "your valid activity streams xml"); service.signRequest(token, request); Response response = request.send(); System.out.println(); System.out.println(response.getCode()); System.out.println(response.getBody()); System.out.println(); System.out.println("Thats it man! Go and build something awesome with Scribe! :)"); }</code><technical_language>class is named EchoApi ECHOApi. This code compile</technical_language>

Target:
public static void main(String[] args) { final String key = "your key"; final String secret = "your secret"; Token token = new Token("", ""); OAuthService service = new ServiceBuilder().apiKey(key).apiSecret(secret).provider(EchoApi.class).build(); System.out.println("Now we're going to access a protected resource..."); OAuthRequest request = new OAuthRequest(Verb.POST, PROTECTED_RESOURCE_URL); request.addBodyParameter("content", "your valid activity streams xml"); service.signRequest(token, request); Response response = request.send(); System.out.println(); System.out.println(response.getCode()); System.out.println(response.getBody()); System.out.println(); System.out.println("Thats it man! Go and build something awesome with Scribe! :)"); }
Source:
<code>protected long getClosestDiskSizeInGB(long sizeInBytes) { if (sizeInBytes < 0) { throw new CloudRuntimeException("Disk size should be greater than 0 bytes, received: " + sizeInBytes + " bytes"); } long div = sizeInBytes / GB_UNIT_BYTES; long rest = sizeInBytes % GB_UNIT_BYTES; <START> return rest == 0L ? div : div + 1; <END> }</code><technical_language>this simplified Math.ceil()</technical_language>

Target:
protected long getClosestDiskSizeInGB(long sizeInBytes) { if (sizeInBytes < 0) { throw new CloudRuntimeException("Disk size should be greater than 0 bytes, received: " + sizeInBytes + " bytes"); } return (long) Math.ceil(1.0 * sizeInBytes / GB_UNIT_BYTES); }
Source:
<code>public Link getLink(ObjectNode linkNode, String location, ParseResult result) { if (linkNode == null) { return null; } Link link = new Link(); JsonNode ref = linkNode.get("$ref"); if (ref != null) { if (ref.getNodeType().equals(JsonNodeType.STRING)) { } else { result.invalidType(location, "$ref", "string", linkNode); return null; } } String value = getString("operationRef", linkNode, false, location, result); <START> link.setOperationRef(value); <END> value = getString("operationId", linkNode, false, location, result); link.setOperationId(value); ObjectNode parametersObject = getObject("parameters",linkNode,false,location,result); if (parametersObject!= null) { link.setParameters(getLinkParameters(parametersObject, location, result)); } ObjectNode headerObject = getObject("headers",linkNode,false,location,result); if (headerObject!= null) { link.setHeaders(getHeaders(headerObject, location, result)); } ObjectNode serverObject = getObject("server",linkNode,false,location,result); if (serverObject!= null) { link.setServer(getServer(serverObject, location, result)); } value = getString("description", linkNode, false, location, result); link.setDescription(value); link.setExtensions(new LinkedHashMap<>()); Set<String> keys = getKeys(linkNode); for (String key : keys) { if (key.startsWith("x-")) { link.getExtensions().put(key, Json.mapper().convertValue(linkNode.get(key), Object.class)); } } return link; }</code><technical_language>do a StringUtils.isNotBlank(...) check setting</technical_language>

Target:
public Link getLink(ObjectNode linkNode, String location, ParseResult result) { if (linkNode == null) { return null; } Link link = new Link(); JsonNode ref = linkNode.get("$ref"); if (ref != null) { if (ref.getNodeType().equals(JsonNodeType.STRING)) { } else { result.invalidType(location, "$ref", "string", linkNode); return null; } } String value = getString("operationRef", linkNode, false, location, result); if(StringUtils.isNotBlank(value)){ link.setOperationRef(value); } value = getString("operationId", linkNode, false, location, result); if(StringUtils.isNotBlank(value)){ link.setOperationId(value); } ObjectNode parametersObject = getObject("parameters",linkNode,false,location,result); if (parametersObject!= null) { link.setParameters(getLinkParameters(parametersObject, location, result)); } ObjectNode headerObject = getObject("headers",linkNode,false,location,result); if (headerObject!= null) { link.setHeaders(getHeaders(headerObject, location, result)); } ObjectNode serverObject = getObject("server",linkNode,false,location,result); if (serverObject!= null) { link.setServer(getServer(serverObject, location, result)); } value = getString("description", linkNode, false, location, result); if(StringUtils.isNotBlank(value)){ link.setDescription(value); } Map <String,Object> extensions = getExtensions(linkNode,location,result); if(extensions != null && extensions.size() > 0) { link.setExtensions(extensions); } return link; }
Source:
<code>public HttpResponse doUpdateResult(@QueryParameter String election) throws IOException { if (!isOpen(election)){ <START> countVotes(election); <END> applySingleTransferableVote( election ); } return new HttpRedirect("/election/results"); }</code><technical_language>clear this is called, concerned this action is re-process a CSV file, rewrite a new file, run a python process</technical_language>

Target:
public HttpResponse doUpdateResult(@QueryParameter String election) throws IOException { if (!isOpen(election) && isAdmin()){ countVotes(election); applySingleTransferableVote( election ); } return new HttpRedirect("/election/results"); }
Source:
<code><START> public void updateFeedbackQuestion(FeedbackQuestionAttributes newAttributes, boolean hasResponseRateUpdate) <END> throws InvalidParametersException, EntityDoesNotExistException { FeedbackQuestionAttributes oldQuestion = null; if (newAttributes.getId() == null) { oldQuestion = fqDb.getFeedbackQuestion(newAttributes.feedbackSessionName, newAttributes.courseId, newAttributes.questionNumber); } else { oldQuestion = fqDb.getFeedbackQuestion(newAttributes.getId()); } if (oldQuestion == null) { throw new EntityDoesNotExistException( "Trying to update a feedback question that does not exist."); } if(oldQuestion.isChangesRequiresResponseDeletion(newAttributes)) { frLogic.deleteFeedbackResponsesForQuestionAndCascade(oldQuestion.getId(), hasResponseRateUpdate); } oldQuestion.updateValues(newAttributes); newAttributes.removeIrrelevantVisibilityOptions(); fqDb.updateFeedbackQuestion(newAttributes); }</code><technical_language>@unyoungwax, able this private too</technical_language>

Target:
private void updateFeedbackQuestion(FeedbackQuestionAttributes newAttributes, boolean hasResponseRateUpdate) throws InvalidParametersException, EntityDoesNotExistException { FeedbackQuestionAttributes oldQuestion = null; if (newAttributes.getId() == null) { oldQuestion = fqDb.getFeedbackQuestion(newAttributes.feedbackSessionName, newAttributes.courseId, newAttributes.questionNumber); } else { oldQuestion = fqDb.getFeedbackQuestion(newAttributes.getId()); } if (oldQuestion == null) { throw new EntityDoesNotExistException( "Trying to update a feedback question that does not exist."); } if(oldQuestion.isChangesRequiresResponseDeletion(newAttributes)) { frLogic.deleteFeedbackResponsesForQuestionAndCascade(oldQuestion.getId(), hasResponseRateUpdate); } oldQuestion.updateValues(newAttributes); newAttributes.removeIrrelevantVisibilityOptions(); fqDb.updateFeedbackQuestion(newAttributes); }
Source:
<code>public void migrateIfNecessary_1_1_to_1_2() throws Exception { String toMigrate = getFileContent("scesim-1-1.scesim"); String migrated = migrationInstance.from1_1to1_2().apply(toMigrate); assertTrue(toMigrate.contains("<ScenarioSimulationModel version=\"1.1\">")); <START> assertFalse(migrated.contains("<ScenarioSimulationModel version=\"1.1\">")); <END> assertTrue(migrated.contains("dmoSession></dmoSession>")); assertTrue(migrated.contains("<type>RULE</type>")); }</code><technical_language>@danielezonca This is missing crucial test, i.e. migrated version "1.2"</technical_language>

Target:
public void migrateIfNecessary_1_1_to_1_2() throws Exception { String toMigrate = getFileContent("scesim-1-1.scesim"); String migrated = migrationInstance.from1_1to1_2().apply(toMigrate); assertTrue(toMigrate.contains("<ScenarioSimulationModel version=\"1.1\">")); assertFalse(migrated.contains("<ScenarioSimulationModel version=\"1.1\">")); assertTrue(migrated.contains("<ScenarioSimulationModel version=\"1.2\">")); assertTrue(migrated.contains("dmoSession></dmoSession>")); assertTrue(migrated.contains("<type>RULE</type>")); }
Source:
<code>public EventJob(String thingUID, String channelID, String event) { <START> checkNotNull(thingUID, "Thing UID cannot be null"); <END> checkNotNull(channelID, "Channel ID cannot be null"); checkNotNull(event, "Event cannot be null"); this.thingUID = thingUID; this.channelID = channelID; this.event = event; }</code><technical_language>Please change a normal null check throw a IllegalArgumentException. This is more meaningful throwing NPE here</technical_language>

Target:
public EventJob(String thingUID, String channelID, String event) { checkArgument(thingUID != null, "Thing UID cannot be null"); checkArgument(channelID != null, "Channel ID cannot be null"); checkArgument(event != null, "Event cannot be null"); this.thingUID = thingUID; this.channelID = channelID; this.event = event; }
Source:
<code>public void setup() throws Exception { <START> Field field = JpaUserDao.class.getDeclaredField("managerProvider"); <END> field.setAccessible(true); field.set(userDao, managerProvider); EntityManager entityManager = mock(EntityManager.class); when(entityManager.createNamedQuery(anyString(), anyObject())).thenReturn(typedQuery); when(managerProvider.get()).thenReturn(entityManager); when(typedQuery.setMaxResults(anyInt())).thenReturn(typedQuery); when(typedQuery.setFirstResult(anyInt())).thenReturn(typedQuery); when(typedQuery.setFirstResult(anyInt())).thenReturn(typedQuery); }</code><technical_language>please @InjectMocks instead</technical_language>

Target:
public void setup() throws Exception { EntityManager entityManager = mock(EntityManager.class); when(entityManager.createNamedQuery(anyString(), anyObject())).thenReturn(typedQuery); when(managerProvider.get()).thenReturn(entityManager); when(typedQuery.setMaxResults(anyInt())).thenReturn(typedQuery); when(typedQuery.setFirstResult(anyInt())).thenReturn(typedQuery); when(typedQuery.setFirstResult(anyInt())).thenReturn(typedQuery); }