auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean doFilter = false; try { HttpServletRequest req = (HttpServletRequest) request; if (!FiltersHelper.isAuthenticated(req)) { String profileName = (String) request.getAttribute(FiltersHelper.Constants.REQUEST_PROFILE_KEY); ExtMap authRecord = (ExtMap) request.getAttribute(FiltersHelper.Constants.REQUEST_AUTH_RECORD_KEY); if (authRecord != null) { InitialContext context = new InitialContext(); try { VdcLoginReturnValueBase returnValue = (VdcLoginReturnValueBase)FiltersHelper.getBackend(context).login(new LoginUserParameters( profileName, authRecord, loginAsAdmin ? VdcActionType.LoginAdminUser : VdcActionType.LoginUser) ); if (returnValue.getSucceeded()) { <START> HttpSession session = req.getSession(true); <END> session.setAttribute( SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY, returnValue.getSessionId() ); } } finally { context.close(); } } } doFilter = true; } catch (Exception ex) { log.error(String.format("Error in login to engine. Message is: %1$s", ex.getMessage())); ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (doFilter) { chain.doFilter(request, response); } }</code><technical_language>This creates a session if user "Prefer: persistent-auth"</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean doFilter = false; try { HttpServletRequest req = (HttpServletRequest) request; if (!FiltersHelper.isAuthenticated(req)) { String profileName = (String) request.getAttribute(FiltersHelper.Constants.REQUEST_PROFILE_KEY); ExtMap authRecord = (ExtMap) request.getAttribute(FiltersHelper.Constants.REQUEST_AUTH_RECORD_KEY); if (authRecord != null) { InitialContext context = new InitialContext(); try { VdcLoginReturnValueBase returnValue = (VdcLoginReturnValueBase)FiltersHelper.getBackend(context).login(new LoginUserParameters( profileName, authRecord, loginAsAdmin ? VdcActionType.LoginAdminUser : VdcActionType.LoginUser) ); if (returnValue.getSucceeded()) { request.setAttribute( SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY, returnValue.getSessionId() ); } } finally { context.close(); } } } doFilter = true; } catch (Exception ex) { log.error("Error in login to engine ", ex); ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (doFilter) { chain.doFilter(request, response); } }
Source:
<code>public void evaluate() throws Throwable { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); try { instrumentation.toggleCompatChangesForTest(enabled, disabled); testStatement.evaluate(); } finally { <START> instrumentation.clearCompatChangesForTest(); <END> } }</code><technical_language>is guaranteed happen? If not, calling clear toggle sense</technical_language>

Target:
public void evaluate() throws Throwable { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); Compatibility.Callbacks inAppState = Compatibility.setOverrides(enabled, disabled); ArrayMap<Long, Boolean> overrides = new ArrayMap<>(); for (Long change: enabled) { overrides.put(change, true); } for (Long change: disabled) { overrides.put(change, false); } Map<Long, Boolean> systemServerConfig = instrumentation.setCompatChangesForTest(overrides); try { testStatement.evaluate(); } finally { Compatibility.clearOverrides(inAppState); instrumentation.clearCompatChangesForTest(systemServerConfig); } }
Source:
<code>public PartialFileHistory.FileHistoryId read(InputNode node) throws InvalidXMLNodeException { try { return PartialFileHistory.FileHistoryId.parseFileId(node.getValue()); } catch (Exception e) { <START> throw new InvalidXMLNodeException(e); <END> } }</code><technical_language>Change InvalidXmlNodeException</technical_language>

Target:
public PartialFileHistory.FileHistoryId read(InputNode node) throws InvalidXmlNodeException { try { return PartialFileHistory.FileHistoryId.parseFileId(node.getValue()); } catch (Exception e) { throw new InvalidXmlNodeException(e); } }
Source:
<code>private void saveInExtensionClass(Map<String, Class<?>> extensionClasses, Class<?> clazz, String name) { Class<?> c = extensionClasses.get(name); if (c == null) { extensionClasses.put(name, clazz); } else if (c != clazz) { duplicateExceptionMsg.append("Duplicate extension ") .append(type.getName()) .append(" name ") .append(name) .append(" on ") .append(c.getName()) .append(" and ") .append(clazz.getName()) <START> .append("\r\n"); <END> } }</code><technical_language>I recommend switching System.lineSeparator() better, do think</technical_language>

Target:
private void saveInExtensionClass(Map<String, Class<?>> extensionClasses, Class<?> clazz, String name) { Class<?> c = extensionClasses.get(name); if (c == null) { extensionClasses.put(name, clazz); } else if (c != clazz) { throw new DubboInitCheckException("Duplicate extension " + type.getName() + " name " + name + " on " + c.getName() + " and " + clazz.getName()); } }
Source:
<code>public void checkNumberOfLoggedEvents(AbstractAuditBackend backend, AuditQueryBuilder builder) { List<LogEntry> logs = backend.queryLogs(builder); if (logs.size() != NUM_OF_EVENTS) { System.out.println("ERROR: Incorrect log entries: "+ Arrays.toString(logs.toArray())); <START> } <END> assertEquals(NUM_OF_EVENTS, logs.size()); }</code><technical_language>Instead of if + System.out cleaner do: assertEquals("Incorrect log entries: "+ Arrays.toString(logs.toArray()), NUM_OF_EVENTS, logs.size());</technical_language>

Target:
public void checkNumberOfLoggedEvents(AbstractAuditBackend backend, AuditQueryBuilder builder) { List<LogEntry> logs = backend.queryLogs(builder); assertEquals("Incorrect log entries: "+ Arrays.toString(logs.toArray()), NUM_OF_EVENTS, logs.size()); }
Source:
<code>private MethodSpec createMapToContentValuesMethodSpec(@NotNull final StorIOContentResolverTypeMeta storIOContentResolverTypeMeta, @NotNull final ClassName storIOContentResolverClassName) { MethodSpec.Builder builder = MethodSpec.methodBuilder("mapToContentValues") .addJavadoc("{@inheritDoc}\n") .addAnnotation(Override.class) .addAnnotation(ANDROID_NON_NULL_ANNOTATION_CLASS_NAME) .addModifiers(PUBLIC) .returns(ClassName.get("android.content", "ContentValues")) .addParameter(ParameterSpec.builder(storIOContentResolverClassName, "object") .addAnnotation(ANDROID_NON_NULL_ANNOTATION_CLASS_NAME) .build()) .addStatement("ContentValues contentValues = new ContentValues($L)", storIOContentResolverTypeMeta.columns.size()) .addCode("\n"); for (final StorIOContentResolverColumnMeta columnMeta : storIOContentResolverTypeMeta.columns.values()) { final boolean primitive = columnMeta.element.asType().getKind().isPrimitive(); <START> final boolean needIgnoreNull = columnMeta.storIOColumn.ignoreNull(); <END> final boolean ignoreNull = !primitive && needIgnoreNull; if (ignoreNull) { builder.beginControlFlow("if($L != null)", "object." + columnMeta.fieldName); } builder.addStatement( "contentValues.put($S, $L)", columnMeta.storIOColumn.name(), "object." + columnMeta.fieldName ); if (ignoreNull) { builder.endControlFlow(); } } return builder .addCode("\n") .addStatement("return contentValues") .build(); }</code><technical_language>sense throw log if user annotated primitive type @IgnoreNull</technical_language>

Target:
private MethodSpec createMapToContentValuesMethodSpec(@NotNull final StorIOContentResolverTypeMeta storIOContentResolverTypeMeta, @NotNull final ClassName storIOContentResolverClassName) { MethodSpec.Builder builder = MethodSpec.methodBuilder("mapToContentValues") .addJavadoc("{@inheritDoc}\n") .addAnnotation(Override.class) .addAnnotation(ANDROID_NON_NULL_ANNOTATION_CLASS_NAME) .addModifiers(PUBLIC) .returns(ClassName.get("android.content", "ContentValues")) .addParameter(ParameterSpec.builder(storIOContentResolverClassName, "object") .addAnnotation(ANDROID_NON_NULL_ANNOTATION_CLASS_NAME) .build()) .addStatement("ContentValues contentValues = new ContentValues($L)", storIOContentResolverTypeMeta.columns.size()) .addCode("\n"); for (final StorIOContentResolverColumnMeta columnMeta : storIOContentResolverTypeMeta.columns.values()) { final boolean ignoreNull = columnMeta.storIOColumn.ignoreNull(); if (ignoreNull) { builder.beginControlFlow("if($L != null)", "object." + columnMeta.fieldName); } builder.addStatement( "contentValues.put($S, $L)", columnMeta.storIOColumn.name(), "object." + columnMeta.fieldName ); if (ignoreNull) { builder.endControlFlow(); } } return builder .addCode("\n") .addStatement("return contentValues") .build(); }
Source:
<code>public void seek(IonReaderBinarySpan position) { <START> if (position == null) <END> { throw new IllegalArgumentException("Position invalid for binary reader"); } if (!(_input instanceof FromByteArray)) { throw new UnsupportedOperationException("Binary seek not implemented for non-byte array backed sources"); } FromByteArray input = (FromByteArray)_input; input._pos = (int) (position._offset + _physical_start_offset); input._limit = (int) (position._limit + _physical_start_offset); input._eof = false; for (;;) { SavePoint sp = input._save_points._active_stack; if (sp == null) break; input._save_points.savePointPopActive(sp); sp.free(); } re_init_raw(); init_user(this._catalog); _symbols = position._symbol_table; }</code><technical_language>suggest leaving style fixes for independent PR</technical_language>

Target:
public void seek(IonReaderBinarySpan position) { IonReaderBinarySpan pos = position; if (pos == null) { throw new IllegalArgumentException("Position invalid for binary reader"); } if (!(_input instanceof FromByteArray)) { throw new UnsupportedOperationException("Binary seek not implemented for non-byte array backed sources"); } FromByteArray input = (FromByteArray)_input; input._pos = (int) (pos._offset + _physical_start_offset); input._limit = (int) (pos._limit + _physical_start_offset); input._eof = false; for (;;) { SavePoint sp = input._save_points._active_stack; if (sp == null) break; input._save_points.savePointPopActive(sp); sp.free(); } re_init_raw(); init_user(this._catalog); _symbols = pos._symbol_table; }
Source:
<code><START> public Consumer<MouseEvent> getAction() { <END> if (refCount > 0) { return action; } return null; }</code><technical_language>If action is set in doResolve depending refCount: * refCount remain a variable instead of a field * condition useless return action</technical_language>

Target:
public Consumer<MouseEvent> getAction() { return action; }
Source:
<code>public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) { <START> cleanupPodAnnotation(task); <END> super.taskCompletedWithProblems(executor, task, durationMS, problems); LOGGER.log(Level.FINE, " Computer " + this + " taskCompletedWithProblems"); }</code><technical_language>do remove annotation afterwards? information useful pod finished</technical_language>

Target:
public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) { annotatePodWithTaskInfo(task, "completedWithProblems"); super.taskCompletedWithProblems(executor, task, durationMS, problems); LOGGER.log(Level.FINE, " Computer " + this + " taskCompletedWithProblems"); }
Source:
<code>public static @Nullable Unit<?> parseUnit(String pattern) { if (StringUtils.isBlank(pattern)) { return null; } int lastBlankIndex = pattern.lastIndexOf(" "); if (lastBlankIndex < 0) { return null; } String unitSymbol = pattern.substring(lastBlankIndex).trim(); if (StringUtils.isNotBlank(unitSymbol) && !unitSymbol.equals(UNIT_PLACEHOLDER)) { try { Quantity<?> quantity = Quantities.getQuantity("1 " + unitSymbol); return quantity.getUnit(); } catch (IllegalArgumentException e) { <START> logger.warn("Unknown unit from pattern: {}", unitSymbol); <END> } } return null; }</code><technical_language>if expect it, please log debug</technical_language>

Target:
public static @Nullable Unit<?> parseUnit(String pattern) { if (StringUtils.isBlank(pattern)) { return null; } int lastBlankIndex = pattern.lastIndexOf(" "); if (lastBlankIndex < 0) { return null; } String unitSymbol = pattern.substring(lastBlankIndex).trim(); if (StringUtils.isNotBlank(unitSymbol) && !unitSymbol.equals(UNIT_PLACEHOLDER)) { if (UNIT_PERCENT_FORMAT_STRING.equals(unitSymbol)) { return SmartHomeUnits.PERCENT; } try { Quantity<?> quantity = Quantities.getQuantity("1 " + unitSymbol); return quantity.getUnit(); } catch (IllegalArgumentException e) { logger.debug("Unknown unit from pattern: {}", unitSymbol); } } return null; }
Source:
<code>public void fit(MultiDataSet dataSet) { <START> throw new DL4JInvalidInputException("MultiLayerNetwork can't handle MultiDataSet. Please consider use of ComputationGraph"); <END> }</code><technical_language>a big deal, *could* if want check for single feature array + single label array, convert DataSet. wrap MultiDataSetIteartor in a DataSetIterator (I mind this post merge of this; open issue for want tackle now)</technical_language>

Target:
public void fit(MultiDataSet dataSet) { if (dataSet.getFeatures().length == 1 && dataSet.getLabels().length == 1) { INDArray features = null; INDArray labels = null; INDArray fMask = null; INDArray lMask = null; if (dataSet.getFeaturesMaskArrays() != null) fMask = dataSet.getFeaturesMaskArrays()[0]; if (dataSet.getFeaturesMaskArrays() != null) lMask = dataSet.getLabelsMaskArrays()[0]; features = dataSet.getFeatures()[0]; labels = dataSet.getLabels()[0]; DataSet ds = new DataSet(features, labels, fMask, lMask); fit(ds); } throw new DL4JInvalidInputException("MultiLayerNetwork can't handle MultiDataSet. Please consider use of ComputationGraph"); }
Source:
<code>protected void executeCommand() { <START> Cluster cluster = clusterDao.get(getParameters().getClusterId()); <END> if (cluster.supportsGlusterService()) { try { glusterSyncJob.refreshSelfHealData(cluster); } catch (Exception e) { log.error("Error while refreshing Gluster self heal data of cluster '{}': {}", cluster.getName(), e.getMessage()); log.debug("Exception", e); } setSucceeded(true); } }</code><technical_language>if cluster is null</technical_language>

Target:
protected void executeCommand() { try { glusterSyncJob.refreshSelfHealData(cluster); } catch (Exception e) { log.error("Error while refreshing Gluster self heal data of cluster '{}': {}", cluster.getName(), e.getMessage()); log.debug("Exception", e); setSucceeded(false); } setSucceeded(true); }
Source:
<code>public void setUp() throws Exception { TestPersistentBinaryDeque.setupTestDir(); m_pbd = PersistentBinaryDeque.builder(TestPersistentBinaryDeque.TEST_NONCE, TestPersistentBinaryDeque.TEST_DIR, s_logger) .compression(true) .initialExtraHeader(null, TestPersistentBinaryDeque.SERIALIZER).build(); <START> m_pbd.setRetentionPolicy(BinaryDeque.RetentionPolicyType.TIME_MS, new Long(s_retainMillis)); <END> m_pbd.startRetentionPolicyEnforcement(); }</code><technical_language>Minor: Long.valueOf instead of new Long</technical_language>

Target:
public void setUp() throws Exception { TestPersistentBinaryDeque.setupTestDir(); m_pbd = PersistentBinaryDeque.builder(TestPersistentBinaryDeque.TEST_NONCE, TestPersistentBinaryDeque.TEST_DIR, s_logger) .compression(true) .initialExtraHeader(null, TestPersistentBinaryDeque.SERIALIZER).build(); m_pbd.setRetentionPolicy(BinaryDeque.RetentionPolicyType.TIME_MS, Long.valueOf(s_retainMillis)); m_pbd.startRetentionPolicyEnforcement(); }
Source:
<code>public void setSearchString(String value) { if (value == null || (!value.toUpperCase().contains(SPACE + SyntaxChecker.SORTBY) <START> && !value.toUpperCase().contains(SPACE + SyntaxChecker.PAGE))) { <END> setSearchString(value, true); } }</code><technical_language>worth extracting SORTBY / PAGE substring check separate method, for example: private boolean containsTokens(String search, SyntaxChecker... tokens)</technical_language>

Target:
public void setSearchString(String value) { if (value == null || !containsTokens(value, SyntaxChecker.SORTBY, SyntaxChecker.PAGE, SyntaxChecker.SORTDIR_ASC, SyntaxChecker.SORTDIR_DESC)) { setSearchString(value, true); } }
Source:
<code>public void run() { AbstractHistogram currentHist = LatencyHistogramStats.constructHistogram(false); <START> ClientInterface ci = VoltDB.instance().getClientInterface(); <END> if (ci != null) { List<AbstractHistogram> thisci = ci.getLatencyStats(); for (AbstractHistogram info : thisci) { currentHist.add(info); } } AbstractHistogram diffHist = currentHist.copy(); diffHist.subtract(m_previousHist); diffHist.setEndTimeStamp(System.currentTimeMillis()); m_previousHist = currentHist; m_diffHistProvider.set(diffHist); }</code><technical_language>clientInterface lines instead of ci</technical_language>

Target:
public void run() { AbstractHistogram currentHist = LatencyHistogramStats.constructHistogram(false); ClientInterface clientInterface = VoltDB.instance().getClientInterface(); if (clientInterface != null) { List<AbstractHistogram> statsHists = clientInterface.getLatencyStats(); for (AbstractHistogram hist : statsHists) { currentHist.add(hist); } } AbstractHistogram diffHist = currentHist.copy(); diffHist.subtract(m_previousHist); diffHist.setEndTimeStamp(System.currentTimeMillis()); m_previousHist = currentHist; m_diffHistProvider.set(diffHist); }
Source:
<code>default CompletableFuture<Map<K, V>> getAllAsync(Set<?> keys) { return CompletableFuture.completedFuture( keys.stream().map(k -> new AbstractMap.SimpleEntry<>((K) k, getAsync((K) k))) <START> .collect(Collectors.toList()).stream() <END> .filter(entry -> entry.getValue().join() != null) .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().join()))); }</code><technical_language>need materialize previous map operation a List obtain a stream it, passing pipe stream coming out of map</technical_language>

Target:
default CompletableFuture<Map<K, V>> getAllAsync(Set<?> keys) { Object[] orderedKeys = new Object[keys.size()]; CompletableFuture[] futures = new CompletableFuture[keys.size()]; int i = 0; for (Object key : keys) { orderedKeys[i] = key; futures[i] = getAsync((K) key); ++i; } return CompletableFuture.allOf(futures).thenApply(nil -> { Map<K, V> map = new HashMap<>(futures.length); for (int j = 0; j < futures.length; ++j) { V value = (V) futures[j].join(); if (value != null) map.put((K) orderedKeys[j], value); } return map; }); }
Source:
<code>public void compareEqual() throws Exception { final String sha = "c2c53d66948214258a26ca9ca845d7ac0c17f8e7"; final MkStorage storage = new MkStorage.InFile(); final Repo repo = this.repo(storage); final MkRepoCommit commit = new MkRepoCommit(storage, repo, sha); final MkRepoCommit other = new MkRepoCommit(storage, repo, sha); MatcherAssert.assertThat( commit.compareTo(other), Matchers.equalTo(0) <START> ); <END> }</code><technical_language>Please, add case other.compareTo(commit)</technical_language>

Target:
public void compareEqual() throws Exception { final String sha = "c2c53d66948214258a26ca9ca845d7ac0c17f8e7"; final MkStorage storage = new MkStorage.InFile(); final Repo repo = this.repo(storage); final MkRepoCommit commit = new MkRepoCommit(storage, repo, sha); final MkRepoCommit other = new MkRepoCommit(storage, repo, sha); MatcherAssert.assertThat( commit.compareTo(other), Matchers.equalTo(0) ); MatcherAssert.assertThat( other.compareTo(commit), Matchers.equalTo(0) ); }
Source:
<code>private void reportInstanceCapacityMetrics(ClusterStatusMonitor clusterStatusMonitor, ResourceControllerDataProvider dataProvider, Map<String, Resource> resourceMap, CurrentStateOutput currentStateOutput) { asyncExecute(dataProvider.getAsyncTasksThreadPool(), () -> { try { Map<String, ResourceAssignment> currentStateAssignment = currentStateOutput.getCurrentStateAssignment(resourceMap.keySet()); ClusterModel clusterModel = ClusterModelProvider.generateClusterModelFromCurrentState( dataProvider, resourceMap, currentStateAssignment); Map<String, Double> maxCapacityUsageMap = new HashMap<>(); Map<String, Map<String, Integer>> instanceCapacityMap = new HashMap<>(); for (AssignableNode node : clusterModel.getAssignableNodes().values()) { String instanceName = node.getInstanceName(); double usage = node.getProjectedHighestUtilization(Collections.emptyMap()); <START> maxCapacityUsageMap.put(instanceName, usage); <END> instanceCapacityMap.put(instanceName, node.getInstanceCapacity()); } clusterStatusMonitor.updateMaxCapacityUsage(maxCapacityUsageMap); clusterStatusMonitor.updateInstanceCapacity(instanceCapacityMap); } catch (Exception ex) { LOG.error("Failed to report instance capacity metrics.", ex); } return null; }); }</code><technical_language>maxUsageMap</technical_language>

Target:
private void reportInstanceCapacityMetrics(ClusterStatusMonitor clusterStatusMonitor, ResourceControllerDataProvider dataProvider, Map<String, Resource> resourceMap, CurrentStateOutput currentStateOutput) { asyncExecute(dataProvider.getAsyncTasksThreadPool(), () -> { try { Map<String, IdealState> idealStateMap = dataProvider.getIdealStates(); Map<String, Resource> resourceToMonitorMap = resourceMap.entrySet().stream() .filter(idealStateMap::containsKey) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Map<String, ResourceAssignment> currentStateAssignment = currentStateOutput.getAssignment(resourceToMonitorMap.keySet()); ClusterModel clusterModel = ClusterModelProvider.generateClusterModelFromExistingAssignment( dataProvider, resourceToMonitorMap, currentStateAssignment); for (AssignableNode node : clusterModel.getAssignableNodes().values()) { String instanceName = node.getInstanceName(); double usage = node.getProjectedHighestUtilization(Collections.emptyMap()); clusterStatusMonitor .updateInstanceCapacityStatus(instanceName, usage, node.getMaxCapacity()); } } catch (Exception ex) { LOG.error("Failed to report instance capacity metrics. Exception message: {}", ex.getMessage()); } return null; }); }
Source:
<code>public FormValidation doValidate(@QueryParameter String apiUrl, @QueryParameter String username, @QueryParameter Secret password, @QueryParameter String oauthAccessToken) throws IOException { GitHub gitHub; if (Util.fixEmpty(apiUrl) != null) { <START> gitHub = GitHub.connectToEnterprise(apiUrl,username,oauthAccessToken); <END> } else { gitHub = GitHub.connect(username,oauthAccessToken,Secret.toString(password)); } if (gitHub.isCredentialValid()) return FormValidation.ok("Verified"); else return FormValidation.error("Failed to validate the account"); }</code><technical_language>GitHub.connectToEnterprise(apiUrl,oauthAccessToken) match login()</technical_language>

Target:
public FormValidation doValidate(@QueryParameter String apiUrl, @QueryParameter String username, @QueryParameter Secret password, @QueryParameter String oauthAccessToken) throws IOException { GitHub gitHub; if (Util.fixEmpty(apiUrl) != null) { gitHub = GitHub.connectToEnterprise(apiUrl,oauthAccessToken); } else { gitHub = GitHub.connect(username,oauthAccessToken,Secret.toString(password)); } if (gitHub.isCredentialValid()) return FormValidation.ok("Verified"); else return FormValidation.error("Failed to validate the account"); }
Source:
<code>public void setMandoc(String value) { <START> mandoc = value; <END> }</code><technical_language>this.mandoc consistent setCtags()</technical_language>

Target:
public void setMandoc(String value) { this.mandoc = value; }
Source:
<code>void simpleDecoupled(ClusterMap clusterMap) throws JSONException, InterruptedException, StoreException, IOException, CoordinatorException { MockConnectionPool.mockCluster = new MockCluster(clusterMap); AmbryCoordinator ac = new AmbryCoordinator(getVProps(), clusterMap); for (int i = 0; i < 20; ++i) { BlobProperties putBlobProperties = new BlobProperties(100, "serviceId", "memberId", "contentType", false, Utils.Infinite_Time); ByteBuffer putUserMetadata = ByteBuffer.allocate(10); for (byte b = 0; b < 10; b++) { putUserMetadata.put(b); } <START> <END> ByteBuffer putContent = ByteBuffer.allocate(100); for (byte b = 0; b < 100; b++) { putContent.put(b); } putContent.flip(); String blobId = putBlob(ac, putBlobProperties, putUserMetadata, putContent); getBlob(ac, blobId, putBlobProperties, putUserMetadata, putContent); deleteBlob(ac, blobId); } ac.close(); }</code><technical_language>putUsreMetadata is flipped</technical_language>

Target:
void simpleDecoupled(ClusterMap clusterMap) throws JSONException, InterruptedException, StoreException, IOException, CoordinatorException { MockConnectionPool.mockCluster = new MockCluster(clusterMap); AmbryCoordinator ac = new AmbryCoordinator(getVProps(), clusterMap); for (int i = 0; i < 20; ++i) { BlobProperties putBlobProperties = new BlobProperties(100, "serviceId", "memberId", "contentType", false, Utils.Infinite_Time); ByteBuffer putUserMetadata = getByteBuffer(10, false); ByteBuffer putContent = getByteBuffer(100, true); String blobId = putBlob(ac, putBlobProperties, putUserMetadata, putContent); getBlob(ac, blobId, putBlobProperties, putUserMetadata, putContent); deleteBlob(ac, blobId); } ac.close(); }
Source:
<code>private Optional<ServiceReference<ServletContext>[]> getServiceReferences(BundleContext context) { try { return Optional.ofNullable( (ServiceReference<ServletContext>[]) context.getAllServiceReferences( null, "(" + Constants.OBJECTCLASS + "=javax.servlet.ServletContext)")); } catch (InvalidSyntaxException | ClassCastException e) { LOGGER.error( <START> "Problem getting ServletContexts from OSGI, One of the servlets running might print stack traces to the browser. A system restart is recommended. See debug logs for additional details."); <END> LOGGER.debug("Problems getting ServletContexts from OSGI Details:", e); return Optional.empty(); } }</code><technical_language>OSGI a period instead of a comma, a reading it</technical_language>

Target:
private Optional<ServiceReference<ServletContext>[]> getServiceReferences(BundleContext context) { try { return Optional.ofNullable( (ServiceReference<ServletContext>[]) context.getAllServiceReferences( null, "(" + Constants.OBJECTCLASS + "=javax.servlet.ServletContext)")); } catch (InvalidSyntaxException | ClassCastException e) { LOGGER.error( "Problem getting ServletContexts from OSGI. One of the servlets running might print stack traces to the browser. A system restart is recommended. See debug logs for additional details."); LOGGER.debug("Problems getting ServletContexts from OSGI Details:", e); return Optional.empty(); } }
Source:
<code>default SortedSet<SourceFile> getVersionsSourcefiles(Long entryId, Long versionId, List<DescriptorLanguage.FileType> fileTypes, VersionDAO versionDAO) { Version version = versionDAO.findVersionInEntry(entryId, versionId); if (version == null) { <START> throw new CustomWebApplicationException("Workflow version" + versionId + " does not exist for this workflow", HttpStatus.SC_BAD_REQUEST); <END> } SortedSet<SourceFile> sourceFiles = version.getSourceFiles(); if (fileTypes != null && !fileTypes.isEmpty()) { sourceFiles = sourceFiles.stream().filter(sourceFile -> fileTypes.contains(sourceFile.getType())).collect(Collectors.toCollection( TreeSet::new)); } return sourceFiles; }</code><technical_language>Remove mention of "workflow" this (because of tools services)</technical_language>

Target:
default SortedSet<SourceFile> getVersionsSourcefiles(Long entryId, Long versionId, List<DescriptorLanguage.FileType> fileTypes, VersionDAO versionDAO) { Version version = versionDAO.findVersionInEntry(entryId, versionId); if (version == null) { throw new CustomWebApplicationException("Version " + versionId + " does not exist for this entry", HttpStatus.SC_BAD_REQUEST); } SortedSet<SourceFile> sourceFiles = version.getSourceFiles(); if (fileTypes != null && !fileTypes.isEmpty()) { sourceFiles = sourceFiles.stream().filter(sourceFile -> fileTypes.contains(sourceFile.getType())).collect(Collectors.toCollection( TreeSet::new)); } return sourceFiles; }
Source:
<code>private static AbstractConfiguration createDefaultConfigInstance() { ConcurrentCompositeConfiguration config = new ConcurrentCompositeConfiguration(); int indexForContainerConfig = 0; try { DynamicURLConfiguration defaultURLConfig = new DynamicURLConfiguration(); config.addConfiguration(defaultURLConfig, URL_CONFIG_NAME); indexForContainerConfig = config.getIndexOfConfiguration(defaultURLConfig); } catch (Throwable e) { logger.warn("Failed to create default dynamic configuration", e); } <START> if (!Boolean.getBoolean(DISABLE_DEFAULT_ENV_CONFIG)) { <END> EnvironmentConfiguration envConfig = new EnvironmentConfiguration(); config.addConfiguration(envConfig, ENV_CONFIG_NAME); indexForContainerConfig = config.getIndexOfConfiguration(envConfig); } if (!Boolean.getBoolean(DISABLE_DEFAULT_SYS_CONFIG)) { SystemConfiguration sysConfig = new SystemConfiguration(); config.addConfiguration(sysConfig, SYS_CONFIG_NAME); indexForContainerConfig = config.getIndexOfConfiguration(sysConfig); } config.setContainerConfigurationIndex(indexForContainerConfig); ConcurrentCompositeConfiguration appOverrideConfig = new ConcurrentCompositeConfiguration(); config.addConfiguration(appOverrideConfig, APPLICATION_PROPERTIES); return config; }</code><technical_language>I system properties (-D) higher priority environment variables. of this way: environment variables applicable processes running OS, system properties override for a specific JVM process</technical_language>

Target:
private static AbstractConfiguration createDefaultConfigInstance() { ConcurrentCompositeConfiguration config = new ConcurrentCompositeConfiguration(); try { DynamicURLConfiguration defaultURLConfig = new DynamicURLConfiguration(); config.addConfiguration(defaultURLConfig, URL_CONFIG_NAME); } catch (Throwable e) { logger.warn("Failed to create default dynamic configuration", e); } if (!Boolean.getBoolean(DISABLE_DEFAULT_SYS_CONFIG)) { SystemConfiguration sysConfig = new SystemConfiguration(); config.addConfiguration(sysConfig, SYS_CONFIG_NAME); } if (!Boolean.getBoolean(DISABLE_DEFAULT_ENV_CONFIG)) { EnvironmentConfiguration envConfig = new EnvironmentConfiguration(); config.addConfiguration(envConfig, ENV_CONFIG_NAME); } ConcurrentCompositeConfiguration appOverrideConfig = new ConcurrentCompositeConfiguration(); config.addConfiguration(appOverrideConfig, APPLICATION_PROPERTIES); config.setContainerConfigurationIndex(config.getIndexOfConfiguration(appOverrideConfig)); return config; }
Source:
<code>protected void removeIntermediateFiles(FSRecordCompactionOperator.OutputMetaData metaData) { logger.debug("found metaData = {}", metaData); committedTuples.remove(metaData); try { Path dest = new Path(metaData.getPath()); FileStatus[] statuses = fs.listStatus(dest.getParent()); for (FileStatus status : statuses) { String statusName = status.getPath().getName(); if (statusName.endsWith(TMP_EXTENSION) && statusName.startsWith(metaData.getFileName())) { String actualFileName = statusName.substring(0, statusName.lastIndexOf('.', statusName.lastIndexOf('.') - 1)); logger.debug("actualFileName = {}", actualFileName); if (metaData.getFileName().equals(actualFileName)) { logger.debug("deleting stray file {}", statusName); fs.delete(status.getPath(), true); } } else if (statusName.equals(metaData.getFileName())) { logger.info("deleting s3-compaction file {}", statusName); fs.delete(status.getPath(), true); } } } catch (IOException e) { logger.error("Unable to Delete a file: {}", metaData.getFileName()); } metaData.setPath(getDirectoryName() + Path.SEPARATOR + metaData.getFileName()); <START> outputPort.emit(metaData); <END> }</code><technical_language>Emit if port is connected; else, tuples in bufferserver for consume</technical_language>

Target:
protected void removeIntermediateFiles(FSRecordCompactionOperator.OutputMetaData metaData) { logger.debug("found metaData = {}", metaData); committedTuples.remove(metaData); try { Path dest = new Path(metaData.getPath()); FileStatus[] statuses = fs.listStatus(dest.getParent()); for (FileStatus status : statuses) { String statusName = status.getPath().getName(); if (statusName.endsWith(TMP_EXTENSION) && statusName.startsWith(metaData.getFileName())) { String actualFileName = statusName.substring(0, statusName.lastIndexOf('.', statusName.lastIndexOf('.') - 1)); logger.debug("actualFileName = {}", actualFileName); if (metaData.getFileName().equals(actualFileName)) { logger.debug("deleting stray file {}", statusName); fs.delete(status.getPath(), true); } } else if (statusName.equals(metaData.getFileName())) { logger.info("deleting s3-compaction file {}", statusName); fs.delete(status.getPath(), true); } } } catch (IOException e) { logger.error("Unable to Delete a file: {}", metaData.getFileName()); } }
Source:
<code>protected void executeCommand() { boolean addedGroupThatAllowsViewingChildren = false; List<ActionGroup> groups = getParameters().getActionGroups(); for (ActionGroup group : groups) { addedGroupThatAllowsViewingChildren |= group.allowsViewingChildren(); getRoleGroupMapDao().save(new RoleGroupMap(group, getParameters().getRoleId())); <START> appendCustomValueSeparatedByComma("ActionGroup", group.toString()); <END> } if (addedGroupThatAllowsViewingChildren) { Role role = getRole(); if (!role.allowsViewingChildren()) { role.setAllowsViewingChildren(true); getRoleDao().update(role); } } setSucceeded(true); }</code><technical_language>s/SeparatedByComma/CommaSeparated/</technical_language>

Target:
protected void executeCommand() { boolean addedGroupThatAllowsViewingChildren = false; List<ActionGroup> groups = getParameters().getActionGroups(); for (ActionGroup group : groups) { addedGroupThatAllowsViewingChildren |= group.allowsViewingChildren(); getRoleGroupMapDao().save(new RoleGroupMap(group, getParameters().getRoleId())); appendCustomValueCommaSeparated("ActionGroup", group.toString()); } if (addedGroupThatAllowsViewingChildren) { Role role = getRole(); if (!role.allowsViewingChildren()) { role.setAllowsViewingChildren(true); getRoleDao().update(role); } } setSucceeded(true); }
Source:
<code>protected void addHtmlClass(final String text) { if (!Util.empty(text)) { if (this.htmlClassList == null) { this.htmlClassList = new HashSet<>(); } <START> this.htmlClassList.add(text); <END> } }</code><technical_language>Do is worth 'trimming value</technical_language>

Target:
protected void addHtmlClass(final String text) { if (!Util.empty(text)) { if (this.htmlClasses == null) { this.htmlClasses = new HashSet<>(); } this.htmlClasses.add(text); } }
Source:
<code>public void testGetStartingOffsetsWhenStreamMetadataIsNull() { final String storeName = "test-get-starting-offset-store"; final String taskName = "test-get-starting-offset-task"; <START> Set<SystemStreamPartition> ssps = IntStream.range(1, 6) .mapToObj(idx -> new SystemStreamPartition("test-system", "test-stream", new Partition(idx))) .collect(Collectors.toSet()); Map<Partition, SystemStreamMetadata.SystemStreamPartitionMetadata> partitionMetadata = ssps.stream() .collect(Collectors.toMap(SystemStreamPartition::getPartition, x -> new SystemStreamMetadata.SystemStreamPartitionMetadata(null, "1", "2"))); <END> TaskSideInputStorageManager testSideInputStorageManager = new MockTaskSideInputStorageManagerBuilder(taskName, LOGGED_STORE_DIR) .addLoggedStore(storeName, ssps) .addStreamMetadata(Collections.singletonMap(new SystemStream("test-system", "test-stream"), new SystemStreamMetadata("test-stream", partitionMetadata))) .build(); initializeSideInputStorageManager(testSideInputStorageManager); ssps.forEach(ssp -> { String startingOffset = testSideInputStorageManager.getStartingOffset( new SystemStreamPartition("test-system", "test-stream", ssp.getPartition())); Assert.assertNull("Starting offset should be null", startingOffset); }); }</code><technical_language>purpose for multiple ssps if testing condition</technical_language>

Target:
public void testGetStartingOffsetsWhenStreamMetadataIsNull() { final String storeName = "test-get-starting-offset-store"; final String taskName = "test-get-starting-offset-task"; Set<SystemStreamPartition> ssps = IntStream.range(1, 2) .mapToObj(idx -> new SystemStreamPartition("test-system", "test-stream", new Partition(idx))) .collect(Collectors.toSet()); Map<Partition, SystemStreamMetadata.SystemStreamPartitionMetadata> partitionMetadata = ssps.stream() .collect(Collectors.toMap(SystemStreamPartition::getPartition, x -> new SystemStreamMetadata.SystemStreamPartitionMetadata(null, "1", "2"))); TaskSideInputStorageManager testSideInputStorageManager = new MockTaskSideInputStorageManagerBuilder(taskName, LOGGED_STORE_DIR) .addLoggedStore(storeName, ssps) .addStreamMetadata(Collections.singletonMap(new SystemStream("test-system", "test-stream"), new SystemStreamMetadata("test-stream", partitionMetadata))) .build(); initializeSideInputStorageManager(testSideInputStorageManager); ssps.forEach(ssp -> { String startingOffset = testSideInputStorageManager.getStartingOffset( new SystemStreamPartition("test-system", "test-stream", ssp.getPartition())); Assert.assertNull("Starting offset should be null", startingOffset); }); }
Source:
<code>public void testCreateTableStatement() throws Exception { String tableName = generateUniqueName(); String schemaName = generateUniqueName(); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName); <START> String properties = "TTL=2592000,IMMUTABLE_ROWS=true,DISABLE_WAL=true"; <END> String createTable = "CREATE TABLE "+ pTableFullName + "(K VARCHAR NOT NULL PRIMARY KEY, " + "V1 VARCHAR, V2 VARCHAR) TTL=2592000, IMMUTABLE_ROWS=TRUE, DISABLE_WAL=TRUE"; try (Connection conn = DriverManager.getConnection(getUrl(), props)) { conn.createStatement().execute(createTable); conn.commit(); String args = {"-tb", tableName, "-s", schemaName}; SchemaExtractionTool set = new SchemaExtractionTool(); set.setConf(conn.unwrap(PhoenixConnection.class).getQueryServices().getConfiguration()); set.run(args); Assert.assertEquals(createTable, set.getOutput().toUpperCase()); } }</code><technical_language>nit: please remove this variable? is anymore</technical_language>

Target:
public void testCreateTableStatement() throws Exception { String tableName = generateUniqueName(); String schemaName = generateUniqueName(); String pTableFullName = SchemaUtil.getQualifiedTableName(schemaName, tableName); String createTableStmt = "CREATE TABLE "+ pTableFullName + "(K VARCHAR NOT NULL PRIMARY KEY, " + "V1 VARCHAR, V2 VARCHAR) TTL=2592000, IMMUTABLE_ROWS=TRUE, DISABLE_WAL=TRUE"; List<String> queries = new ArrayList<String>(){}; queries.add(createTableStmt); String result = runSchemaExtractionTool(schemaName, tableName, null, queries); Assert.assertEquals(createTableStmt, result.toUpperCase()); }
Source:
<code>public void manualJPushAlert(long id) { JPushAlertModel jPushAlertModel = jPushAlertMapper.findJPushAlertModelById(id); if (jPushAlertModel != null) { if (jPushAlertModel.isAutomatic()) { logger.debug("JPush is failed, this JPush is not manual, id = " + id); return; } <START> List<String> districtCode = jPushAlertModel.getPushObjects(); <END> List<String> districtName = null; if (CollectionUtils.isNotEmpty(districtCode)) { districtName = Lists.transform(districtCode, new Function<String, String>() { @Override public String apply(String input) { return DistrictUtil.convertCodeToName(input); } }); } if (jPushAlertModel.getPushUserType().contains(PushUserType.ALL) && jPushAlertModel.getPushObjects() == null) { String[] jumpToOrLink = chooseJumpToOrLink(new JPushAlertDto(jPushAlertModel)); mobileAppJPushClient.sendPushAlertByAll(String.valueOf(jPushAlertModel.getId()), jPushAlertModel.getContent(), jumpToOrLink[0], jumpToOrLink[1], jPushAlertModel.getPushSource()); } else { List<String> loginNames = findManualJPushAlertUserLoginName(jPushAlertModel.getPushUserType(), districtName); if (CollectionUtils.isEmpty(loginNames)) { logger.debug("this JPush without data, id = " + id); return; } autoJPushByBatchRegistrationId(jPushAlertModel, loginNames, jPushAlertModel.getPushSource()); } jPushAlertModel.setStatus(PushStatus.SEND_SUCCESS); jPushAlertMapper.update(jPushAlertModel); } else { logger.debug("this JPush is disabled, id = " + id); } }</code><technical_language>PushDistricts</technical_language>

Target:
public void manualJPushAlert(long id) { JPushAlertModel jPushAlertModel = jPushAlertMapper.findJPushAlertModelById(id); if (jPushAlertModel != null) { if (jPushAlertModel.isAutomatic()) { logger.debug("JPush is failed, this JPush is not manual, id = " + id); return; } List<String> districtCode = jPushAlertModel.getPushDistricts(); List<String> districtName = null; if (CollectionUtils.isNotEmpty(districtCode)) { districtName = Lists.transform(districtCode, new Function<String, String>() { @Override public String apply(String input) { return DistrictUtil.convertCodeToName(input); } }); } if (jPushAlertModel.getPushUserType().contains(PushUserType.ALL) && jPushAlertModel.getPushDistricts() == null) { String[] jumpToOrLink = chooseJumpToOrLink(new JPushAlertDto(jPushAlertModel)); mobileAppJPushClient.sendPushAlertByAll(String.valueOf(jPushAlertModel.getId()), jPushAlertModel.getContent(), jumpToOrLink[0], jumpToOrLink[1], jPushAlertModel.getPushSource()); } else { List<String> loginNames = findManualJPushAlertUserLoginName(jPushAlertModel.getPushUserType(), districtName); if (CollectionUtils.isEmpty(loginNames)) { logger.debug("this JPush without data, id = " + id); return; } autoJPushByBatchRegistrationId(jPushAlertModel, loginNames, jPushAlertModel.getPushSource()); } jPushAlertModel.setStatus(PushStatus.SEND_SUCCESS); jPushAlertMapper.update(jPushAlertModel); } else { logger.debug("this JPush is disabled, id = " + id); } }
Source:
<code>public synchronized void setH2DbService(H2DbService dbService) { this.dbService = dbService; <START> startDbStore(); <END> }</code><technical_language>need this synchronized</technical_language>

Target:
public synchronized void setH2DbService(H2DbService dbService) { this.dbService = dbService; startDbStore(); signalPublisher(); }
Source:
<code>public void addFeedbackResponseComment(String addResponseCommentId, String commentText) { <START> waitForElementPresence(By.id(addResponseCommentId)); <END> WebElement addResponseCommentForm = browser.driver.findElement(By.id(addResponseCommentId)); WebElement parentContainer = addResponseCommentForm.findElement(By.xpath("../..")); WebElement showResponseCommentAddFormButton = parentContainer.findElement(By.id("button_add_comment")); click(showResponseCommentAddFormButton); WebElement editorElement = addResponseCommentForm.findElement(By.className("mce-content-body")); waitForRichTextEditorToLoad(editorElement.getAttribute("id")); fillRichTextEditor(editorElement.getAttribute("id"), commentText); click(addResponseCommentForm.findElement(By.className("col-sm-offset-5")).findElement(By.tagName("a"))); if (commentText.isEmpty()) { waitForElementToBeClickable(editorElement); } else { waitForElementToDisappear(By.id(addResponseCommentId)); } }</code><technical_language>Is this part of issue</technical_language>

Target:
public void addFeedbackResponseComment(String addResponseCommentId, String commentText) { WebElement addResponseCommentForm = browser.driver.findElement(By.id(addResponseCommentId)); WebElement parentContainer = addResponseCommentForm.findElement(By.xpath("../..")); WebElement showResponseCommentAddFormButton = parentContainer.findElement(By.id("button_add_comment")); click(showResponseCommentAddFormButton); WebElement editorElement = addResponseCommentForm.findElement(By.className("mce-content-body")); waitForRichTextEditorToLoad(editorElement.getAttribute("id")); fillRichTextEditor(editorElement.getAttribute("id"), commentText); click(addResponseCommentForm.findElement(By.className("col-sm-offset-5")).findElement(By.tagName("a"))); if (commentText.isEmpty()) { waitForElementToBeClickable(editorElement); } else { waitForElementToDisappear(By.id(addResponseCommentId)); } }
Source:
<code>private void startPythonWorker() throws IOException { String pythonWorker = MyriaConstants.PYTHONWORKER; ProcessBuilder pb = new ProcessBuilder(MyriaConstants.PYTHONEXEC, "-m", pythonWorker); final Map<String, String> env = pb.environment(); env.put("PYTHONUNBUFFERED", "YES"); pb.redirectError(Redirect.INHERIT); pb.redirectOutput(Redirect.INHERIT); worker = pb.start(); OutputStream stdin = worker.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(stdin, StandardCharsets.UTF_8); out.write(serverSocket.getLocalPort() + "\n"); out.flush(); clientSock = serverSocket.accept(); LOGGER.info("successfully launched worker"); setupStreams(); <START> return; <END> }</code><technical_language>do need setupStreams()? Also, return;</technical_language>

Target:
private void startPythonWorker() throws IOException { String pythonWorker = MyriaConstants.PYTHONWORKER; ProcessBuilder pb = new ProcessBuilder(MyriaConstants.PYTHONEXEC, "-m", pythonWorker); final Map<String, String> env = pb.environment(); env.put("PYTHONUNBUFFERED", "YES"); pb.redirectError(Redirect.INHERIT); pb.redirectOutput(Redirect.INHERIT); worker = pb.start(); OutputStream stdin = worker.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(stdin, StandardCharsets.UTF_8); out.write(serverSocket.getLocalPort() + "\n"); out.flush(); clientSock = serverSocket.accept(); setupStreams(); }
Source:
<code>public static boolean isStopGlusterProcessesSupported(Version version) { <START> return Version.v3_5.compareTo(version) <= 0; <END> }</code><technical_language>instead: return Version.v3_5.less(version);</technical_language>

Target:
public static boolean isStopGlusterProcessesSupported(Version version) { return Version.v3_5.lessOrEquals(version); }
Source:
<code>public static List<FilterEntry> parse(String filters) { List<FilterEntry> ret = new LinkedList<>(); if (!PATTERN_BLANK.matcher(filters).matches()) { Matcher m = PATTERN_PARSE.matcher(filters); boolean ok = false; int expectedStart = 0; while (m.find()) { log.debug("parse: handling '{}'", m.group(0)); if (m.start() != expectedStart) { throw new RuntimeException("Cannot parse filters"); } expectedStart = m.end(); ok = m.end() == m.regionEnd(); ret.add( new FilterEntry( m.group("anymsg") != null ? null : m.group("message"), <START> m.group("anyseverity") != null ? null : m.group("severity"), <END> m.group("exclude") != null, m.group("recipient") == null || m.group("anyrecipient") != null ? null : new Recipient( m.group("transport"), m.group("name") ) ) ); } if (!ok) { throw new IllegalArgumentException("Cannot parse filters"); } } return ret; }</code><technical_language>if put * in pattern of severity avoid anyseverity if like</technical_language>

Target:
public static List<FilterEntry> parse(String filters) { List<FilterEntry> ret = new LinkedList<>(); if (!PATTERN_BLANK.matcher(filters).matches()) { Matcher m = PATTERN_PARSE.matcher(filters); boolean ok = false; int expectedStart = 0; while (m.find()) { log.debug("parse: handling '{}'", m.group(0)); if (m.start() != expectedStart) { throw new RuntimeException("Cannot parse filters"); } expectedStart = m.end(); ok = m.end() == m.regionEnd(); ret.add( new FilterEntry( m.group("anymsg") != null ? null : m.group("message"), m.group("severity") == null || m.group("severity").equals("*") ? null : AuditLogSeverity.valueOf(m.group("severity")), m.group("exclude") != null, m.group("recipient") == null || m.group("anyrecipient") != null ? null : new Recipient( m.group("transport"), m.group("name") ) ) ); } if (!ok) { throw new IllegalArgumentException("Cannot parse filters"); } } return ret; }
Source:
<code>private void deleteAllRefs() throws Exception { final RevWalk rw = new RevWalk(db); for <START> (final Ref <END> r : db.getRefDatabase().getAllRefs()) { if (Constants.HEAD.equals(r.getName())) continue; final RefUpdate u = db.updateRef(r.getName()); u.setForceUpdate(true); u.delete(rw); } }</code><technical_language>optional: avoid unnecessary 'final'</technical_language>

Target:
private void deleteAllRefs() throws Exception { final RevWalk rw = new RevWalk(db); for (Ref r : db.getRefDatabase().getAllRefs()) { if (Constants.HEAD.equals(r.getName())) continue; final RefUpdate u = db.updateRef(r.getName()); u.setForceUpdate(true); u.delete(rw); } }