auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void showStoragePermissionRevokedNotification() { Intent intent = new Intent(mContext, FirstStartActivity.class); Notification n = getNotificationBuilder(mInfoChannel) .setContentTitle(mContext.getString(R.string.syncthing_terminated)) <START> .setContentText(mContext.getString(R.string.toast_write_storage_permission_required)) <END> .setSmallIcon(R.drawable.ic_stat_notify) .setContentIntent(PendingIntent.getActivity(mContext, 0, intent, 0)) .setAutoCancel(true) .setOnlyAlertOnce(true) .build(); mNotificationManager.notify(ID_MISSINGPERM, n); }</code><technical_language>string anywhere</technical_language>

Target:
public void showStoragePermissionRevokedNotification() { Intent intent = new Intent(mContext, FirstStartActivity.class); Notification n = getNotificationBuilder(mInfoChannel) .setContentTitle(mContext.getString(R.string.syncthing_terminated)) .setContentText(mContext.getString(R.string.toast_write_storage_permission_required)) .setSmallIcon(R.drawable.ic_stat_notify) .setContentIntent(PendingIntent.getActivity(mContext, 0, intent, 0)) .setAutoCancel(true) .setOnlyAlertOnce(true) .build(); mNotificationManager.notify(ID_MISSING_PERM, n); }
Source:
<code>public static void initialize() { assumeTrue(testTrace.exists()); <START> stateFile = new File(TmfTraceManager.getSupplementaryFileDir(testTrace.getTrace()) + TEST_FILE_NAME); <END> TestLttngKernelAnalysisModule module = new TestLttngKernelAnalysisModule(TEST_FILE_NAME); try { module.setTrace(testTrace.getTrace()); } catch (TmfAnalysisException e) { fail(); } module.schedule(); assertTrue(module.waitForCompletion(new NullProgressMonitor())); ssq = module.getStateSystem(); assertNotNull(ssq); }</code><technical_language>Is a reason File.createTempFile() anymore? advantage guaranteed get a "new", non-existing file time (it adds a random suffix extension). If not, check if file exists delete if does</technical_language>

Target:
public static void initialize() { assumeTrue(testTrace.exists()); try { stateFile = File.createTempFile("test-partial", ".ht"); input = new LttngKernelStateProvider(testTrace.getTrace()); ssq = TmfStateSystemFactory.newPartialHistory(stateFile, input, true); } catch (IOException e) { fail(); } catch (TmfTraceException e) { fail(); } }
Source:
<code>private static void speedUpDcoumentBuilderFactory() { <START> String className = System.getProperty(DOCUMENT_BUILDER_FACTORY_PROP_NAME); <END> if (className == null) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (DOCUMENT_BUILDER_FACTORY_IMPL_CLASS_NAME.equals(factory.getClass().getName())) { System.setProperty(DOCUMENT_BUILDER_FACTORY_PROP_NAME, DOCUMENT_BUILDER_FACTORY_IMPL_CLASS_NAME); } } }</code><technical_language>Inline</technical_language>

Target:
private static void speedUpDcoumentBuilderFactory() { if (System.getProperty(DOCUMENT_BUILDER_FACTORY_PROP_NAME) == null) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (DOCUMENT_BUILDER_FACTORY_IMPL_CLASS_NAME.equals(factory.getClass().getName())) { System.setProperty(DOCUMENT_BUILDER_FACTORY_PROP_NAME, DOCUMENT_BUILDER_FACTORY_IMPL_CLASS_NAME); } } }
Source:
<code>public void generateSpreadsheet(HttpServletResponse response, String filename) { Set<Attends> attends = executionCourse.getAttendsSet(); final SpreadsheetBuilder builder = new SpreadsheetBuilder(); builder.addSheet(executionCourse.getPrettyAcronym().concat("Attends"), new SheetData<Attends>(attends) { protected String getLabel(final String key) { return BundleUtil.getString(Bundle.APPLICATION, key); } @Override protected void makeLine(final Attends attends) { addCell(getLabel("label.username"), attends.getRegistration().getPerson().getUsername()); addCell(getLabel("label.number"), attends.getRegistration().getNumber()); addCell(getLabel("label.name"), attends.getRegistration().getPerson().getPresentationName()); addCell(getLabel("label.Degree"), attends.getStudentCurricularPlanFromAttends().getDegreeCurricularPlan() .getPresentationName()); addCell(getLabel("label.attends.enrollmentState"), BundleUtil.getString(Bundle.ENUMERATION, attends.getAttendsStateType().getQualifiedName())); executionCourse.getAssociatedEvaluationsSet().forEach( ev -> addCell( ev.getPresentationName(), attends.getAssociatedMarksSet().stream().filter(mark -> mark.getEvaluation() == ev) .map(Mark::getMark).findAny().orElse(""))); } }); try { builder.build(WorkbookExportFormat.EXCEL, response.getOutputStream()); response.setHeader("Content-disposition", "attachment; filename=" + filename); response.setContentType("application/vnd.ms-excel"); response.flushBuffer(); } catch (IOException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>throw exception..</technical_language>

Target:
public void generateSpreadsheet(HttpServletResponse response, String filename) throws IOException { Set<Attends> attends = executionCourse.getAttendsSet(); final SpreadsheetBuilder builder = new SpreadsheetBuilder(); builder.addSheet(executionCourse.getPrettyAcronym().concat("Attends"), new SheetData<Attends>(attends) { protected String getLabel(final String key) { return BundleUtil.getString(Bundle.APPLICATION, key); } @Override protected void makeLine(final Attends attends) { addCell(getLabel("label.username"), attends.getRegistration().getPerson().getUsername()); addCell(getLabel("label.number"), attends.getRegistration().getNumber()); addCell(getLabel("label.name"), attends.getRegistration().getPerson().getPresentationName()); addCell(getLabel("label.Degree"), attends.getStudentCurricularPlanFromAttends().getDegreeCurricularPlan() .getPresentationName()); addCell(getLabel("label.attends.enrollmentState"), BundleUtil.getString(Bundle.ENUMERATION, attends.getAttendsStateType().getQualifiedName())); executionCourse.getAssociatedEvaluationsSet().forEach( ev -> addCell( ev.getPresentationName(), attends.getAssociatedMarksSet().stream().filter(mark -> mark.getEvaluation() == ev) .map(Mark::getMark).findAny().orElse(""))); } }); builder.build(WorkbookExportFormat.EXCEL, response.getOutputStream()); response.setHeader("Content-disposition", "attachment; filename=" + filename); response.setContentType("application/vnd.ms-excel"); response.flushBuffer(); }
Source:
<code>public boolean supports(int capability) { if (mBridge != null) { if (mBridge.getApiLevel() > 12) { return mBridge.getFeatures().contains(capability); } else { <START> return capability < 14 <END> && mBridge.getCapabilities().contains(Capability.values()[capability]); } } if (mLegacyBridge != null) { if (capability == Features.UNBOUND_RENDERING) { return getLegacyApiLevel() == 4; } } return false; }</code><technical_language>symbolic name for feature supported in release is (along <= instead of <)</technical_language>

Target:
public boolean supports(int capability) { if (mBridge != null) { if (mBridge.getApiLevel() > 12) { return mBridge.supports(capability); } else { return capability <= Features.SIMULATE_PLATFORM && mBridge.getCapabilities().contains(Capability.values()[capability]); } } if (mLegacyBridge != null) { if (capability == Features.UNBOUND_RENDERING) { return getLegacyApiLevel() == 4; } } return false; }
Source:
<code>private ICPPClassType getFirstCandidateForNamingClass(IASTName name) throws DOMException { LookupData data = new LookupData(name); isUnqualifiedLookup= !data.qualified; ICPPScope scope = CPPSemantics.getLookupScope(name); while (scope != null && !(scope instanceof ICPPClassScope)) { if (scope instanceof ICPPInternalUnknownScope) { IType scopeType = ((ICPPInternalUnknownScope) scope).getScopeType(); if (scopeType instanceof ICPPDeferredClassInstance) { return ((ICPPDeferredClassInstance) scopeType).getClassTemplate(); } if (scopeType instanceof ICPPUnknownMemberClass && isPrefixLookup) { scopeType = HeuristicResolver.resolveUnknownType((ICPPUnknownMemberClass) scopeType, name.getParent()); if (scopeType instanceof ICPPClassType) { return (ICPPClassType) scopeType; } } <START> break; <END> } scope = CPPSemantics.getParentScope(scope, data.getTranslationUnit()); } if (scope instanceof ICPPClassScope) { return ((ICPPClassScope) scope).getClassType(); } return null; }</code><technical_language>This break necessary. If parent scope is unknown scope, loop exit anyways</technical_language>

Target:
private ICPPClassType getFirstCandidateForNamingClass(IASTName name) throws DOMException { LookupData data = new LookupData(name); isUnqualifiedLookup= !data.qualified; ICPPScope scope = CPPSemantics.getLookupScope(name); while (scope != null && !(scope instanceof ICPPClassScope)) { if (scope instanceof ICPPInternalUnknownScope) { IType scopeType = ((ICPPInternalUnknownScope) scope).getScopeType(); if (scopeType instanceof ICPPDeferredClassInstance) { return ((ICPPDeferredClassInstance) scopeType).getClassTemplate(); } if (scopeType instanceof ICPPUnknownMemberClass && isPrefixLookup) { scopeType = HeuristicResolver.resolveUnknownType((ICPPUnknownMemberClass) scopeType, name.getParent()); if (scopeType instanceof ICPPClassType) { return (ICPPClassType) scopeType; } } } scope = CPPSemantics.getParentScope(scope, data.getTranslationUnit()); } if (scope instanceof ICPPClassScope) { return ((ICPPClassScope) scope).getClassType(); } return null; }
Source:
<code>public JSONArray toFlatJson(String[] selectedResults) { JSONArray results = new JSONArray(); if (selectedResults == null || selectedResults.length == 0) { for (HashMap.Entry<String, MetricInfo> entry : metrics.entrySet()) { MetricInfo metric = entry.getValue(); <START> if (metric.metric == null) <END> { continue; } JSONObject obj = serializeMetric(metric, true); results.put(obj); } } else { for (int i = 0; i < selectedResults.length; i++) { MetricInfo metric = metrics.get(selectedResults[i]); if (metric == null || metric.metric == null) { continue; } JSONObject obj = serializeMetric(metric,true); results.put(obj); } } return results; }</code><technical_language>if (metric || metric.metric == null) above? Also, for aesthetics, if changes in this code, refactor metric var lines 205,234 248 metricinfo currmetric</technical_language>

Target:
public JSONArray toFlatJson(String[] selectedResults) { JSONArray results = new JSONArray(); if (selectedResults == null || selectedResults.length == 0) { for (HashMap.Entry<String, MetricInfo> entry : metrics.entrySet()) { MetricInfo metricInfo = entry.getValue(); if (metricInfo == null || metricInfo.metric == null) { continue; } JSONObject obj = serializeMetric(metricInfo, true); results.put(obj); } } else { for (int i = 0; i < selectedResults.length; i++) { MetricInfo metricInfo = metrics.get(selectedResults[i]); if (metricInfo == null || metricInfo.metric == null) { continue; } JSONObject obj = serializeMetric(metricInfo,true); results.put(obj); } } return results; }
Source:
<code>public Void perform(TaskActionToolbox toolbox) { final List<TaskLock> taskLocks = toolbox.getTaskLockbox().findLocksForTask(task); for(final DataSegment segment : segments) { final boolean ok = Iterables.any( taskLocks, new Predicate<TaskLock>() { @Override public boolean apply(TaskLock taskLock) { return taskLock.getVersion().equals(segment.getVersion()) <START> && taskLock.getDataSource().equals(segment.getDataSource()) <END> && taskLock.getInterval().contains(segment.getInterval()); } } ); if(!ok) { throw new ISE("No currently-held lock covers segment: %s", segment); } } try { toolbox.getMergerDBCoordinator().announceHistoricalSegments(segments); final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder() .setUser2(task.getDataSource()) .setUser4(task.getType()); for (DataSegment segment : segments) { metricBuilder.setUser5(segment.getInterval().toString()); toolbox.getEmitter().emit(metricBuilder.build("indexer/segment/bytes", segment.getSize())); } return null; } catch (Exception e) { throw Throwables.propagate(e); } }</code><technical_language>do eic</technical_language>

Target:
public Void perform(TaskActionToolbox toolbox) { if(!toolbox.taskLockCoversSegments(task, segments, false)) { throw new ISE("Segments not covered by locks for task: %s", task.getId()); } try { toolbox.getMergerDBCoordinator().announceHistoricalSegments(segments); final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder() .setUser2(task.getDataSource()) .setUser4(task.getType()); for (DataSegment segment : segments) { metricBuilder.setUser5(segment.getInterval().toString()); toolbox.getEmitter().emit(metricBuilder.build("indexer/segment/bytes", segment.getSize())); } return null; } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
<code>public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); FeedbackSessionAttributes feedbackSession = getFeedbackSession(feedbackSessionName, courseId); <START> InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, userInfo.getId()); <END> gateKeeper.verifyAccessible(instructor, feedbackSession, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); }</code><technical_language>Unnecessary line move</technical_language>

Target:
public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, userInfo.getId()); FeedbackSessionAttributes feedbackSession = getNonNullFeedbackSession(feedbackSessionName, courseId); gateKeeper.verifyAccessible(instructor, feedbackSession, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); }
Source:
<code>public synchronized void syncTask(Host host, Task task){ <START> if (host == null){ <END> host = getActiveHost(); log.warn("host is null, task will be sync by any active host {}", task.getName(), host.getName()); } try { host.getRunningTasks().put(task.getId(), task); log.debug("sync task:{} to host:{}", task.getName(), host.getName()); TaskProcessor.setTasksMap(host.getName(), task.getId()); }catch (Exception e){ log.error("something went wrong durring task sync {}", e); } }</code><technical_language>do this check. issue in other place of code</technical_language>

Target:
public synchronized void syncTask(Host host, Task task){ if (host == null){ host = getActiveHost(); log.debug("host is null, task will be sync by any active host {}", task.getName(), host.getName()); } try { host.getRunningTasks().put(task.getId(), task); log.debug("sync task:{} to host:{}", task.getName(), host.getName()); TaskProcessor.setTasksMap(host.getName(), task.getId()); }catch (Exception e){ log.error("something went wrong durring task sync {}", e); } }
Source:
<code>public void dispatchEvent(final Object sink, final IEvent<?> event, final Component component) { AnnotationEventSink eventSink = eventSinkByClass.get(sink.getClass()); AnnotationEventDispatcherConfig config = Application.get().getMetaData( Initializer.ANNOTATION_EVENT_DISPATCHER_CONFIG_CONTEXT_KEY); if (eventSink != null && eventSink != EMPTY_SINK && (config.getEventFilter() == null || config.getEventFilter().isAssignableFrom( event.getPayload().getClass())) <START> && (config.isDispatchToNonVisibleComponents() || isVisible(sink))) <END> { eventSink.onEvent(sink, event); } }</code><technical_language>s/NonVisible/Invisible/ ? similar for disabled components ?</technical_language>

Target:
public void dispatchEvent(final Object sink, final IEvent<?> event, final Component component) { AnnotationEventSink eventSink = eventSinkByClass.get(sink.getClass()); AnnotationEventDispatcherConfig config = Application.get().getMetaData( Initializer.ANNOTATION_EVENT_DISPATCHER_CONFIG_CONTEXT_KEY); if (eventSink != null && eventSink != EMPTY_SINK && (config.getEventFilter() == null || config.getEventFilter().isAssignableFrom( event.getPayload().getClass()))) { eventSink.onEvent(sink, event); } }
Source:
<code>public Configuration getConfiguration(GraphContext context) { return ConfigurationBuilder.begin() .addRule() .when(Query.fromType(WindupConfigurationModel.class).withProperty(WindupConfigurationModel.CSV_MODE,true) .and(Query.fromType(ClassificationModel.class).as("classifications") <START> .and(Query.fromType(InlineHintModel.class).as("hints") <END> .and(Query.fromType(ProjectModel.class).as("projects"))))) .perform( Iteration.over(Iteration.DEFAULT_VARIABLE_LIST_STRING).perform( new ExportCSVReportOperation()).endIteration()); }</code><technical_language>I this moved operation itself. Rewrite do short-circuit evaluation, queries run export is enabled. In case of a large application, this is adding a bit of time windup run</technical_language>

Target:
public Configuration getConfiguration(GraphContext context) { return ConfigurationBuilder.begin() .addRule() .when(Query.fromType(WindupConfigurationModel.class).withProperty(WindupConfigurationModel.CSV_MODE,true)) .perform( Iteration.over(Iteration.DEFAULT_VARIABLE_LIST_STRING).perform( new ExportCSVReportOperation()).endIteration()); }
Source:
<code>public long getFrom( TemporalAccessor temporal ) { <START> throw new UnsupportedTemporalTypeException( "We don't support anything." ); <END> }</code><technical_language>want change message juuuust a bit</technical_language>

Target:
public long getFrom( TemporalAccessor temporal ) { throw new UnsupportedOperationException( "Getting a " + this.name + " from temporal values is not supported." ); }
Source:
<code>public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { CompositeChange change = new CompositeChange(MessageFormat.format(PDEUIMessages.RenamePluginProcessor_changeTitle, new Object[] {fInfo.getCurrentValue(), fInfo.getNewValue()})); <START> SubMonitor subMonitor = SubMonitor.convert(pm, "", getTotalWork()); END> CreateHeaderChangeOperation op = new CreateHeaderChangeOperation(fInfo.getBase(), Constants.BUNDLE_SYMBOLICNAME, fInfo.getCurrentValue(), fInfo.getNewValue()); op.run(subMonitor.newChild(1)); change.add(op.getChange()); if (fInfo.isRenameProject()) { change.add(createProjectChange(subMonitor.newChild( 1))); } if (fInfo.isUpdateReferences()) change.addAll(createReferenceChanges(subMonitor.newChild(2))); return change; }</code><technical_language>parameter constructor</technical_language>

Target:
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { CompositeChange change = new CompositeChange(MessageFormat.format(PDEUIMessages.RenamePluginProcessor_changeTitle, new Object[] {fInfo.getCurrentValue(), fInfo.getNewValue()})); SubMonitor subMonitor = SubMonitor.convert(pm, getTotalWork()); CreateHeaderChangeOperation op = new CreateHeaderChangeOperation(fInfo.getBase(), Constants.BUNDLE_SYMBOLICNAME, fInfo.getCurrentValue(), fInfo.getNewValue()); op.run(subMonitor.newChild(1)); change.add(op.getChange()); if (fInfo.isRenameProject()) { change.add(createProjectChange(subMonitor.newChild( 1))); } if (fInfo.isUpdateReferences()) change.addAll(createReferenceChanges(subMonitor.newChild(2))); return change; }
Source:
<code>private int getMaxHaddexAgeInMonths(int clientID, int orgID) { <START> return sysConfigBL.getIntValue(SYS_CONFIG_MAX_HADDEX_AGE_IN_MONTHS, 24, clientID, orgID); <END> }</code><technical_language>suggestion final int months = sysConfigBL.getIntValue(SYS_CONFIG_MAX_HADDEX_AGE_IN_MONTHS, 24, clientID, orgID); if (months > 0) { return months; } return Integer.MAX_VALUE;</technical_language>

Target:
private int getMaxHaddexAgeInMonths(int clientID, int orgID) { final int months = sysConfigBL.getIntValue(SYS_CONFIG_MAX_HADDEX_AGE_IN_MONTHS, 24, clientID, orgID); if (months > 0) { return months; } return Integer.MAX_VALUE; }
Source:
<code>public QueryRunner<SegmentAnalysis> mergeRunners( ExecutorService exec, Iterable<QueryRunner<SegmentAnalysis>> queryRunners ) { final ListeningExecutorService queryExecutor = MoreExecutors.listeningDecorator(exec); return new ConcatQueryRunner<SegmentAnalysis>( Sequences.map( Sequences.simple(queryRunners), new Function<QueryRunner<SegmentAnalysis>, QueryRunner<SegmentAnalysis>>() { @Override public QueryRunner<SegmentAnalysis> apply(final QueryRunner<SegmentAnalysis> input) { return new QueryRunner<SegmentAnalysis>() { @Override public Sequence<SegmentAnalysis> run( final Query<SegmentAnalysis> query, final Map<String, Object> responseContext ) { final int priority = query.getContextPriority(0); ListenableFuture<Sequence<SegmentAnalysis>> future = queryExecutor.submit( new AbstractPrioritizedCallable<Sequence<SegmentAnalysis>>(priority) { @Override public Sequence<SegmentAnalysis> call() throws Exception <START> { <END> return Sequences.simple( Sequences.toList(input.run(query, responseContext), new ArrayList<SegmentAnalysis>()) ); } } ); try { queryWatcher.registerQuery(query, future); final Number timeout = query.getContextValue("timeout", (Number) null); return timeout == null ? future.get() : future.get(timeout.longValue(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { log.warn(e, "Query interrupted, cancelling pending results, query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException("Query interrupted"); } catch(CancellationException e) { throw new QueryInterruptedException("Query cancelled"); } catch(TimeoutException e) { log.info("Query timeout, cancelling pending results for query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException("Query timeout"); } catch (ExecutionException e) { throw Throwables.propagate(e.getCause()); } } }; } } ) ); }</code><technical_language>for other query types, ChainedExecutionQueryRunner takes care this materializing result,</technical_language>

Target:
public QueryRunner<SegmentAnalysis> mergeRunners( ExecutorService exec, Iterable<QueryRunner<SegmentAnalysis>> queryRunners ) { return new ChainedExecutionQueryRunner<>( exec, toolChest.getOrdering(), queryWatcher, queryRunners ); }
Source:
<code>public void testGenerateSingleTypeEnumConstantMatcher() throws IOException, TemplateModelException { final TestFileUtilsImpl fileUtils = new TestFileUtilsImpl(); <START> Map<String,Object> testMap = new HashMap<>(); <END> final Enum enumEntry = new Enum("ds3_job_status", ImmutableList.of("IN_PROGRESS", "COMPLETED", "CANCELED")); testMap.put("enumEntry", enumEntry); final CCodeGenerator codeGenerator = new CCodeGenerator(); codeGenerator.processTemplate(testMap, "source-templates/TypedefEnumMatcher.ftl", fileUtils.getOutputStream()); final ByteArrayOutputStream bstream = (ByteArrayOutputStream) fileUtils.getOutputStream(); final String output = new String(bstream.toByteArray()); final String expectedOutput = "static ds3_job_status _match_ds3_job_status(const ds3_log* log, const xmlChar* text) {" + "\n" + " if (xmlStrcmp(text, (const xmlChar*) \"IN_PROGRESS\") == 0) {" + "\n" + " return IN_PROGRESS;" + "\n" + " } else if (xmlStrcmp(text, (const xmlChar*) \"COMPLETED\") == 0) {" + "\n" + " return COMPLETED;" + "\n" + " } else if (xmlStrcmp(text, (const xmlChar*) \"CANCELED\") == 0) {" + "\n" + " return CANCELED;" + "\n" + " } else {" + "\n" + " ds3_log_message(log, DS3_ERROR, \"ERROR: Unknown value of '%s'. Returning IN_PROGRESS for safety.\", text);" + "\n" + " return IN_PROGRESS;" + "\n" + " }" + "\n" + "}" + "\n"; assertEquals(expectedOutput, output); }</code><technical_language>Missing final</technical_language>

Target:
public void testGenerateSingleTypeEnumConstantMatcher() throws IOException, TemplateModelException { final TestFileUtilsImpl fileUtils = new TestFileUtilsImpl(); final Map<String,Object> testMap = new HashMap<>(); final Enum enumEntry = new Enum("ds3_job_status", ImmutableList.of("IN_PROGRESS", "COMPLETED", "CANCELED")); testMap.put("enumEntry", enumEntry); final CCodeGenerator codeGenerator = new CCodeGenerator(); codeGenerator.processTemplate(testMap, "source-templates/TypedefEnumMatcher.ftl", fileUtils.getOutputStream()); final ByteArrayOutputStream bstream = (ByteArrayOutputStream) fileUtils.getOutputStream(); final String output = new String(bstream.toByteArray()); final String expectedOutput = "static ds3_job_status _match_ds3_job_status(const ds3_log* log, const xmlChar* text) {" + "\n" + " if (xmlStrcmp(text, (const xmlChar*) \"IN_PROGRESS\") == 0) {" + "\n" + " return IN_PROGRESS;" + "\n" + " } else if (xmlStrcmp(text, (const xmlChar*) \"COMPLETED\") == 0) {" + "\n" + " return COMPLETED;" + "\n" + " } else if (xmlStrcmp(text, (const xmlChar*) \"CANCELED\") == 0) {" + "\n" + " return CANCELED;" + "\n" + " } else {" + "\n" + " ds3_log_message(log, DS3_ERROR, \"ERROR: Unknown value of '%s'. Returning IN_PROGRESS for safety.\", text);" + "\n" + " return IN_PROGRESS;" + "\n" + " }" + "\n" + "}" + "\n"; assertEquals(expectedOutput, output); }
Source:
<code>public VersionNumber getCurrentLevel() throws IOException { VersionNumber from = new VersionNumber("1.0"); File state = getUpdateStateFile(); if (state.exists()) { <START> from = new VersionNumber(defaultIfBlank(readFileToString(state), "1.0").trim()); <END> } return from; }</code><technical_language>behavior for blank files. IOException is preferable</technical_language>

Target:
public VersionNumber getCurrentLevel() { VersionNumber from = new VersionNumber("1.0"); File state = getUpdateStateFile(); if (state.exists()) { try { from = new VersionNumber(defaultIfBlank(readFileToString(state), "1.0").trim()); } catch (IOException ex) { LOGGER.log(Level.SEVERE, "Cannot read the current version file", ex); return null; } } return from; }
Source:
<code>@RequirePOST public HttpResponse doCheckUpdatesServer() throws IOException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); int sleep = SystemProperties.getInteger(PluginManager.class.getName() + ".sleepTimeMilis", 1000); int retries = SystemProperties.getInteger(PluginManager.class.getName() + ".retries", 3); retries = retries > 0 ? retries : 3; sleep = sleep > 0 ? sleep : 1000; FormValidation response = null; int i = 0; boolean success = false; <START> while(i < retries && !success) { <END> i++; try { response = checkUpdatesServer(); lastErrorCheckUpdateCenters = response.getMessage(); success = (response.kind == FormValidation.Kind.OK); } catch (Exception e) { lastErrorCheckUpdateCenters = e.getLocalizedMessage(); } if (!success) { LOGGER.warning(String.format("The attempt #%s to check updates server failed. Exception: %s", i, lastErrorCheckUpdateCenters)); if (i < retries) { LOGGER.info(String.format("Will retry after %s milliseconds", sleep)); try { Thread.sleep(sleep); } catch (InterruptedException ie) { LOGGER.info("The wait for a new attempt to check updates server was interrupted. Exception: " + ie); } } else { LOGGER.info(String.format("Attempted to check updates server for %s times with no success, raising an error", retries)); LOGGER.severe(String.format("Error checking updates server for %s times. Last exception was: %s", retries, lastErrorCheckUpdateCenters)); if(!LOGGER.isLoggable(Level.WARNING)) { LOGGER.severe("Change the log level to WARNING or below to see the error message of every attempt"); } lastErrorCheckUpdateCenters = Messages.PluginManager_CheckUpdateServerError(lastErrorCheckUpdateCenters); } } } return HttpResponses.forwardToPreviousPage(); }</code><technical_language>combine variables a for loop</technical_language>

Target:
@RequirePOST public HttpResponse doCheckUpdatesServer() throws IOException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); Retrier<FormValidation> updateServerRetrier = new Retrier.Builder<>( this::checkUpdatesServer, (currentAttempt, result) -> result.kind == FormValidation.Kind.OK, "check updates server") .withAttempts(CHECK_UPDATE_ATTEMPTS) .withDelay(CHECK_UPDATE_SLEEP_TIME_MILLIS) .withDuringActionExceptions(new Class[] {Exception.class}) .withDuringActionExceptionListener( (attempt, e) -> FormValidation.errorWithMarkup(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage())) .build(); try { FormValidation result = updateServerRetrier.start(); if (!FormValidation.Kind.OK.equals(result.kind)) { LOGGER.log(Level.SEVERE, Messages.PluginManager_UpdateSiteError(CHECK_UPDATE_ATTEMPTS, result.getMessage())); if (CHECK_UPDATE_ATTEMPTS > 1 && !Logger.getLogger(Retrier.class.getName()).isLoggable(Level.WARNING)) { LOGGER.log(Level.SEVERE, Messages.PluginManager_UpdateSiteChangeLogLevel(Retrier.class.getName())); } lastErrorCheckUpdateCenters = Messages.PluginManager_CheckUpdateServerError(result.getMessage()); } else { lastErrorCheckUpdateCenters = null; } } catch (Exception e) { LOGGER.log(Level.WARNING, Messages.PluginManager_UnexpectedException(), e); throw new IOException(e); } return HttpResponses.forwardToPreviousPage(); }
Source:
<code>public void getPopUpData(File file){ try { ExifInterface exif_data = new ExifInterface(file.getAbsolutePath()); Date lastModDate = new Date(file.lastModified()); long length = file.length()/1024; String img_width = exif_data.getAttribute(ExifInterface.TAG_IMAGE_WIDTH); String img_height = exif_data.getAttribute(ExifInterface.TAG_IMAGE_LENGTH); <START> if(img_width.isEmpty() || img_height.isEmpty() || img_width.equals("0") || img_height.equals("0") ) { <END> try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; ParcelFileDescriptor fd = getContentResolver().openFileDescriptor(Uri.fromFile(file), "r"); if (fd != null) { BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, options); img_width = options.outWidth + ""; img_height = options.outHeight + ""; fd.close(); options = null; } } catch (Exception e) { } } ((TextView)pwindo.getContentView().findViewById(R.id.path)).setText(file.getAbsolutePath()); ((TextView)pwindo.getContentView().findViewById(R.id.time)).setText(lastModDate.toString()); ((TextView)pwindo.getContentView().findViewById(R.id.image_width)).setText(img_width); ((TextView)pwindo.getContentView().findViewById(R.id.height)).setText(img_height); ((TextView)pwindo.getContentView().findViewById(R.id.size)).setText(Long.toString(length)+ "KB"); } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>Position literals in comparisons, if argument is null NullPointerExceptions avoided, return false</technical_language>

Target:
public void getPopUpData(File file){ try { ExifInterface exif_data = new ExifInterface(file.getAbsolutePath()); Date lastModDate = new Date(file.lastModified()); long length = file.length()/1024; String img_width = exif_data.getAttribute(ExifInterface.TAG_IMAGE_WIDTH); String img_height = exif_data.getAttribute(ExifInterface.TAG_IMAGE_LENGTH); if("0".equals(img_width) || "0".equals(img_height)) { try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; ParcelFileDescriptor fd = getContentResolver().openFileDescriptor(Uri.fromFile(file), "r"); if (fd != null) { BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, options); img_width = options.outWidth + ""; img_height = options.outHeight + ""; fd.close(); options = null; } } catch (Exception e) { } } ((TextView)pwindo.getContentView().findViewById(R.id.path)).setText(file.getAbsolutePath()); ((TextView)pwindo.getContentView().findViewById(R.id.time)).setText(lastModDate.toString()); ((TextView)pwindo.getContentView().findViewById(R.id.image_width)).setText(img_width); ((TextView)pwindo.getContentView().findViewById(R.id.height)).setText(img_height); ((TextView)pwindo.getContentView().findViewById(R.id.size)).setText(Long.toString(length)+ "KB"); } catch (IOException e) { e.printStackTrace(); } }
Source:
<code>public void counterexampleFoundWithAllParametersIsCorrect() { String propertyName = "mySuperProperty"; String[] arguments = {"first", "second", "third"}; long[] seeds = {12345, 8842}; String assertionName = "assertion name"; AssertionError error = new AssertionError(assertionName); AssertionError actual = PropertyFalsified.counterexampleFound( propertyName, arguments, seeds, error); String expected = format("Property named 'mySuperProperty' failed (assertion name)%n" + "With arguments: [first, second, third]%n" + "Seeds for reproduction: [12345, 8842]"); <START> assertThat(actual.getMessage(), is(expected)); <END> }</code><technical_language>Personal preference: matcher equalTo instead of is</technical_language>

Target:
public void counterexampleFoundWithAllParametersIsCorrect() { String propertyName = "mySuperProperty"; String[] arguments = {"first", "second", "third"}; long[] seeds = {12345, 8842}; String assertionName = "assertion name"; AssertionError error = new AssertionError(assertionName); AssertionError actual = PropertyFalsified.counterexampleFound( propertyName, arguments, seeds, error); String expected = format("Property named 'mySuperProperty' failed (assertion name)%n" + "With arguments: [first, second, third]%n" + "Seeds for reproduction: [12345, 8842]"); assertThat(actual.getMessage(), equalTo(expected)); }
Source:
<code>public void testMultipleInvocations() throws NoHeadException, ConcurrentRefUpdateException, NoMessageException, UnmergedPathException, JGitInternalException { Git git = new Git(db); CommitCommand commitCmd = git.commit(); commitCmd.setMessage("initial commit").call(); try { commitCmd.setAuthor(author); <START> fail("didn't caught the expected exception"); <END> } catch (IllegalStateException e) { } LogCommand logCmd = git.log(); logCmd.call(); try { logCmd.call(); fail("didn't caught the expected exception"); } catch (IllegalStateException e) { } }</code><technical_language>spelling: change caught catch</technical_language>

Target:
public void testMultipleInvocations() throws NoHeadException, ConcurrentRefUpdateException, NoMessageException, UnmergedPathException, JGitInternalException { Git git = new Git(db); CommitCommand commitCmd = git.commit(); commitCmd.setMessage("initial commit").call(); try { commitCmd.setAuthor(author); fail("didn't catch the expected exception"); } catch (IllegalStateException e) { } LogCommand logCmd = git.log(); logCmd.call(); try { logCmd.call(); fail("didn't catch the expected exception"); } catch (IllegalStateException e) { } }
Source:
<code>private static void validate(AggregatedPayload payload) { if (payload == null) { throw new InvalidDataException("Invalid request body"); } Set<ConstraintViolation<AggregatedPayload>> constraintViolations = validator.validate(payload); for (ConstraintViolation<AggregatedPayload> constraintViolation : constraintViolations) { String source = constraintViolation.getPropertyPath().toString().equalsIgnoreCase("valid") ? "" : constraintViolation.getPropertyPath().toString(); String metricName = ""; Object leafBean = constraintViolation.getLeafBean(); if (leafBean instanceof BluefloodGauge) { metricName = ((BluefloodGauge) leafBean).getName(); } else if (leafBean instanceof BluefloodCounter) { metricName = ((BluefloodCounter) leafBean).getName(); } else if (leafBean instanceof BluefloodTimer) { metricName = ((BluefloodTimer) leafBean).getName(); } else if (leafBean instanceof BluefloodSet) { metricName = ((BluefloodSet) leafBean).getName(); } if ((metricName.isEmpty()) && (payload.getAllMetricNames().size() > 0)) { metricName = payload.getAllMetricNames().get(0); <START> } <END> payload.validationErrors.add(new ErrorResponse.ErrorData(payload.getTenantId(), metricName, source, constraintViolation.getMessage())); } }</code><technical_language>metricName in list relate current violation? If a metricName, processed, empty</technical_language>

Target:
private static void validate(AggregatedPayload payload) { if (payload == null) { throw new InvalidDataException("Invalid request body"); } Set<ConstraintViolation<AggregatedPayload>> constraintViolations = validator.validate(payload); for (ConstraintViolation<AggregatedPayload> constraintViolation : constraintViolations) { String source = constraintViolation.getPropertyPath().toString().equalsIgnoreCase("valid") ? "" : constraintViolation.getPropertyPath().toString(); String metricName = ""; Object leafBean = constraintViolation.getLeafBean(); if (leafBean instanceof BluefloodGauge) { metricName = ((BluefloodGauge) leafBean).getName(); } else if (leafBean instanceof BluefloodCounter) { metricName = ((BluefloodCounter) leafBean).getName(); } else if (leafBean instanceof BluefloodTimer) { metricName = ((BluefloodTimer) leafBean).getName(); } else if (leafBean instanceof BluefloodSet) { metricName = ((BluefloodSet) leafBean).getName(); } payload.validationErrors.add(new ErrorResponse.ErrorData(payload.getTenantId(), metricName, source, constraintViolation.getMessage(), payload.getTimestamp())); } }
Source:
<code>private List<ArchiveEvent> cleanupJobsBeyondSizeLimit(Set<Path> jobArchivesToRemove) { Set<String> jobIdsToRemoveFromOverview = new HashSet<>(); for (Path archive : jobArchivesToRemove) { jobIdsToRemoveFromOverview.add(archive.getName()); try { archive.getFileSystem().delete(archive, false); } catch (IOException ioe) { <START> LOG.error("Error while deleting old archive " + archive, ioe); <END> } } return cleanupExpiredJobs(jobIdsToRemoveFromOverview); }</code><technical_language>I reduce log level warn history server work if this happen</technical_language>

Target:
private List<ArchiveEvent> cleanupJobsBeyondSizeLimit(Set<Path> jobArchivesToRemove) { Set<String> jobIdsToRemoveFromOverview = new HashSet<>(); for (Path archive : jobArchivesToRemove) { jobIdsToRemoveFromOverview.add(archive.getName()); try { archive.getFileSystem().delete(archive, false); } catch (IOException ioe) { LOG.warn("Could not delete old archive " + archive, ioe); } } return cleanupExpiredJobs(jobIdsToRemoveFromOverview); }
Source:
<code>public void should_save_issues_from_external_report() { <START> if (sqSupportsExternalIssues()) { <END> orchestrator.resetData(); SonarScanner build = Tests.createScanner() .setProjectDir(TestUtils.projectDir("tslint-report-project")) .setProjectKey(PROJECT_KEY) .setProjectName(PROJECT_KEY) .setProjectVersion("1.0") .setSourceDirs("src"); build.setProperty("sonar.typescript.tslint.reportPaths", "report.json"); orchestrator.executeBuild(build); SearchRequest request = new SearchRequest(); request.setComponentKeys(Collections.singletonList(PROJECT_KEY)); List<Issue> issuesList = newWsClient().issues().search(request).getIssuesList(); assertThat(issuesList).extracting("line").containsExactlyInAnyOrder(3, 5, 5, 7); assertThat(issuesList).extracting("rule").containsExactlyInAnyOrder( "external_tslint_repo:no-unused-expression", "external_tslint_repo:prefer-const", "external_tslint_repo:semicolon", "external_tslint_repo:curly"); } }</code><technical_language>drop this line (from for ESLint probably)</technical_language>

Target:
public void should_save_issues_from_external_report() { orchestrator.resetData(); SonarScanner build = Tests.createScanner() .setProjectDir(TestUtils.projectDir("tslint-report-project")) .setProjectKey(PROJECT_KEY) .setProjectName(PROJECT_KEY) .setProjectVersion("1.0") .setSourceDirs("src"); build.setProperty("sonar.typescript.tslint.reportPaths", "report.json"); orchestrator.executeBuild(build); SearchRequest request = new SearchRequest(); request.setComponentKeys(Collections.singletonList(PROJECT_KEY)); List<Issue> issuesList = newWsClient().issues().search(request).getIssuesList(); assertThat(issuesList).extracting("line").containsExactlyInAnyOrder(3, 5, 5, 7); assertThat(issuesList).extracting("rule").containsExactlyInAnyOrder( "external_tslint_repo:no-unused-expression", "external_tslint_repo:prefer-const", "external_tslint_repo:semicolon", "external_tslint_repo:curly"); }
Source:
<code>private void drawTiles( Canvas canvas ) { if( mPreviouslyDrawnTiles.size() > 0 ) { drawTilesConsideringPreviouslyDrawnLevel( canvas ); } else { drawTilesWithoutConsideringPreviouslyDrawnLevel( canvas ); } <START> Log.d( getClass().getSimpleName(), "prevous tile count: " + mPreviouslyDrawnTiles.size() ); <END> }</code><technical_language>TODO : remove log release</technical_language>

Target:
private void drawTiles( Canvas canvas ) { if( mPreviouslyDrawnTiles.size() > 0 ) { drawTilesConsideringPreviouslyDrawnLevel( canvas ); } else { drawTilesWithoutConsideringPreviouslyDrawnLevel( canvas ); } }
Source:
<code>public MessageSource<Object> jdbcMessageSource() { JdbcPollingChannelAdapter jdbcPollingChannelAdapter = new JdbcPollingChannelAdapter(dataSource, properties.getQuery()); jdbcPollingChannelAdapter.setMaxRowsPerPoll(properties.getMaxRowsPerPoll()); if (properties.getUpdate() != null) { jdbcPollingChannelAdapter.setUpdateSql(properties.getUpdate()); <START> } <END> return jdbcPollingChannelAdapter; }</code><technical_language>reason worry value. is optional JdbcPollingChannelAdapter takes care null. I if is redundant. Of course, is minor live this :smile:</technical_language>

Target:
public MessageSource<Object> jdbcMessageSource() { JdbcPollingChannelAdapter jdbcPollingChannelAdapter = new JdbcPollingChannelAdapter(dataSource, properties.getQuery()); jdbcPollingChannelAdapter.setMaxRowsPerPoll(properties.getMaxRowsPerPoll()); jdbcPollingChannelAdapter.setUpdateSql(properties.getUpdate()); return jdbcPollingChannelAdapter; }
Source:
<code>private InteractionRewriter visitInteractionAwareExpressionStatement(ExpressionStatement stat) { InteractionRewriter rewriter = new InteractionRewriter(resources, getCurrentWithOrMockClosure()); <START> if(isInterationExpression(rewriter, stat)) { <END> insideInteraction = true; super.doVisitExpressionStatement(stat); insideInteraction = false; } else { super.doVisitExpressionStatement(stat); } return rewriter; }</code><technical_language>nit: missing space (also for other if statements in doVisitBinaryExpression)</technical_language>

Target:
private InteractionRewriter visitInteractionAwareExpressionStatement(ExpressionStatement stat) { InteractionRewriter rewriter = new InteractionRewriter(resources, getCurrentWithOrMockClosure()); if (isInteractionExpression(rewriter, stat)) { insideInteraction = true; super.doVisitExpressionStatement(stat); insideInteraction = false; } else { super.doVisitExpressionStatement(stat); } return rewriter; }
Source:
<code><START> public Builder<String> taskCreator(final String batchId, final TaskOnBatch task) throws EvrythngClientException { <END> return postAccepted(String.format(PATH_BATCH_TASKS, batchId), task); }</code><technical_language>return Builder of AcceptedResourceLocation</technical_language>

Target:
public Builder<AcceptedResourceResponse> taskCreator(final String batchId, final TaskOnBatch task) throws EvrythngClientException { return postAsynchronously(String.format(PATH_BATCH_TASKS, batchId), task, Pattern.compile(".*/([^/]*)$")); }
Source:
<code>public void handleRequests(Request request) throws InterruptedException { try { DataInputStream stream = new DataInputStream(request.getInputStream()); RequestOrResponseType type = RequestOrResponseType.values()[stream.readShort()]; switch (type) { case PutRequest: handlePutRequest(request); break; case GetRequest: handleGetRequest(request); break; case DeleteRequest: handleDeleteRequest(request); break; case TtlUpdateRequest: handleTtlUpdateRequest(request); break; case ReplicaMetadataRequest: handleReplicaMetadataRequest(request); break; case AdminRequest: <START> throw new UnsupportedOperationException("Request type not supported"); <END> default: throw new UnsupportedOperationException("Request type not supported"); } } catch (Exception e) { logger.error("Error while handling request " + request + " closing connection", e); requestResponseChannel.closeConnection(request); } }</code><technical_language>do need a separate case for AdminRequest here. goto default</technical_language>

Target:
public void handleRequests(Request request) throws InterruptedException { try { DataInputStream stream = new DataInputStream(request.getInputStream()); RequestOrResponseType type = RequestOrResponseType.values()[stream.readShort()]; switch (type) { case PutRequest: handlePutRequest(request); break; case GetRequest: handleGetRequest(request); break; case DeleteRequest: handleDeleteRequest(request); break; case TtlUpdateRequest: handleTtlUpdateRequest(request); break; case ReplicaMetadataRequest: handleReplicaMetadataRequest(request); break; case AdminRequest: handleAdminRequest(request); break; default: throw new UnsupportedOperationException("Request type not supported"); } } catch (Exception e) { logger.error("Error while handling request " + request + " closing connection", e); requestResponseChannel.closeConnection(request); } }
Source:
<code>private CachedJob<T> initializeOrEnsureRefMatch(final JobRef<T> ref) throws IllegalStateException { if (!_cachedJob.isPresent()) { LOGGER.info() .setMessage("initializing") .addData("ref", ref) .log(); _cachedJob = Optional.of(new CachedJob<>(_injector, ref)); } final JobRef<T> oldRef = _cachedJob.get().getRef(); if (!oldRef.equals(ref)) { LOGGER.error() .setMessage("JobRef in received message does not match cached JobRef") .addData("cached", oldRef) .addData("new", ref) .log(); stopForever(); <START> throw new IllegalStateException("got JobRef id=" + ref.getJobId() + " but already initialized with id=" + oldRef.getJobId()); <END> } return _cachedJob.get(); }</code><technical_language>nit: Prefer String.format("...") for readability</technical_language>

Target:
private CachedJob<T> initializeOrEnsureRefMatch(final JobRef<T> ref) throws IllegalStateException, NoSuchJobException { if (!_cachedJob.isPresent()) { LOGGER.info() .setMessage("initializing") .addData("ref", ref) .log(); _cachedJob = Optional.of(CachedJob.createAndLoad(_injector, ref, _periodicMetrics)); } final JobRef<T> oldRef = _cachedJob.get().getRef(); if (!oldRef.equals(ref)) { throw new IllegalStateException(String.format("got JobRef %s, but already initialized with %s", ref, oldRef)); } return _cachedJob.get(); }
Source:
<code>public void partActivated(IWorkbenchPart part) { if (part == AbstractTimeGraphView.this) { synchronized (FIND_ACTION) { if (fFindActionHandler == null) { fFindActionHandler = new ActionHandler(FIND_ACTION); } <START> @SuppressWarnings("null") <END> final Object service = PlatformUI.getWorkbench().getService(IHandlerService.class); fFindHandlerActivation = ((IHandlerService) service).activateHandler(ActionFactory.FIND.getCommandId(), fFindActionHandler); } } FIND_ACTION.partActivated(part); }</code><technical_language>hudson fails "Unnecessary @SuppressWarnings("null")". In workspace I a warning I remove it</technical_language>

Target:
public void partActivated(IWorkbenchPart part) { if (part == AbstractTimeGraphView.this) { synchronized (FIND_ACTION) { if (fFindActionHandler == null) { fFindActionHandler = new ActionHandler(FIND_ACTION); } final Object service = PlatformUI.getWorkbench().getService(IHandlerService.class); fFindHandlerActivation = ((IHandlerService) service).activateHandler(ActionFactory.FIND.getCommandId(), fFindActionHandler); } } FIND_ACTION.partActivated(part); }
Source:
<code>public boolean await(long deadline) throws InterruptedException { <START> final WorkManager mgr = Framework.getService(WorkManager.class); <END> if (mgr.awaitCompletion(deadline - System.currentTimeMillis(), TimeUnit.MILLISECONDS)) { return true; } logInfos(mgr); return false; }</code><technical_language>Remove unneeded final. Call variable workManager for clarity</technical_language>

Target:
public boolean await(long deadline) throws InterruptedException { WorkManager workManager = Framework.getService(WorkManager.class); if (workManager.awaitCompletion(deadline - System.currentTimeMillis(), TimeUnit.MILLISECONDS)) { return true; } logInfos(workManager); return false; }