auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public synchronized boolean record(final String chrom, final int pos) { this.lastChrom = chrom; this.lastPos = pos; <START> if (this.lastStartTime == -1) this.lastStartTime = System.currentTimeMillis(); <END> if (++this.processed % this.n == 0) { log(chrom, pos); return true; } else { return false; } }</code><technical_language>Odd indent line 86 lack of braces this code confusing. a newline { } if body intent clear. Fixing indent help</technical_language>

Target:
public synchronized boolean record(final String chrom, final int pos) { this.lastChrom = chrom; this.lastPos = pos; if (this.lastStartTime == -1) { this.lastStartTime = System.currentTimeMillis(); } if (++this.processed % this.n == 0) { record(); return true; } else { return false; } }
Source:
<code>public CassandraDataSegmentPusher( CassandraDataSegmentConfig config, ObjectMapper jsonMapper) { this.config = config; this.jsonMapper = jsonMapper; this.astyanaxContext = new AstyanaxContext.Builder() .forCluster(CLUSTER_NAME) .forKeyspace(config.getKeyspace()) .withAstyanaxConfiguration(new AstyanaxConfigurationImpl().setDiscoveryType(NodeDiscoveryType.NONE)) .withConnectionPoolConfiguration( new ConnectionPoolConfigurationImpl("MyConnectionPool").setMaxConnsPerHost(10) .setSeeds(config.getHost())).withConnectionPoolMonitor(new CountingConnectionPoolMonitor()) .buildKeyspace(ThriftFamilyFactory.getInstance()); <START> this.astyanaxContext.start(); <END> this.keyspace = this.astyanaxContext.getEntity(); descriptorStorage = new ColumnFamily<String, String>(DESCRIPTOR_TABLE_NAME, StringSerializer.get(), StringSerializer.get()); indexStorage = new CassandraChunkedStorageProvider(keyspace, INDEX_TABLE_NAME); }</code><technical_language>if this start() method throw exception (or if is a subsequent close() method), safer a start() method pusher itself. annotate @LifecycleStart object is created, add Lifecycle (lifecycle.addManagedInstance()). add lifecycle method signatures of initialization code, a lifecycle object some layer of call stack, signature adjustments. working making this a simpler process..</technical_language>

Target:
public CassandraDataSegmentPusher( CassandraDataSegmentConfig config, ObjectMapper jsonMapper) { super(config); this.jsonMapper=jsonMapper; }
Source:
<code>private void initialize() throws Exception { for (DcZkInfo dcZkInfo : dcToDcZkInfo.values()) { HelixAdmin admin = dcZkInfo.helixManager.getClusterManagmentTool(); for (String instanceName : admin.getInstancesInCluster(clusterName)) { InstanceConfig instanceConfig = admin.getInstanceConfig(clusterName, instanceName); AmbryDataNode datanode = new AmbryDataNode(dcZkInfo.dcName, clusterMapConfig, instanceConfig.getHostName(), instanceConfig.getPort(), getRackIdStr(instanceConfig), getSslPortStr(instanceConfig)); initializeDisksAndReplicasOnNode(datanode, instanceConfig); instanceNameToDataNodeIdMap.put(instanceName, datanode); dcZkInfo.clusterChangeListener.allInstances.add(instanceName); } } <START> for (Set<AmbryDisk> disks : dataNodeIdToDiskIds.values()) { <END> for (AmbryDisk disk : disks) { clusterWideRawCapacityBytes += disk.getRawCapacityInBytes(); } } for (Map.Entry<AmbryPartition, Set<AmbryReplica>> partitionInfo : partitionIdToReplicaIds.entrySet()) { long replicaCapacity = partitionInfo.getValue().iterator().next().getCapacityInBytes(); clusterWideAllocatedRawCapacityBytes += replicaCapacity * partitionInfo.getValue().size(); clusterWiseAllocatedUsableCapacityBytes += replicaCapacity; } }</code><technical_language>this done initializeDisksAndReplicasOnNode</technical_language>

Target:
private void initialize() throws Exception { for (DcZkInfo dcZkInfo : dcToDcZkInfo.values()) { HelixAdmin admin = dcZkInfo.helixManager.getClusterManagmentTool(); for (String instanceName : admin.getInstancesInCluster(clusterName)) { InstanceConfig instanceConfig = admin.getInstanceConfig(clusterName, instanceName); AmbryDataNode datanode = new AmbryDataNode(dcZkInfo.dcName, clusterMapConfig, instanceConfig.getHostName(), Integer.valueOf(instanceConfig.getPort()), getRackId(instanceConfig), getSslPortStr(instanceConfig)); initializeDisksAndReplicasOnNode(datanode, instanceConfig); instanceNameToAmbryDataNode.put(instanceName, datanode); dcZkInfo.clusterChangeListener.allInstances.add(instanceName); } } for (Set<AmbryDisk> disks : ambryDataNodeToAmbryDisks.values()) { for (AmbryDisk disk : disks) { clusterWideRawCapacityBytes += disk.getRawCapacityInBytes(); } } for (Set<AmbryReplica> partitionReplicas : ambryPartitionToAmbryReplicas.values()) { long replicaCapacity = partitionReplicas.iterator().next().getCapacityInBytes(); clusterWideAllocatedRawCapacityBytes += replicaCapacity * partitionReplicas.size(); clusterWiseAllocatedUsableCapacityBytes += replicaCapacity; } }
Source:
<code>static void validateEmail( final String email ) throws ResourceException { <START> if ( !EMAIL_PATTERN.matcher( email ).matches() ) <END> { throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "Invalid e-mail address: " + email ); } }</code><technical_language>null email fail here. lets prevent potential NPE, theory is UI pass it</technical_language>

Target:
static void validateEmail( final String email ) throws ResourceException { if ( StringUtils.isEmpty( email ) ) { throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "E-mail address cannot be empty" ); } if ( !EMAIL_PATTERN.matcher( email ).matches() ) { throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "Invalid e-mail address: " + email ); } }
Source:
<code>public final Observable<T> takeLast(final int count) { <START> return lift(new OperatorTakeLast(count)); <END> }</code><technical_language>add type parameters constructor calls below</technical_language>

Target:
public final Observable<T> takeLast(final int count) { return lift(new OperatorTakeLast<T>(count)); }
Source:
<code><START> private synchronized void renderQueues() { <END> Platform.runLater(() -> { List<MatchmakingQueue> queues = Collections.synchronizedList(teamMatchmakingService.getMatchmakingQueues()); synchronized (queues) { queueBox.getChildren().clear(); queues.sort(Comparator.comparing(MatchmakingQueue::getQueueId)); queues.forEach(queue -> { MatchmakingQueueItemController controller = uiService.loadFxml("theme/play/teammatchmaking/matchmaking_queue_card.fxml"); controller.setQueue(queue); queueBox.getChildren().add(controller.getRoot()); }); } }); }</code><technical_language>synchronized? I executes in site PlatformRun.later ... is synchronized is UI Thread !!</technical_language>

Target:
private void renderQueues() { Platform.runLater(() -> { List<MatchmakingQueue> queues = Collections.synchronizedList(teamMatchmakingService.getMatchmakingQueues()); synchronized (queues) { queueBox.getChildren().clear(); queues.sort(Comparator.comparing(MatchmakingQueue::getQueueId)); queues.forEach(queue -> { MatchmakingQueueItemController controller = uiService.loadFxml("theme/play/teammatchmaking/matchmaking_queue_card.fxml"); controller.setQueue(queue); queueBox.getChildren().add(controller.getRoot()); }); } }); }
Source:
<code>@Override public void onMatch(RelOptRuleCall call) { IgniteProject rel = call.rel(0); RelNode input = call.rel(1); RelOptCluster cluster = rel.getCluster(); RelMetadataQuery mq = cluster.getMetadataQuery(); RelTraitSet traits = rel.getTraitSet() .replace(IgniteDistributions.project(mq, input, rel.getProjects())); <START> if (call.getPlanner().getRelTraitDefs().contains(RelCollationTraitDef.INSTANCE)) { <END> List<RelCollation> projCollations = RelMdCollation.project(mq, input, rel.getProjects()); if (!F.isEmpty(projCollations)) traits = traits.replace(projCollations.get(0)); } RuleUtils.transformTo(call, new IgniteProject(cluster, traits, input, rel.getProjects(), rel.getRowType())); }</code><technical_language>Collation is a required trait, a condition is useless here</technical_language>

Target:
@Override public void onMatch(RelOptRuleCall call) { IgniteProject rel = call.rel(0); RelNode input = call.rel(1); RelOptCluster cluster = rel.getCluster(); RelMetadataQuery mq = cluster.getMetadataQuery(); RelTraitSet traits = rel.getTraitSet() .replace(IgniteDistributions.project(mq, input, rel.getProjects())); List<RelCollation> projCollations = RelMdCollation.project(mq, input, rel.getProjects()); if (!F.isEmpty(projCollations)) traits = traits.replace(projCollations.get(0)); RuleUtils.transformTo(call, new IgniteProject(cluster, traits, input, rel.getProjects(), rel.getRowType())); }
Source:
<code>public boolean trySetBytes(long bytes) { boolean result = delegate.trySetBytes(bytes); if (peakMemory.isPresent()) { <START> peakMemory.get().accumulateAndGet(delegate.getBytes(), Math::max); <END> } return result; }</code><technical_language>spare this call !result</technical_language>

Target:
public boolean trySetBytes(long bytes) { return delegate.trySetBytes(bytes); }
Source:
<code>public long deleteHorizonMs() { <START> return -1L; <END> }</code><technical_language>RecordBatch.NO_TIMESTAMP too</technical_language>

Target:
public long deleteHorizonMs() { return RecordBatch.NO_TIMESTAMP; }
Source:
<code>public FSDataOutputStream openHdfsOutputFile(Path path, boolean useLocal, boolean allowOveride) throws IOException { short repCount = (short) HadoopLogsConfigs.getReplicationCount(); <START> long blockSize = (long) HadoopLogsConfigs.getHdfsBlockSize() * 1048576L; <END> if (useLocal) { return localFileSystem.create(path, allowOveride, bufferSize, repCount, blockSize); } else { return remoteFileSystem.create(path, allowOveride, bufferSize, repCount, blockSize); } }</code><technical_language>constant a static variable. is converting megabytes bytes? If so, 'MB_TO_BYTES_CONVERSION'</technical_language>

Target:
public FSDataOutputStream openHdfsOutputFile(Path path, boolean useLocal, boolean allowOveride) throws IOException { short repCount = (short) HadoopLogsConfigs.getReplicationCount(); long blockSize = (long) HadoopLogsConfigs.getHdfsBlockSize() * 1024L*1024L; if (useLocal) { return localFileSystem.create(path, allowOveride, bufferSize, repCount, blockSize); } else { return remoteFileSystem.create(path, allowOveride, bufferSize, repCount, blockSize); } }
Source:
<code>public HiveMetastoreClientFactory( Optional<SSLContext> sslContext, Optional<HostAndPort> socksProxy, Duration timeout, HiveMetastoreAuthentication metastoreAuthentication) { <START> this.sslContext = sslContext; <END> this.socksProxy = requireNonNull(socksProxy, "socksProxy is null"); this.timeoutMillis = toIntExact(timeout.toMillis()); this.metastoreAuthentication = requireNonNull(metastoreAuthentication, "metastoreAuthentication is null"); }</code><technical_language>requireNN</technical_language>

Target:
public HiveMetastoreClientFactory( Optional<SSLContext> sslContext, Optional<HostAndPort> socksProxy, Duration timeout, HiveMetastoreAuthentication metastoreAuthentication) { this.sslContext = requireNonNull(sslContext, "sslContext is null"); this.socksProxy = requireNonNull(socksProxy, "socksProxy is null"); this.timeoutMillis = toIntExact(timeout.toMillis()); this.metastoreAuthentication = requireNonNull(metastoreAuthentication, "metastoreAuthentication is null"); }
Source:
<code><START> public ITmfTrace openMinimalTrace(String projectName, String traceName, Boolean isExperiment) { <END> return null; }</code><technical_language>Add a TODO implemented in a patch. I this is next task, other reviewers ;-)</technical_language>

Target:
public ITmfTrace openMinimalTrace(String projectName, String traceName, Boolean isExperiment) throws FileNotFoundException { Map<String, Object> parameters = new HashMap<>(); parameters.put("name", traceName); String filePath = getFile(projectName, traceName, isExperiment).getLocation().getPath(); parameters.put("uri", filePath); QueryParameters query = new QueryParameters(parameters, Collections.emptyList()); TraceManagerService traceManager = new TraceManagerService(); Response response = traceManager.putTrace(query); Object traceObject = response.getEntity(); if (traceObject instanceof ITmfTrace) { return (ITmfTrace) traceObject; } throw new FileNotFoundException(); }
Source:
<code>void addModuleCompletions(ModuleService moduleService) { if (this.moduleService == moduleService) { return; } sorted = false; this.moduleService = moduleService; <START> ArrayList<Completion> list = new ArrayList<Completion>(); <END> for (ModuleInfo info : moduleService.getModules()) { if(info.getMenuPath().getLeaf() != null) { String name = info.getMenuPath().getLeaf().getName().trim(); String headline = "run(\"" + name +"\")"; String description = "<b>" + headline + "</b><p>" + "<a href=\"<LINK_0>" + name.replace(" ", "%20") + "\">Search imagej wiki for help</a>"; list.add(makeListEntry(this, headline, null, description)); } } addCompletions(list); }</code><technical_language>name this more concisely completions, in addMacroExtensionAutoCompletions method? Also, redundant type arguments removed constructor call: suggestion ArrayList<Completion> completions = new ArrayList<>();</technical_language>

Target:
void addModuleCompletions(ModuleService moduleService) { if (this.moduleService == moduleService) { return; } sorted = false; this.moduleService = moduleService; ArrayList<Completion> completions = new ArrayList<>(); for (ModuleInfo info : moduleService.getModules()) { if(info.getMenuPath().getLeaf() != null) { String name = info.getMenuPath().getLeaf().getName().trim(); String headline = "run(\"" + name +"\")"; String description = "<b>" + headline + "</b><p>" + "<a href=\"<LINK_0>" + name.replace(" ", "%20") + "\">Search imagej wiki for help</a>"; completions.add(makeListEntry(this, headline, null, description)); } } addCompletions(completions); }
Source:
<code>public byte[] serialize() { <START> ByteBuffer buffer = ByteBuffer.allocate(9); <END> buffer.put(TYPE_DOUBLE); buffer.putDouble(value); return buffer.array(); }</code><technical_language>magic number</technical_language>

Target:
public byte[] serialize() { ByteBuffer buffer = ByteBuffer.allocate(Byte.BYTES + Double.BYTES); buffer.put(getType().getByte()); buffer.putDouble(value); return buffer.array(); }
Source:
<code>public static String createUniqueText() { <START> return String.format(UNIQUE_TEXT_FORMAT, System.nanoTime()); <END> }</code><technical_language>millis shoud enought</technical_language>

Target:
public static String createUniqueText() { return String.format(UNIQUE_TEXT_FORMAT, System.currentTimeMillis()); }
Source:
<code>default Optional<String> getGroupId() { Optional<String> standalone = getAttribute(getClass().getClassLoader(), "Engine-GroupID-" + getId()); if (standalone.isPresent()) { return standalone; } <START> return Optional.empty(); <END> }</code><technical_language>IMO this read a ternary operator if (...) { return ...; } return ...; pattern</technical_language>

Target:
default Optional<String> getGroupId() { return Optional.empty(); }
Source:
<code><START> protected VersionInfo fetchVersionInfoFromResponse(Map<String, String> responseAsMap) throws ParseException { <END> return new VersionInfo.Builder().withBuildDate(responseAsMap.get(VersionInfo.VersionKeys.BUILD_DATE)) .withGitCommit(responseAsMap.get(VersionInfo.VersionKeys.GIT_COMMIT)) .withGitVersion(responseAsMap.get(VersionInfo.VersionKeys.GIT_VERSION)) .withMajor(responseAsMap.get(VersionInfo.VersionKeys.MAJOR)) .withMinor(responseAsMap.get(VersionInfo.VersionKeys.MINOR)) .withGitTreeState(responseAsMap.get(VersionInfo.VersionKeys.GIT_TREE_STATE)) .withPlatform(responseAsMap.get(VersionInfo.VersionKeys.PLATFORM)) .withGoVersion(responseAsMap.get(VersionInfo.VersionKeys.GO_VERSION)) .withCompiler(responseAsMap.get(VersionInfo.VersionKeys.COMPILER)) .build(); }</code><technical_language>This static</technical_language>

Target:
protected static VersionInfo fetchVersionInfoFromResponse(Map<String, String> responseAsMap) throws ParseException { return new VersionInfo.Builder().withBuildDate(responseAsMap.get(VersionInfo.VersionKeys.BUILD_DATE)) .withGitCommit(responseAsMap.get(VersionInfo.VersionKeys.GIT_COMMIT)) .withGitVersion(responseAsMap.get(VersionInfo.VersionKeys.GIT_VERSION)) .withMajor(responseAsMap.get(VersionInfo.VersionKeys.MAJOR)) .withMinor(responseAsMap.get(VersionInfo.VersionKeys.MINOR)) .withGitTreeState(responseAsMap.get(VersionInfo.VersionKeys.GIT_TREE_STATE)) .withPlatform(responseAsMap.get(VersionInfo.VersionKeys.PLATFORM)) .withGoVersion(responseAsMap.get(VersionInfo.VersionKeys.GO_VERSION)) .withCompiler(responseAsMap.get(VersionInfo.VersionKeys.COMPILER)) .build(); }
Source:
<code>private static InetAddress getPrivateIpAddress(DatabaseInstance instance) { Preconditions.checkNotNull(instance, "instance is null"); List<IpMapping> ipMappingList = instance.getIpAddresses(); <START> if (ipMappingList == null || ipMappingList.size() == 0) { <END> throw new IllegalArgumentException("No network interfaces found for database instance '" + instance.getName() + "'."); } else { try { return InetAddress.getByName(ipMappingList.get(0).getIpAddress()); } catch (UnknownHostException e) { throw new IllegalArgumentException("Invalid IPv4 address", e); } } }</code><technical_language>This is consistent code GoogleComputeInstance, I || ipMappingList.isEmpty() for clarity</technical_language>

Target:
private static InetAddress getPrivateIpAddress(DatabaseInstance instance) { Preconditions.checkNotNull(instance, "instance is null"); List<IpMapping> ipMappingList = instance.getIpAddresses(); if (ipMappingList == null || ipMappingList.isEmpty()) { throw new IllegalArgumentException("No network interfaces found for database instance '" + instance.getName() + "'."); } else { try { return InetAddress.getByName(ipMappingList.get(0).getIpAddress()); } catch (UnknownHostException e) { throw new IllegalArgumentException("Invalid IPv4 address", e); } } }
Source:
<code>public ActionResult execute() { String searchKey = getNonNullRequestParamValue(Const.ParamsNames.SEARCH_KEY); List<StudentAttributes> students; List<StudentData> studentDataList = new ArrayList<>(); if (userInfo.isAdmin) { students = logic.searchStudentsInWholeSystem(searchKey).studentList; } else { List<InstructorAttributes> instructors = logic.getInstructorsForGoogleId(userInfo.id); students = logic.searchStudents(searchKey, instructors).studentList; } for (StudentAttributes s : students) { courseIds.add(s.getCourse()); StudentData studentData = new StudentData(s); if (userInfo.isAdmin) { studentData.setKey(StringHelper.encrypt(s.getKey())); } studentDataList.add(studentData); } <START> StudentsData studentsData = new StudentsData(); studentsData.setStudents(studentDataList); populateCourseIdToInstituteMap(); studentsData.getStudents().forEach((StudentData student) -> { student.setInstitute(courseIdToInstituteMap.get(student.getCourseId())); }); <END> studentsData.getStudents().forEach(StudentData::hideLastName); if (userInfo.isInstructor) { studentsData.getStudents().forEach(StudentData::hideInformationForInstructor); } return new JsonResult(studentsData); }</code><technical_language>Instead of creating StudentsData > setting students > students > setting institute data, do data manipulation (setting key institute) studentDataList first? a finalized studentDataList, pass StudentsData constructor mentioned above</technical_language>

Target:
public ActionResult execute() { String searchKey = getNonNullRequestParamValue(Const.ParamsNames.SEARCH_KEY); List<StudentAttributes> students; List<StudentData> studentDataList = new ArrayList<>(); if (userInfo.isAdmin) { students = logic.searchStudentsInWholeSystem(searchKey).studentList; } else { List<InstructorAttributes> instructors = logic.getInstructorsForGoogleId(userInfo.id); students = logic.searchStudents(searchKey, instructors).studentList; } for (StudentAttributes s : students) { StudentData studentData = new StudentData(s); if (userInfo.isAdmin) { studentData.addAdditionalInformationForAdminSearch( StringHelper.encrypt(s.getKey()), getInstituteFromCourseId(s.getCourse())); } else { studentData.hideInformationForInstructor(); } studentData.hideLastName(); studentDataList.add(studentData); } StudentsData studentsData = new StudentsData(); studentsData.setStudents(studentDataList); return new JsonResult(studentsData); }
Source:
<code>public void testFindAll() throws Throwable { String p = "<p>Find all instances of find on the page and highlight them.</p>"; <START> mWebView.loadData("<html><body>" + p + "</body></html>", "text/html", "UTF-8"); <END> waitForLoadComplete(mWebView, TEST_TIMEOUT); runTestOnUiThread(new Runnable() { public void run() { assertEquals(2, mWebView.findAll("find")); } }); }</code><technical_language>need WebView methods called UI thread. (I violations of this in this file, fixed in master - <LINK_0>;a=history;f=tests/tests/webkit/src/android/webkit/cts/WebViewTest.java;h=af35f626ad97d30ef3ca4ce89a679cd2cb0138cd;hb=master - want this auto-merges master)</technical_language>

Target:
public void testFindAll() throws Throwable { getActivity().runOnUiThread(new Runnable() { public void run() { String p = "<p>Find all instances of find on the page and highlight them.</p>"; mWebView.loadData("<html><body>" + p +"</body></html>", "text/html", "UTF-8"); } }); waitForLoadComplete(mWebView, TEST_TIMEOUT); runTestOnUiThread(new Runnable() { public void run() { assertEquals(2, mWebView.findAll("find")); } }); }
Source:
<code>private static ITmfTrace openAndInitializeTrace(IFile file, String location, String name, String typeID) throws TmfTraceException, InstantiationException, IllegalAccessException, FileNotFoundException, TmfTraceImportException { List<TraceTypeHelper> traceTypes = TmfTraceType.selectTraceType(location, typeID); if (traceTypes.isEmpty()) { <START> throw new FileNotFoundException(); <END> } TraceTypeHelper helper = traceTypes.get(0); ITmfTrace trace = helper.getTraceClass().newInstance(); trace.initTrace(file, location, ITmfEvent.class, name, typeID); return trace; }</code><technical_language>message in exception</technical_language>

Target:
private static ITmfTrace openAndInitializeTrace(IFile file, String location, String name, String typeID) throws TmfTraceException, InstantiationException, IllegalAccessException, FileNotFoundException, TmfTraceImportException { List<TraceTypeHelper> traceTypes = TmfTraceType.selectTraceType(location, typeID); if (traceTypes.isEmpty()) { throw new FileNotFoundException("No trace type could not be found"); } TraceTypeHelper helper = traceTypes.get(0); ITmfTrace trace = helper.getTraceClass().newInstance(); trace.initTrace(file, location, ITmfEvent.class, name, typeID); return trace; }
Source:
<code>public void testNoSelfSuppression() { try { try (TestAsyncWriter t = new TestAsyncWriter()) { for (int i = 0; i < 1000; i++) { t.write(i); } Assert.fail("Expected exception"); } } catch (Exception e) { <START> Assert.assertFalse(e.getMessage().contains("Self-suppression")); <END> Assert.assertTrue(e instanceof MyException); } }</code><technical_language>This redundant, bad practice assert based text of exception message. e instanceof MyException assert sufficient</technical_language>

Target:
public void testNoSelfSuppression() { try (TestAsyncWriter t = new TestAsyncWriter()) { try { t.write(1); t.write(2); t.write(3); Assert.fail("Expected exception"); } catch (MyException e) { Assert.assertEquals(1, e.item.intValue()); } try { t.write(4); Assert.fail("Expected exception"); } catch (RuntimeIOException e) { } } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_template_printer); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { showErrorDialog(Localization.get("print.not.supported")); } Bundle data = getIntent().getExtras(); if (data == null) { showErrorDialog(Localization.get("no.print.data")); } this.outputPath = CommCareApplication._().getTempFilePath() + ".html"; <START> String path = data.getString("cc:print_template_reference"); <END> if (path != null) { try { path = ReferenceManager._().DeriveReference(path).getLocalURI(); preparePrintDoc(path); } catch (InvalidReferenceException e) { showErrorDialog(Localization.get("template.invalid")); } } else { SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); path = prefs.getString(CommCarePreferences.PRINT_DOC_LOCATION, ""); if ("".equals(path)) { showErrorDialog(Localization.get("missing.template.file")); } else { preparePrintDoc(path); } } }</code><technical_language>if 'data' is null</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_template_printer); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { showErrorDialog(Localization.get("print.not.supported")); return; } Bundle data = getIntent().getExtras(); if (data == null) { showErrorDialog(Localization.get("no.print.data")); return; } this.outputPath = CommCareApplication._().getTempFilePath() + ".html"; String path = data.getString("cc:print_template_reference"); if (path != null) { try { path = ReferenceManager._().DeriveReference(path).getLocalURI(); preparePrintDoc(path); } catch (InvalidReferenceException e) { showErrorDialog(Localization.get("template.invalid")); } } else { SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); path = prefs.getString(CommCarePreferences.PRINT_DOC_LOCATION, ""); if ("".equals(path)) { showErrorDialog(Localization.get("missing.template.file")); } else { preparePrintDoc(path); } } }
Source:
<code>RtPullComments(final Request req, final Pull pull) { this.entry = req; this.owner = pull; this.request = this.entry.uri() .path("/repos") .path(pull.repo().coordinates().user()) .path(pull.repo().coordinates().repo()) .path("/pulls") <START> .path("" + pull.number()) <END> .path("/comments") .back(); }</code><technical_language>Integer.toString(pull.number()) instead</technical_language>

Target:
RtPullComments(final Request req, final Pull pull) { this.entry = req; this.owner = pull; this.request = this.entry.uri() .path("/repos") .path(pull.repo().coordinates().user()) .path(pull.repo().coordinates().repo()) .path("/pulls") .path(Integer.toString(pull.number())) .path("/comments") .back(); }
Source:
<code>private void close(final boolean clean) { if (state() == State.CREATED) { transitionTo(State.CLOSING); } else { if (state() == State.RUNNING) { if (clean) { commit(); } <START> <END> transitionTo(State.CLOSING); } if (state() == State.CLOSING) { executeAndMaybeSwallow(clean, () -> { StateManagerUtil.closeStateManager(log, logPrefix, clean, false, stateMgr, stateDirectory, TaskType.STANDBY); }, "state manager close"); } else { throw new IllegalStateException("Illegal state " + state() + " while closing standby task " + id); } } closeTaskSensor.record(); transitionTo(State.CLOSED); }</code><technical_language>I checkstyle enforce it... if I should..</technical_language>

Target:
private void close(final boolean clean) { if (state() == State.CREATED) { transitionTo(State.CLOSING); } else { if (state() == State.RUNNING) { if (clean) { commit(); } transitionTo(State.CLOSING); } if (state() == State.CLOSING) { executeAndMaybeSwallow(clean, () -> { StateManagerUtil.closeStateManager(log, logPrefix, clean, false, stateMgr, stateDirectory, TaskType.STANDBY); }, "state manager close", log); } else { throw new IllegalStateException("Illegal state " + state() + " while closing standby task " + id); } } closeTaskSensor.record(); transitionTo(State.CLOSED); }
Source:
<code>public void init() { get( "/forms/query", (req, res) -> util.getMetacardsByFilter(QUERY_TEMPLATE_TAG) .values() .stream() .map(Result::getMetacard) .filter(Objects::nonNull) .map(transformer::toFormTemplate) .filter(Objects::nonNull) .collect(Collectors.toList()), MAPPER::toJson); get( "/forms/result", (req, res) -> util.getMetacardsByFilter(ATTRIBUTE_GROUP_TAG) .values() .stream() .map(Result::getMetacard) .filter(Objects::nonNull) .map(transformer::toFieldFilter) .filter(Objects::nonNull) .collect(Collectors.toList()), MAPPER::toJson); get( "/forms/sharing", (req, res) -> { String currentUser = SubjectUtils.getEmailAddress(SecurityUtils.getSubject()); return util.getMetacardsByFilter(QUERY_TEMPLATE_TAG) .entrySet() .stream() <START> .map(Map.Entry::getValue) <END> .map(Result::getMetacard) .filter( metacard -> metacard.getAttribute(SecurityAttributes.ACCESS_INDIVIDUALS) != null) .filter( metacard -> metacard .getAttribute(SecurityAttributes.ACCESS_INDIVIDUALS) .getValues() .contains(currentUser)) .map(transformer::toFormTemplate) .filter(Objects::nonNull) .collect(Collectors.toList()); }, util::getJson); }</code><technical_language>Right in mind filtering pretty simple: enough distinguish system templates user created templates. security plugins preventing templates shared user returning UI</technical_language>

Target:
public void init() { get( "/forms/query", (req, res) -> util.getMetacardsByFilter(QUERY_TEMPLATE_TAG) .values() .stream() .map(Result::getMetacard) .filter(Objects::nonNull) .map(transformer::toFormTemplate) .filter(Objects::nonNull) .collect(Collectors.toList()), MAPPER::toJson); get( "/forms/result", (req, res) -> util.getMetacardsByFilter(ATTRIBUTE_GROUP_TAG) .values() .stream() .map(Result::getMetacard) .filter(Objects::nonNull) .map(transformer::toFieldFilter) .filter(Objects::nonNull) .collect(Collectors.toList()), MAPPER::toJson); delete( "/forms/:id", APPLICATION_JSON, (req, res) -> { String id = req.params(":id"); DeleteResponse deleteResponse = catalogFramework.delete(new DeleteRequestImpl(id)); if (!deleteResponse.getProcessingErrors().isEmpty()) { res.status(500); LOGGER.debug("Failed to Delete Form {}", id); return ImmutableMap.of("message", "Failed to delete."); } return ImmutableMap.of("message", "Successfully deleted."); }, util::getJson); }
Source:
<code>private static void fillRepresentations(Contract contract, Section section, ApiDeclaration apiDeclaration, Map<String, List<String>> subtypes, List<String> declaredTypes) { Representation representation; for (Entry<String, ModelDeclaration> modelEntry : apiDeclaration .getModels().entrySet()) { ModelDeclaration model = modelEntry.getValue(); if (model.getSubTypes() != null && !model.getSubTypes().isEmpty()) { subtypes.put(model.getId(), model.getSubTypes()); } if (!declaredTypes.contains(modelEntry.getKey())) { declaredTypes.add(modelEntry.getKey()); representation = toRepresentation(model, modelEntry.getKey()); <START> representation.addSections(Arrays.asList(section.getName())); <END> contract.getRepresentations().add(representation); LOGGER.log(Level.FINE, "Representation " + modelEntry.getKey() + " added."); } } }</code><technical_language>adding a addSection method</technical_language>

Target:
private static void fillRepresentations(Contract contract, Section section, ApiDeclaration apiDeclaration, Map<String, List<String>> subtypes, List<String> declaredTypes) { Representation representation; for (Entry<String, ModelDeclaration> modelEntry : apiDeclaration .getModels().entrySet()) { ModelDeclaration model = modelEntry.getValue(); if (model.getSubTypes() != null && !model.getSubTypes().isEmpty()) { subtypes.put(model.getId(), model.getSubTypes()); } if (!declaredTypes.contains(modelEntry.getKey())) { declaredTypes.add(modelEntry.getKey()); representation = toRepresentation(model, modelEntry.getKey()); representation.addSection(section.getName()); contract.getRepresentations().add(representation); LOGGER.log(Level.FINE, "Representation " + modelEntry.getKey() + " added."); } } }
Source:
<code>public Change createChange(IProgressMonitor pm) throws CoreException { pm.beginTask("", 1); try { if (fFieldName.length() == 0) { fFieldName= getInitialFieldName(); } ASTRewrite rewrite= ASTRewrite.create(fCompilationUnitNode.getAST()); if (fInitializeIn == INITIALIZE_IN_METHOD && tempHasInitializer()) addLocalDeclarationSplit(rewrite); else addLocalDeclarationRemoval(rewrite); if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR) addInitializersToConstructors(rewrite); addTempRenames(rewrite); addFieldDeclaration(rewrite); CompilationUnitChange result= new CompilationUnitChange(RefactoringCoreMessages.PromoteTempToFieldRefactoring_name, fCu); result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor())); TextEdit resultingEdits; <START> Map<String, String> formatter= (this.fFormatterOptions == null) ? fCu.getJavaProject().getOptions(true) : this.fFormatterOptions; <END> try { resultingEdits= rewrite.rewriteAST(new Document(fCu.getSource()), formatter); } catch (JavaModelException e) { resultingEdits= rewrite.rewriteAST(); } TextChangeCompatibility.addTextEdit(result, RefactoringCoreMessages.PromoteTempToFieldRefactoring_editName, resultingEdits); return result; } finally { pm.done(); } }</code><technical_language>I check for fFormatterOptions null if true, call rewrite.rewriteAST() code did. Otherwise, new call. explain catch below</technical_language>

Target:
public Change createChange(IProgressMonitor pm) throws CoreException { pm.beginTask("", 1); try { if (fFieldName.length() == 0) { fFieldName= getInitialFieldName(); } ASTRewrite rewrite= ASTRewrite.create(fCompilationUnitNode.getAST()); if (fInitializeIn == INITIALIZE_IN_METHOD && tempHasInitializer()) addLocalDeclarationSplit(rewrite); else addLocalDeclarationRemoval(rewrite); if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR) addInitializersToConstructors(rewrite); addTempRenames(rewrite); addFieldDeclaration(rewrite); CompilationUnitChange result= new CompilationUnitChange(RefactoringCoreMessages.PromoteTempToFieldRefactoring_name, fCu); result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor())); TextEdit resultingEdits; if (fFormatterOptions == null) { resultingEdits= rewrite.rewriteAST(); } else { resultingEdits= rewrite.rewriteAST(new Document(fCu.getSource()), fFormatterOptions); } TextChangeCompatibility.addTextEdit(result, RefactoringCoreMessages.PromoteTempToFieldRefactoring_editName, resultingEdits); return result; } finally { pm.done(); } }
Source:
<code>protected void runTest() throws Throwable { <START> assertNotNull("TestCase.name cannot be null", name); END> Method runMethod = null; try { runMethod = getClass().getMethod(name, (Class[]) null); } catch (NoSuchMethodException e) { fail("Method \"" + name + "\" not found"); } if (!Modifier.isPublic(runMethod.getModifiers())) { fail("Method \"" + name + "\" should be public"); } try { runMethod.invoke(this); } catch (InvocationTargetException e) { e.fillInStackTrace(); throw e.getTargetException(); } catch (IllegalAccessException e) { e.fillInStackTrace(); throw e; } }</code><technical_language>"TestCase name null"</technical_language>

Target:
protected void runTest() throws Throwable { assertNotNull("TestCase name cannot be null", name); Method runMethod = null; try { runMethod = getClass().getMethod(name, (Class[]) null); } catch (NoSuchMethodException e) { fail("Method \"" + name + "\" not found"); } if (!Modifier.isPublic(runMethod.getModifiers())) { fail("Method \"" + name + "\" should be public"); } try { runMethod.invoke(this); } catch (InvocationTargetException e) { e.fillInStackTrace(); throw e.getTargetException(); } catch (IllegalAccessException e) { e.fillInStackTrace(); throw e; } }
Source:
<code>private void setStructureDependencies(final PublisherFilter publisherFilter) throws DotDataException, DotSecurityException { try { <START> for (String inode : contentTypesSet) { <END> structureDependencyHelper(inode,publisherFilter); } } catch (DotDataException e) { Logger.error(this, e.getMessage(),e); } }</code><technical_language>set final</technical_language>

Target:
private void setStructureDependencies(final PublisherFilter publisherFilter) throws DotDataException, DotSecurityException { try { for (final String inode : contentTypesSet) { structureDependencyHelper(inode,publisherFilter); } } catch (DotDataException e) { Logger.error(this, e.getMessage(),e); } }
Source:
<code>public void verify_fallback_in_download_presigned_urls() throws Exception { AmazonServiceException firstException = new AmazonServiceException("Didn't find Object Id in bucket"); firstException.setStatusCode(HttpStatus.NOT_FOUND.value()); int bucketPoolSize = 32; int bucketKeySize = 2; <START> ReflectionTestUtils.setField(service, "bucketPoolSize", bucketPoolSize); <END> ReflectionTestUtils.setField(service, "bucketKeySize", bucketKeySize); ObjectURLGenerator urlGen = new AmazonURLGenerator(); ReflectionTestUtils.setField(urlGen, "s3Client", ObjectDownloadServiceStubFactory.createS3ClientForRadosGW(endpointUrl)); ReflectionTestUtils.setField(service, "urlGenerator", urlGen); when(s3Client.getObject(Mockito.any())).thenThrow(firstException); List<Part> parts = ObjectDownloadServiceStubFactory.createParts(5); ObjectSpecification os = ObjectDownloadServiceStubFactory.createObjectSpecification(objectId, ObjectKeys.getObjectKey(dataDir, objectId), 104857600); os.setParts(parts); os.setRelocated(true); ObjectDownloadService sut = spy(service); doReturn(os).when(sut).getSpecification(objectId); val objSpec = sut.download(objectId, 0, 104857600, false); Part p = objSpec.getParts().get(0); URL url = new URL(p.getUrl()); String path = url.getPath(); if (path.startsWith("/")) { path = path.substring(1, path.length() - 1); } String bucket = Splitter.on('/').trimResults().omitEmptyStrings().split(path).iterator().next(); assertEquals(dataBucketName, bucket); System.out.println(); }</code><technical_language>Same. strings refactoring friendly. Lets address this</technical_language>

Target:
public void verify_fallback_in_download_presigned_urls() throws Exception { val firstException = new AmazonServiceException("Didn't find Object Id in bucket"); firstException.setStatusCode(HttpStatus.NOT_FOUND.value()); int bucketPoolSize = 32; int bucketKeySize = 2; namingService.setBucketPoolSize(bucketPoolSize); namingService.setBucketKeySize(bucketKeySize); val urlGen = new AmazonURLGenerator(); ReflectionTestUtils.setField(urlGen, "s3Client", ObjectDownloadServiceStubFactory.createS3ClientForRadosGW(endpointUrl)); ReflectionTestUtils.setField(service, "urlGenerator", urlGen); when(s3Client.getObject(Mockito.any())).thenThrow(firstException); val parts = ObjectDownloadServiceStubFactory.createParts(5); val os = ObjectDownloadServiceStubFactory.createObjectSpecification(objectId, ObjectKeys.getObjectKey(dataDir, objectId), 104857600); os.setParts(parts); os.setRelocated(true); val sut = spy(service); doReturn(os).when(sut).getSpecification(objectId); val objSpec = sut.download(objectId, 0, 104857600, false); val p = objSpec.getParts().get(0); val url = new URL(p.getUrl()); String path = url.getPath(); if (path.startsWith("/")) { path = path.substring(1, path.length() - 1); } val bucket = Splitter.on('/').trimResults().omitEmptyStrings().split(path).iterator().next(); assertEquals(objectBucketName, bucket); System.out.println(); }
Source:
<code>public void activate() { hueBridgeHandler.registerLightStatusListener(this); <START> logger.info("Hue Light Discovery Service activated."); <END> }</code><technical_language>IMHO remove this log message all</technical_language>

Target:
public void activate() { hueBridgeHandler.registerLightStatusListener(this); }
Source:
<code>public ReadPreference getReadPreference() { if (readPreferenceTagSets.isEmpty()) { <START> return readPreference.getReadPreference(); <END> } else { return ReadPreference.valueOf(readPreference.name(), getReadPreferenceTags()); } }</code><technical_language>rename ReadPreferenceType field readPreference defaultReadPreference necessarily ReadPreference used</technical_language>

Target:
public ReadPreferenceType getReadPreference() { return readPreference; }
Source:
<code>public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); <START> return result; <END> }</code><technical_language>I guess Objects java 7 equals =)</technical_language>

Target:
public int hashCode() { return Objects.hashCode(name); }
Source:
<code>private void checkComment(GHIssueComment comment) throws IOException { GHUser sender = comment.getUser(); String body = comment.getBody(); <START> if (helper.isRequestForTestingPhrase(body)) { <END> logger.log(Level.FINEST, "'Request for testing' comment from bot user {0} ignored.", sender); return; } if (helper.isWhitelistPhrase(body) && helper.isAdmin(sender)) { if (!helper.isWhitelisted(author)) { logger.log(Level.FINEST, "Author {0} not whitelisted, adding to whitelist.", author); helper.addWhitelist(author.getLogin()); } accepted = true; shouldRun = true; } else if (helper.isOktotestPhrase(body) && helper.isAdmin(sender)) { logger.log(Level.FINEST, "Admin {0} gave OK to test", sender); accepted = true; shouldRun = true; } else if (helper.isRetestPhrase(body)) { logger.log(Level.FINEST, "Retest phrase"); if (helper.isAdmin(sender)) { logger.log(Level.FINEST, "Admin {0} gave retest phrase", sender); shouldRun = true; } else if (accepted && helper.isWhitelisted(sender)) { logger.log(Level.FINEST, "Retest accepted and user {0} is whitelisted", sender); shouldRun = true; triggered = true; } } else if (helper.isTriggerPhrase(body)) { logger.log(Level.FINEST, "Trigger phrase"); if (helper.isAdmin(sender)) { logger.log(Level.FINEST, "Admin {0} ran trigger phrase", sender); shouldRun = true; triggered = true; } else if (accepted && helper.isWhitelisted(sender)) { logger.log(Level.FINEST, "Trigger accepted and user {0} is whitelisted", sender); shouldRun = true; triggered = true; } } }</code><technical_language>I adding sender.isMe() check is right do</technical_language>

Target:
private void checkComment(GHIssueComment comment) throws IOException { GHUser sender = comment.getUser(); String body = comment.getBody(); if (helper.isBotUser(sender)) { logger.log(Level.FINEST, "Comment from bot user {0} ignored.", sender); return; } if (helper.isWhitelistPhrase(body) && helper.isAdmin(sender)) { if (!helper.isWhitelisted(author)) { logger.log(Level.FINEST, "Author {0} not whitelisted, adding to whitelist.", author); helper.addWhitelist(author.getLogin()); } accepted = true; shouldRun = true; } else if (helper.isOktotestPhrase(body) && helper.isAdmin(sender)) { logger.log(Level.FINEST, "Admin {0} gave OK to test", sender); accepted = true; shouldRun = true; } else if (helper.isRetestPhrase(body)) { logger.log(Level.FINEST, "Retest phrase"); if (helper.isAdmin(sender)) { logger.log(Level.FINEST, "Admin {0} gave retest phrase", sender); shouldRun = true; } else if (accepted && helper.isWhitelisted(sender)) { logger.log(Level.FINEST, "Retest accepted and user {0} is whitelisted", sender); shouldRun = true; triggered = true; } } else if (helper.isTriggerPhrase(body)) { logger.log(Level.FINEST, "Trigger phrase"); if (helper.isAdmin(sender)) { logger.log(Level.FINEST, "Admin {0} ran trigger phrase", sender); shouldRun = true; triggered = true; } else if (accepted && helper.isWhitelisted(sender)) { logger.log(Level.FINEST, "Trigger accepted and user {0} is whitelisted", sender); shouldRun = true; triggered = true; } } if (shouldRun) { triggerSender = sender; commentBody = body; } }
Source:
<code>public void testAllNodesFollowOneLeader() { ICluster seed = Cluster.joinAwait(); LeaderElection seedLeader = createLeaderElection(seed); List<LeaderElection> leaders = createCluster(seed); awaitSeconds(30); <START> Address seedLeaderAddress = seedLeader.leader(); <END> for (LeaderElection m : leaders) { Address memberLeaderAddress = m.leader(); assertTrue("Expected leader address " + seedLeaderAddress + ", but actual: " + memberLeaderAddress, memberLeaderAddress.equals(seedLeaderAddress)); } for (LeaderElection m : leaders) { m.cluster().shutdown(); } seed.shutdown(); }</code><technical_language>Is seed member chosen a leader</technical_language>

Target:
public void testAllNodesFollowOneLeader() { ICluster seed = Cluster.joinAwait(); LeaderElection seedLeader = createLeaderElection(seed); Queue<LeaderElection> leaders = createCluster(seed, NUM_OF_NODES); awaitSeconds(4); Member seedMember = leaders.peek().leader(); for (LeaderElection m : leaders) { Member member = m.leader(); assertTrue("Expected leader address " + seedMember.address() + ", but actual: " + member.address(), member.equals(seedMember)); } teardownCluster(seed, leaders); }
Source:
<code>private Provider<KubevirtProviderProperties> getProvider() { <START> return backend.runInternalQuery(QueryType.GetProviderById, new IdQueryParameters(getCachedVm().getClusterId())).getReturnValue(); <END> }</code><technical_language>replace a direct call providerDao.get(getCachedVm().getClusterId())</technical_language>

Target:
private Provider<KubevirtProviderProperties> getProvider() { return (Provider<KubevirtProviderProperties>) providerDao.get(getCachedVm().getClusterId()); }
Source:
<code>public void testDifferentGAVsWithAlias() throws Exception { Long oldPid = processClient.startProcess(CONTAINER_ALIAS, PROCESS_ID_EVALUATION); assertNotNull(oldPid); <START> assertTrue(oldPid > 0); <END> ProcessInstance processInstance = processClient.getProcessInstance(CONTAINER_ALIAS, oldPid); assertNotNull(processInstance); assertEquals(CONTAINER_ID, processInstance.getContainerId()); ReleaseId differentReleaseId101 = new ReleaseId("org.kie.server.different", "different-gav-definition-project", "1.0.1.Final"); KieContainerResource containerResource = new KieContainerResource(CONTAINER_ID_101, differentReleaseId101); containerResource.setContainerAlias(CONTAINER_ALIAS); client.createContainer(CONTAINER_ID_101, containerResource); Long pid = processClient.startProcess(CONTAINER_ALIAS, PROCESS_ID_EVALUATION_2); assertNotNull(pid); assertTrue(pid > 0); processInstance = processClient.getProcessInstance(CONTAINER_ALIAS, pid); assertNotNull(processInstance); assertEquals(CONTAINER_ID_101, processInstance.getContainerId()); }</code><technical_language>information assertTrue give in case greater 0. If care value, assertions for numbers. in general, AssertJ simplifies assertions in tests. considered library</technical_language>

Target:
public void testDifferentGAVsWithAlias() throws Exception { Long oldPid = processClient.startProcess(CONTAINER_ALIAS, PROCESS_ID_EVALUATION); assertThat(oldPid).isNotNull().isGreaterThan(0); ProcessInstance processInstance = processClient.getProcessInstance(CONTAINER_ALIAS, oldPid); assertThat(processInstance).isNotNull(); assertThat(processInstance.getContainerId()).isEqualTo(CONTAINER_ID); ReleaseId differentReleaseId101 = new ReleaseId("org.kie.server.different", "different-gav-definition-project", "1.0.1.Final"); KieContainerResource containerResource = new KieContainerResource(CONTAINER_ID_101, differentReleaseId101); containerResource.setContainerAlias(CONTAINER_ALIAS); client.createContainer(CONTAINER_ID_101, containerResource); Long pid = processClient.startProcess(CONTAINER_ALIAS, PROCESS_ID_EVALUATION_2); assertThat(pid).isNotNull().isGreaterThan(0); processInstance = processClient.getProcessInstance(CONTAINER_ALIAS, pid); assertThat(processInstance).isNotNull(); assertThat(processInstance.getContainerId()).isEqualTo(CONTAINER_ID_101); }
Source:
<code>private void validateScope(Set<String> scopes) throws OAuthProblemException{ for(String s: scopes) { String[] scopeParts = s.split(":"); Application application = applicationService.find(scopeParts[0]); if(application == null || (scopeParts.length > 1 && !application.hasScope(scopeParts[1]))) <START> throw OAuthProblemException.error("invalid_request", String.format("Invalid scope %s", s)); <END> } }</code><technical_language>invalid_scope in place of invalid_request</technical_language>

Target:
private void validateScope(Set<String> scopes) throws OAuthProblemException{ for(String s: scopes) { String[] scopeParts = s.split(":"); Application application = applicationService.find(scopeParts[0]); if(application == null || (scopeParts.length > 1 && !application.hasScope(scopeParts[1]))) throw OAuthProblemException.error("invalid_scope", String.format("Invalid scope %s", s)); } }