auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testExtAndDirWithOneRule() { HashMap<String, Rule> rules = new HashMap<>(); rules.put("Rule", new Rule("testExtAndDirWithOneRule", new Rule.ExtensionCondition("jpg"), new MetaTypeCondition(MetaTypeCondition.Type.FILES), new ParentPathCondition("dir1"), null, null, null)); FilesSet Files_Ext_Dirs_Filter = new FilesSet("Filter", "Filter to find all jpg files in dir1.", false, true, rules); try { Case openCase = Case.getOpenCase(); runIngestJob(openCase.getDataSources(), Files_Ext_Dirs_Filter); FileManager fileManager = Case.getOpenCase().getServices().getFileManager(); <START> List<AbstractFile> results = fileManager.findFiles("%.jpg%"); <END> assertEquals(12, results.size()); for (AbstractFile file : results) { if (file.getParentPath().equalsIgnoreCase("/dir1/") && file.getNameExtension().equalsIgnoreCase("jpg")) { String errMsg = String.format("File %s (objId=%d) unexpectedly blocked by the file filter.", file.getName(), file.getId()); assertTrue(errMsg, !(file.getMIMEType() == null || file.getMIMEType().isEmpty())); } else { String errMsg = String.format("File %s (objId=%d) unexpectedly passed by the file filter.", file.getName(), file.getId()); assertTrue(errMsg, file.getMIMEType() == null); } } } catch (NoCurrentCaseException | TskCoreException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } }</code><technical_language>This code is checking files jpg extensions. is enough for this test case</technical_language>

Target:
public void testExtAndDirWithOneRule() { HashMap<String, Rule> rules = new HashMap<>(); rules.put("Rule", new Rule("testExtAndDirWithOneRule", new Rule.ExtensionCondition("jpg"), new MetaTypeCondition(MetaTypeCondition.Type.FILES), new ParentPathCondition("dir1"), null, null, null)); FilesSet filesExtDirsFilter = new FilesSet("Filter", "Filter to find all jpg files in dir1.", false, true, rules); try { Case openCase = Case.getOpenCase(); runIngestJob(openCase.getDataSources(), filesExtDirsFilter); FileManager fileManager = Case.getOpenCase().getServices().getFileManager(); List<AbstractFile> results = fileManager.findFiles("%%"); assertEquals(62, results.size()); for (AbstractFile file : results) { if (file.getParentPath().equalsIgnoreCase("/dir1/") && file.getNameExtension().equalsIgnoreCase("jpg")) { String errMsg = String.format("File %s (objId=%d) unexpectedly blocked by the file filter.", file.getName(), file.getId()); assertTrue(errMsg, file.getMIMEType() != null && !file.getMIMEType().isEmpty()); } else { String errMsg = String.format("File %s (objId=%d) unexpectedly passed by the file filter.", file.getName(), file.getId()); assertTrue(errMsg, file.getMIMEType() == null); } } } catch (NoCurrentCaseException | TskCoreException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } }
Source:
<code>public void stop() { giant.lock(); try { <START> log.info("Naptime!"); <END> queue.clear(); running.clear(); active = false; } finally { giant.unlock(); } }</code><technical_language>I understand this line is saying</technical_language>

Target:
public void stop() { giant.lock(); try { log.info("Naptime! Shutting down until we are started again."); queue.clear(); running.clear(); active = false; } finally { giant.unlock(); } }
Source:
<code>public static void setOCToPreferences(String ocPath) { WorkbenchPreferenceDialog dialog = new WorkbenchPreferenceDialog(); OpenShift3PreferencePage page = new OpenShift3PreferencePage(dialog); dialog.open(); dialog.select(page); page.setOCLocation(ocPath); try { <START> new WaitUntil(new ControlIsEnabled(new PushButton("Apply")), TimePeriod.DEFAULT); END> } catch (WaitTimeoutExpiredException exc) { fail("WaitTimeoutExpiredException occured while processing oc binary on path " + ocPath); } page.apply(); dialog.cancel(); }</code><technical_language>@odockal CDKLabel.Buttons.APPLY</technical_language>

Target:
public static void setOCToPreferences(String ocPath) { WorkbenchPreferenceDialog dialog = new WorkbenchPreferenceDialog(); OpenShift3PreferencePage page = new OpenShift3PreferencePage(dialog); dialog.open(); dialog.select(page); page.setOCLocation(ocPath); try { new WaitUntil(new ControlIsEnabled(new PushButton(CDKLabel.Buttons.APPLY)), TimePeriod.DEFAULT); } catch (WaitTimeoutExpiredException exc) { fail("WaitTimeoutExpiredException occured while processing oc binary on path " + ocPath); } page.apply(); dialog.cancel(); }
Source:
<code>@Test public void testFullOuterJoinUniqueness1() { final String sql = "select e.jb, d.nm \n" + "from (select cast(null as int) jb from sales.emp " + " where empno = 10 group by cast(null as int)) as e \n" + "full outer join (select cast (null as int) nm from sales.dept " + "group by cast(null as int)) as d on e.jb = d.nm \n" + "group by e.jb, d.nm"; <START> RelNode rel = convertSql(sql); <END> final RelMetadataQuery mq = RelMetadataQuery.instance(); final ImmutableBitSet allCols = ImmutableBitSet.range(0, rel.getRowType().getFieldCount()); Boolean areGroupByKeysUnique = mq.areColumnsUnique(rel.getInput(0), allCols); assertThat(areGroupByKeysUnique, is(false)); }</code><technical_language>I more readable name empno deptno instead of jb nm</technical_language>

Target:
@Test public void testFullOuterJoinUniqueness1() { final String sql = "select e.empno, d.deptno \n" + "from (select cast(null as int) empno from sales.emp " + " where empno = 10 group by cast(null as int)) as e \n" + "full outer join (select cast (null as int) deptno from sales.dept " + "group by cast(null as int)) as d on e.empno = d.deptno \n" + "group by e.empno, d.deptno"; RelNode rel = convertSql(sql); final RelMetadataQuery mq = RelMetadataQuery.instance(); final ImmutableBitSet allCols = ImmutableBitSet.range(0, rel.getRowType().getFieldCount()); Boolean areGroupByKeysUnique = mq.areColumnsUnique(rel.getInput(0), allCols); assertThat(areGroupByKeysUnique, is(false)); }
Source:
<code>public void scheduleAll(final Project project, final String submitUser) throws SchedulerException, ProjectManagerException { for (final Flow flow : project.getFlows()) { if (flow.isEmbeddedFlow()) { continue; } final String flowFileName = flow.getId() + ".flow"; final int latestFlowVersion = this.projectLoader .getLatestFlowVersion(flow.getProjectId(), flow .getVersion(), flowFileName); if (latestFlowVersion > 0) { final File tempDir = Files.createTempDir(); final File flowFile; try { flowFile = this.projectLoader .getUploadedFlowFile(project.getId(), project.getVersion(), flowFileName, latestFlowVersion, tempDir); final FlowTrigger flowTrigger = FlowLoaderUtils.getFlowTriggerFromYamlFile(flowFile); if (flowTrigger != null) { final Map<String, Object> contextMap = ImmutableMap .of(FlowTriggerQuartzJob.SUBMIT_USER, submitUser, FlowTriggerQuartzJob.FLOW_TRIGGER, flowTrigger, FlowTriggerQuartzJob.FLOW_ID, flow.getId(), FlowTriggerQuartzJob.FLOW_VERSION, latestFlowVersion, FlowTriggerQuartzJob.PROJECT_ID, project.getId()); logger.info("scheduling flow " + flow.getProjectId() + "." + flow.getId()); this.scheduler .registerJob(flowTrigger.getSchedule().getCronExpression(), new QuartzJobDescription (FlowTriggerQuartzJob.class, FlowTriggerQuartzJob.JOB_NAME, generateGroupName(flow), contextMap)); } <START> } catch (final Exception ex) { <END> logger.error("error in registering flow", ex); } finally { FlowLoaderUtils.cleanUpDir(tempDir); } } } }</code><technical_language>detail logger message a lit > error in registering flow trigger <PojrectName_FlowName> in Quartz,</technical_language>

Target:
public void scheduleAll(final Project project, final String submitUser) throws SchedulerException, ProjectManagerException { for (final Flow flow : project.getFlows()) { if (flow.isEmbeddedFlow()) { continue; } final String flowFileName = flow.getId() + ".flow"; final int latestFlowVersion = this.projectLoader .getLatestFlowVersion(flow.getProjectId(), flow .getVersion(), flowFileName); if (latestFlowVersion > 0) { final File tempDir = Files.createTempDir(); final File flowFile; try { flowFile = this.projectLoader .getUploadedFlowFile(project.getId(), project.getVersion(), flowFileName, latestFlowVersion, tempDir); final FlowTrigger flowTrigger = FlowLoaderUtils.getFlowTriggerFromYamlFile(flowFile); if (flowTrigger != null) { final Map<String, Object> contextMap = ImmutableMap .of(FlowTriggerQuartzJob.SUBMIT_USER, submitUser, FlowTriggerQuartzJob.FLOW_TRIGGER, flowTrigger, FlowTriggerQuartzJob.FLOW_ID, flow.getId(), FlowTriggerQuartzJob.FLOW_VERSION, latestFlowVersion, FlowTriggerQuartzJob.PROJECT_ID, project.getId()); logger.info("scheduling flow " + flow.getProjectId() + "." + flow.getId()); this.scheduler .registerJob(flowTrigger.getSchedule().getCronExpression(), new QuartzJobDescription (FlowTriggerQuartzJob.class, FlowTriggerQuartzJob.JOB_NAME, generateGroupName(flow), contextMap)); } } catch (final Exception ex) { logger.error(String.format("error in registering flow [project: %s, flow: %s]", project .getName(), flow.getId()), ex); } finally { FlowLoaderUtils.cleanUpDir(tempDir); } } } }
Source:
<code>protected Collection<TaskAttribute> getAttributes() { Map<String, TaskAttribute> allAttributes = getTaskData().getRoot().getAttributes(); List<TaskAttribute> attributes = new ArrayList<TaskAttribute>(allAttributes.size()); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED)); attributes.add(getTaskData().getRoot() <START> .getMappedAttribute(BugzillaRestTaskSchema.getDefault().RESET_ASSIGNED_TO.getKey())); <END> attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_REPORTER)); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.ADD_SELF_CC)); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_CC)); for (TaskAttribute attribute : allAttributes.values()) { TaskAttributeMetaData properties = attribute.getMetaData(); if (TaskAttribute.KIND_PEOPLE.equals(properties.getKind())) { if (!attributes.contains(attribute)) { attributes.add(attribute); } } } return attributes; }</code><technical_language>Instead of duplicating this code, call super a ListIterator insert reset attribute assigned attribute</technical_language>

Target:
protected Collection<TaskAttribute> getAttributes() { Collection<TaskAttribute> attributes = super.getAttributes(); Integer nextEmptyPosition = attributeOrder.size(); ArrayList<TaskAttribute> resultAttributes = new ArrayList<>(attributes.size()); resultAttributes.addAll(attributes); for (TaskAttribute taskAttribute : attributes) { if (taskAttribute != null) { Integer newPosition = attributeOrder.get(taskAttribute.getId()); if (newPosition == null) { newPosition = nextEmptyPosition++; } resultAttributes.set(newPosition, taskAttribute); } } return resultAttributes; }
Source:
<code>public BytecodeNode generateCall(FunctionHandle functionHandle, BytecodeGeneratorContext context, Type returnType, List<RowExpression> arguments, Optional<Variable> outputBlockVariable) { FunctionManager functionManager = context.getFunctionManager(); ScalarFunctionImplementation function = functionManager.getScalarFunctionImplementation(functionHandle); List<BytecodeNode> argumentsBytecode = new ArrayList<>(); for (int i = 0; i < arguments.size(); i++) { RowExpression argument = arguments.get(i); ScalarFunctionImplementation.ArgumentProperty argumentProperty = function.getArgumentProperty(i); if (argumentProperty.getArgumentType() == VALUE_TYPE) { argumentsBytecode.add(context.generate(argument, Optional.empty())); } else { argumentsBytecode.add(context.generate(argument, Optional.empty(), Optional.of(argumentProperty.getLambdaInterface()))); } } return context.generateCall( <START> functionManager.getFunctionMetadata(functionHandle).getName().getUnqualifiedName(), <END> function, argumentsBytecode, outputBlockVariable.map(variable -> new OutputBlockVariableAndType(variable, returnType))); }</code><technical_language>I I mentioned getSuffix is more accurate getUnqualifiedName. If prefer "unqualified name", more a utility function unqualifyName(qualifiedName). call part of a qualified name "unqualified name"</technical_language>

Target:
public BytecodeNode generateCall(FunctionHandle functionHandle, BytecodeGeneratorContext context, Type returnType, List<RowExpression> arguments, Optional<Variable> outputBlockVariable) { FunctionManager functionManager = context.getFunctionManager(); BuiltInScalarFunctionImplementation function = functionManager.getBuiltInScalarFunctionImplementation(functionHandle); List<BytecodeNode> argumentsBytecode = new ArrayList<>(); for (int i = 0; i < arguments.size(); i++) { RowExpression argument = arguments.get(i); BuiltInScalarFunctionImplementation.ArgumentProperty argumentProperty = function.getArgumentProperty(i); if (argumentProperty.getArgumentType() == VALUE_TYPE) { argumentsBytecode.add(context.generate(argument, Optional.empty())); } else { argumentsBytecode.add(context.generate(argument, Optional.empty(), Optional.of(argumentProperty.getLambdaInterface()))); } } return context.generateCall( functionManager.getFunctionMetadata(functionHandle).getName().getFunctionName(), function, argumentsBytecode, outputBlockVariable.map(variable -> new OutputBlockVariableAndType(variable, returnType))); }
Source:
<code><START> public static co.cask.cdap.etl.proto.v2.ETLPlugin getPlugin(String tableName) { <END> Map<String, String> properties = new HashMap<>(); properties.put("tableName", tableName); return new co.cask.cdap.etl.proto.v2.ETLPlugin("Mock", BatchSink.PLUGIN_TYPE, properties, null); }</code><technical_language>dont need fully qualified name</technical_language>

Target:
public static ETLPlugin getPlugin(String tableName) { Map<String, String> properties = new HashMap<>(); properties.put("tableName", tableName); return new ETLPlugin("Mock", BatchSink.PLUGIN_TYPE, properties, null); }
Source:
<code>public static <T> T[] addAll(final T[] array1, final T... array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } final Class<?> type1 = array1.getClass().getComponentType(); @SuppressWarnings("unchecked") final T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length); System.arraycopy(array1, 0, joinedArray, 0, array1.length); try { System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); } catch (final ArrayStoreException ase) { final Class<?> type2 = array2.getClass().getComponentType(); if (!type1.isAssignableFrom(type2)) { throw IllegalArgumentExceptions.format(ase, "Cannot store %s in an array of %s", type2.getName(), <START> type1.getName(), ase); <END> } throw ase; } return joinedArray; }</code><technical_language>is ase parameter listed twice? wrong</technical_language>

Target:
public static <T> T[] addAll(final T[] array1, final T... array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } final Class<?> type1 = array1.getClass().getComponentType(); @SuppressWarnings("unchecked") final T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length); System.arraycopy(array1, 0, joinedArray, 0, array1.length); try { System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); } catch (final ArrayStoreException ase) { final Class<?> type2 = array2.getClass().getComponentType(); if (!type1.isAssignableFrom(type2)) { throw IllegalArgumentExceptions.format(ase, "Cannot store %s in an array of %s", type2.getName(), type1.getName()); } throw ase; } return joinedArray; }
Source:
<code>public void testDeactivatingTaskAndSavingAllWithOnlyDirtyFiles() throws Exception { List<IEditorPart> dirtyFiles = activateTaskAndOpenFiles(); doReturn(0).when(listener).openTaskDeactivationDialog(anyList()); assertTrue(listener.shouldDeactivateTask(task1)); assertFalse(dirtyFiles.get(0).isDirty()); <START> assertFalse(dirtyFiles.get(1).isDirty()); <END> }</code><technical_language>verify arguments openTaskDeactivationDialog</technical_language>

Target:
public void testDeactivatingTaskAndSavingAllWithOnlyDirtyFiles() throws Exception { List<IEditorPart> dirtyFiles = activateTaskAndEditFiles(); doReturn(0).when(listener).openTaskDeactivationDialog(anyList()); assertTrue(listener.shouldDeactivateTask(task1)); assertFalse(dirtyFiles.get(0).isDirty()); assertFalse(dirtyFiles.get(1).isDirty()); verify(listener).openTaskDeactivationDialog( Matchers.argThat(new CompareListOfReferencesWithoutOrder(makeDirtyReferencesFromParts(dirtyFiles)))); }
Source:
<code>public void testGetDataCenterWith404() throws InterruptedException { server.enqueue(response404()); DataCenter dataCenter = dataCenterApi().getDataCenter("some-id"); <START> assertEquals(dataCenter, null); <END> assertEquals(server.getRequestCount(), 1); assertSent(server, "GET", "/datacenters/some-id"); }</code><technical_language>[minor] assertNull</technical_language>

Target:
public void testGetDataCenterWith404() throws InterruptedException { server.enqueue(response404()); DataCenter dataCenter = dataCenterApi().getDataCenter("some-id"); assertNull(dataCenter); assertEquals(server.getRequestCount(), 1); assertSent(server, "GET", "/datacenters/some-id"); }
Source:
<code>private Network findCurrentNetwork(Map<Network, Set<Guid>> networks) { Network result = networks == null ? null : networks.keySet() .stream() .filter(network -> Objects.equals(network.getProvidedBy().getExternalId(), id)) .findFirst() <START> .orElse(null); <END> if (result == null) { notFound(); } return result; }</code><technical_language>This is hard read. avoid ternary operator</technical_language>

Target:
private Network findCurrentNetwork(Map<Network, Set<Guid>> networks) { final Network result; if (networks == null) { result = null; } else { result = networks.keySet() .stream() .filter(network -> Objects.equals(network.getProvidedBy().getExternalId(), id)) .findFirst() .orElse(null); } if (result == null) { notFound(); } return result; }
Source:
<code>private static boolean makeNodeUpToDate() { if (System.getProperty(NODE_URL_PROPERTY) != null) { String jarUrl = System.getProperty(NODE_URL_PROPERTY); String jarFile = DEFAULT_SCHEDULER_NODE_JAR; if (System.getProperty(NODE_JAR_SAVEAS_PROPERTY) != null) { jarFile = System.getProperty(NODE_JAR_SAVEAS_PROPERTY); } if (!isLocalJarUpToDate(jarUrl, jarFile)) { System.out.println("Downloading node.jar from " + jarUrl + " to " + jarFile); try { File destination = new File(jarFile); File lockFile = null; FileLock lock = null; if (destination.exists()) { <START> lockFile = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value(), "lock"); <END> if (!lockFile.exists()) { lockFile.createNewFile(); } System.out.println("Getting the lock on " + lockFile.getAbsoluteFile()); FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel(); lock = channel.lock(); if (isLocalJarUpToDate(jarUrl, jarFile)) { System.out.println("Another process downloaded node.jar - don't do it anymore"); System.out.println("Releasing the lock on " + lockFile.getAbsoluteFile()); lock.release(); channel.close(); return false; } } FileUtils.copyURLToFile(new URL(jarUrl), destination); System.out.println("Download finished"); cleanExpandDirectory(jarFile); if (lock != null && lockFile != null) { System.out.println("Releasing the lock on " + lockFile.getAbsoluteFile()); lock.release(); } return true; } catch (Exception e) { System.err.println("Cannot download node.jar from " + jarUrl); e.printStackTrace(); return false; } } else { return true; } } else { throw new IllegalArgumentException("No java property " + NODE_URL_PROPERTY + " specified. This property must be set when using " + RMNodeUpdater.class.getSimpleName()); } }</code><technical_language>don t need / lock</technical_language>

Target:
private boolean makeNodeUpToDate() { if (!isLocalJarUpToDate(nodeJarUrl, nodeJarSaveAs)) { logger.info("Downloading node.jar from " + nodeJarUrl + " to " + nodeJarSaveAs); try { File destination = new File(nodeJarSaveAs); File lockFile = null; FileLock lock = null; if (destination.exists()) { lockFile = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value(), "lock"); if (!lockFile.exists()) { lockFile.createNewFile(); } logger.info("Getting the lock on " + lockFile.getAbsoluteFile()); FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel(); lock = channel.lock(); if (isLocalJarUpToDate(nodeJarUrl, nodeJarSaveAs)) { logger.warn("Another process downloaded node.jar - don't do it anymore"); logger.info("Releasing the lock on " + lockFile.getAbsoluteFile()); lock.release(); channel.close(); return false; } } fetchUrl(nodeJarUrl, destination); destination.setLastModified(getRemoteLastModifiedMillis(nodeJarUrl)); logger.info("Download finished"); cleanExpandDirectory(nodeJarSaveAs); if (lock != null && lockFile != null) { logger.info("Releasing the lock on " + lockFile.getAbsoluteFile()); lock.release(); } return true; } catch (Exception e) { logError("Cannot download node.jar from " + nodeJarUrl, e); return false; } } else { return true; } }
Source:
<code>public ExprEval eval(ObjectBinding bindings) { ExprEval ret = expr.eval(bindings); if (ret.type() == ExprType.LONG) { return ExprEval.of(-ret.longValue()); } if (ret.type() == ExprType.DOUBLE) { return ExprEval.of(-ret.doubleValue()); } <START> throw new IllegalArgumentException("unsupported type " + ret.type()); <END> }</code><technical_language>throw IAE instead</technical_language>

Target:
public ExprEval eval(ObjectBinding bindings) { ExprEval ret = expr.eval(bindings); if (ret.type() == ExprType.LONG) { return ExprEval.of(-ret.asLong()); } if (ret.type() == ExprType.DOUBLE) { return ExprEval.of(-ret.asDouble()); } throw new IAE("unsupported type " + ret.type()); }
Source:
<code>public Exchange createExchange(long messageIndex) throws Exception { Exchange exchange = createExchange(); getDataSet().populateMessage(exchange, messageIndex); <START> if (null == disableDataSetIndex || !disableDataSetIndex) { <END> Message in = exchange.getIn(); in.setHeader(Exchange.DATASET_INDEX, messageIndex); } return exchange; }</code><technical_language>coding style is null other side in ==</technical_language>

Target:
public Exchange createExchange(long messageIndex) throws Exception { Exchange exchange = createExchange(); getDataSet().populateMessage(exchange, messageIndex); if (!getDataSetIndex().equals("off")) { Message in = exchange.getIn(); in.setHeader(Exchange.DATASET_INDEX, messageIndex); } return exchange; }
Source:
<code>public int vote(Authentication authentication, Object object, Collection collection) { int vote = ACCESS_ABSTAIN; this.authentication = authentication; SpringSecurityUser user = (SpringSecurityUser) authentication.getPrincipal(); Features features = user.getFeatures(); if (features == null) { return vote; } if (object instanceof FilterInvocation) { <START> user.setUrl(((FilterInvocation) object).getRequestUrl()); <END> } else if (object instanceof ProxyMethodInvocation) { String repositoryId = getRepositoryIdFromUrl(user.getUrl()); logger.debug("Load additional repository privileges by ID " + repositoryId); Collection<String> privilegeNames = user.getFeatures() .getPerRepositoryAuthorities() .get(repositoryId); if (privilegeNames != null) { List<GrantedAuthority> updatedAuthorities = new ArrayList<>(authentication.getAuthorities()); privilegeNames.forEach(name -> { SimpleGrantedAuthority authority = new SimpleGrantedAuthority(name); updatedAuthorities.add(authority); logger.debug("\tAdd " + name + " privilege..."); }); user.setAuthorities(updatedAuthorities); this.authentication = new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(), updatedAuthorities); } } return vote; }</code><technical_language>If I understand correctly org.springframework.web.context.request.RequestContextHolder instead of store url user object field</technical_language>

Target:
public int vote(Authentication authentication, Object object, Collection collection) { int vote = ACCESS_ABSTAIN; SpringSecurityUser user = (SpringSecurityUser) authentication.getPrincipal(); AccessModel accessModel = user.getAccessModel(); if (accessModel == null) { return vote; } String requestUri = UrlUtils.getRequestUri(); if (!requestUri.startsWith(MavenArtifactController.ROOT_CONTEXT)) { return vote; } if (!(object instanceof ProxyMethodInvocation)) { return vote; } String storageId = UrlUtils.getCurrentStorageId(); String repositoryId = UrlUtils.getCurrentRepositoryId(); if (storageId == null || repositoryId == null) { return vote; } final Collection<String> customAuthorities = accessModel.getPathPrivileges(UrlUtils.getRequestUri()); if (customAuthorities != null && !customAuthorities.isEmpty()) { List<GrantedAuthority> authorities = new ArrayList<>(authentication.getAuthorities()); customAuthorities.forEach(privilege -> authorities.add(new SimpleGrantedAuthority(privilege))); logger.debug("Privileges was extended to " + authorities); SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(), authorities)); } return vote; }
Source:
<code>public void shutdown(String taskId) { if (pendingTasks.containsKey(taskId)) { pendingTasks.remove(taskId); return; } final ZkWorker zkWorker = findWorkerRunningTask(taskId); if (zkWorker == null) { log.info("Can't shutdown! No worker running task %s", taskId); return; } try { final URL url = makeWorkerURL(zkWorker.getWorker(), String.format("/task/%s/shutdown", taskId)); final StatusResponseHolder response = httpClient.post(url) .go(RESPONSE_HANDLER) .get(); log.info( "Sent shutdown message to worker: %s, status %s, response: %s", zkWorker.getWorker().getHost(), response.getStatus(), response.getContent() ); if (!response.getStatus().equals(HttpResponseStatus.ACCEPTED)) { <START> throw new ISE("Shutdown failed"); <END> } } catch (Exception e) { throw Throwables.propagate(e); } }</code><technical_language>Is throwing exception communicate shutdown succeed? I completely understand a shutdown fail, a normal thing</technical_language>

Target:
public void shutdown(String taskId) { if (pendingTasks.containsKey(taskId)) { pendingTasks.remove(taskId); return; } final ZkWorker zkWorker = findWorkerRunningTask(taskId); if (zkWorker == null) { log.info("Can't shutdown! No worker running task %s", taskId); return; } try { final URL url = makeWorkerURL(zkWorker.getWorker(), String.format("/task/%s/shutdown", taskId)); final StatusResponseHolder response = httpClient.post(url) .go(RESPONSE_HANDLER) .get(); log.info( "Sent shutdown message to worker: %s, status %s, response: %s", zkWorker.getWorker().getHost(), response.getStatus(), response.getContent() ); if (!response.getStatus().equals(HttpResponseStatus.ACCEPTED)) { log.error("Shutdown failed for %s! Are you sure the task was running?", taskId); } } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
<code>public String formHeronExecCommand(String[] inStringArray) { StringBuilder builder = new StringBuilder(); for (String string : inStringArray) { if (builder.length() > 0) { builder.append(" "); } builder.append(string); } <START> String stringToReturn = builder.toString(); <END> return stringToReturn; }</code><technical_language>return builder.toString();</technical_language>

Target:
private String formHeronExecCommand(String[] inStringArray) { StringBuilder builder = new StringBuilder(); for (String string : inStringArray) { if (builder.length() > 0) { builder.append(" "); } builder.append(string); } builder.append(" "); builder.append(EcsContext.AmiInstanceUrl(config)); String stringToReturn = builder.toString(); return stringToReturn; }
Source:
<code>public Map<String, Boolean> getModePreview() { return singletonMap("preview", <START> Boolean.parseBoolean(System.getProperty("crafter.modePreview", Boolean.FALSE.toString()))); <END> }</code><technical_language>need get property System, property is in server-config.properties, inject property in class (${crafter.engine.preview})</technical_language>

Target:
public Map<String, Boolean> getModePreview() { return singletonMap("preview", modePreview); }
Source:
<code>private IncomingPhoneNumber findSingleNumber(String number, Sid sourceOrganizationSid, Sid destinationOrganizationSid) { IncomingPhoneNumber matchedNumber = null; IncomingPhoneNumberFilter.Builder filterBuilder = IncomingPhoneNumberFilter.Builder.builder(); filterBuilder.byPhoneNumber(number); if (destinationOrganizationSid != null) { filterBuilder.byOrgSid(destinationOrganizationSid.toString()); } <START> if (sourceOrganizationSid!= null && <END> !sourceOrganizationSid.equals(destinationOrganizationSid)) { filterBuilder.byPureSIP(Boolean.FALSE); } IncomingPhoneNumberFilter numFilter = filterBuilder.build(); if (logger.isDebugEnabled()) { logger.debug("Searching with filter:" + numFilter); } List<IncomingPhoneNumber> matchedNumbers = numbersDao.getIncomingPhoneNumbersByFilter(numFilter); if (logger.isDebugEnabled()) { logger.debug("Num of results:" + matchedNumbers.size()); } if (matchedNumbers != null && matchedNumbers.size() > 0) { if (logger.isDebugEnabled()) { logger.debug("Matched number with filter:" + matchedNumbers.get(0)); } matchedNumber = matchedNumbers.get(0); } return matchedNumber; }</code><technical_language>@jaimecasero elaborate reason this rule? Is it? Client XYZ belongs Org A dial +123456789 belongs Org B? allow calling sip numbers Organizations number matched pureSip</technical_language>

Target:
private IncomingPhoneNumber findSingleNumber(String number, Sid sourceOrganizationSid, Sid destinationOrganizationSid) { IncomingPhoneNumber matchedNumber = null; IncomingPhoneNumberFilter.Builder filterBuilder = IncomingPhoneNumberFilter.Builder.builder(); filterBuilder.byPhoneNumber(number); if (destinationOrganizationSid != null) { filterBuilder.byOrgSid(destinationOrganizationSid.toString()); } if (sourceOrganizationSid == null || destinationOrganizationSid == null) { filterBuilder.byPureSIP(Boolean.FALSE); } if (sourceOrganizationSid != null && !sourceOrganizationSid.equals(destinationOrganizationSid)) { filterBuilder.byPureSIP(Boolean.FALSE); } IncomingPhoneNumberFilter numFilter = filterBuilder.build(); if (logger.isDebugEnabled()) { logger.debug("Searching with filter:" + numFilter); } List<IncomingPhoneNumber> matchedNumbers = numbersDao.getIncomingPhoneNumbersByFilter(numFilter); if (logger.isDebugEnabled()) { logger.debug("Num of results:" + matchedNumbers.size()); } if (matchedNumbers != null && matchedNumbers.size() > 0) { if (logger.isDebugEnabled()) { logger.debug("Matched number with filter:" + matchedNumbers.get(0)); } matchedNumber = matchedNumbers.get(0); } return matchedNumber; }
Source:
<code>public SpatialJoinOperatorFactory( int operatorId, PlanNodeId planNodeId, JoinNode.Type joinType, List<Type> probeTypes, List<Integer> probeOutputChannels, int probeGeometryChannel, PagesSpatialIndexFactory pagesSpatialIndexFactory) { <START> checkArgument(joinType == INNER || joinType == LEFT); <END> this.operatorId = operatorId; this.planNodeId = planNodeId; this.joinType = joinType; this.probeTypes = ImmutableList.copyOf(probeTypes); this.probeOutputTypes = probeOutputChannels.stream() .map(probeTypes::get) .collect(toImmutableList()); this.buildOutputTypes = pagesSpatialIndexFactory.getOutputTypes(); this.probeOutputChannels = ImmutableList.copyOf(probeOutputChannels); this.probeGeometryChannel = probeGeometryChannel; this.pagesSpatialIndexFactory = pagesSpatialIndexFactory; }</code><technical_language>Add a message including actual join type. helps a lot debugging. checkArgument(joinType == || joinType == LEFT, "unsupported joint type: %s", joinType)</technical_language>

Target:
public SpatialJoinOperatorFactory( int operatorId, PlanNodeId planNodeId, JoinNode.Type joinType, List<Type> probeTypes, List<Integer> probeOutputChannels, int probeGeometryChannel, PagesSpatialIndexFactory pagesSpatialIndexFactory) { checkArgument(joinType == INNER || joinType == LEFT, "unsupported join type: %s", joinType); this.operatorId = operatorId; this.planNodeId = planNodeId; this.joinType = joinType; this.probeTypes = ImmutableList.copyOf(probeTypes); this.probeOutputTypes = probeOutputChannels.stream() .map(probeTypes::get) .collect(toImmutableList()); this.buildOutputTypes = pagesSpatialIndexFactory.getOutputTypes(); this.probeOutputChannels = ImmutableList.copyOf(probeOutputChannels); this.probeGeometryChannel = probeGeometryChannel; this.pagesSpatialIndexFactory = pagesSpatialIndexFactory; }
Source:
<code>protected Guid getQuotaId() { <START> if (getNewDisk() != null && (isInternalManagedDisk())) { <END> return ((DiskImage) getNewDisk()).getQuotaId(); } return null; }</code><technical_language>please remove redundant brackets (isInter...)</technical_language>

Target:
protected Guid getQuotaId() { if (getNewDisk() != null && isInternalManagedDisk()) { return ((DiskImage) getNewDisk()).getQuotaId(); } return null; }
Source:
<code>public void testDefaultSettings() { ActivityLogEntry.Builder builder = new ActivityLogEntry.Builder("instructorHome", "URL", 10); String logMessage = "TEAMMATESLOG|||instructorHome|||instructorHome|||true|||Unknown|||Unknown|||Unknown" <START> + "|||Unknown|||Unknown|||URL"; <END> AssertHelper.assertLogMessageEquals(logMessage, builder.build().generateLogMessage()); }</code><technical_language>Align '+' start of string in line 18</technical_language>

Target:
public void testDefaultSettings() { Builder builder = new Builder("instructorHome", "URL", 10); String logMessage = "TEAMMATESLOG|||instructorHome|||instructorHome|||true|||Unknown|||Unknown|||Unknown" + "|||Unknown|||Unknown|||URL"; AssertHelper.assertLogMessageEquals(logMessage, builder.build().generateLogMessage()); }
Source:
<code>public MigratableTableTranslation<DBOOrganization, DBOOrganization> getTranslator() { <START> return new BasicMigratableTableTranslation<DBOOrganization>(); <END> }</code><technical_language>extracted a constant</technical_language>

Target:
public MigratableTableTranslation<DBOOrganization, DBOOrganization> getTranslator() { return TRANSLATOR; }
Source:
<code>public int resetAt(int seq) { int delta = Vp8Utils.getExtendedPictureIdDelta(seq, highestSeqNumReceived); if (delta < 0) { roc++; <START> highestSeqNumReceived = seq; <END> } return getIndex(seq, true); }</code><technical_language>this happen delta >= 0</technical_language>

Target:
public void resetAt(int seq) { int delta = Vp8Utils.getExtendedPictureIdDelta(seq, highestSeqNumReceived); if (delta < 0) { roc++; highestSeqNumReceived = seq; } getIndex(seq, true); }
Source:
<code><START> default Either<Seq<? extends E>, T> toEither() { <END> return isValid() ? Either.right(get()) : Either.left(getErrors()); }</code><technical_language>Here, java default Either<Seq<E>, T> toEither()</technical_language>

Target:
default Either<Seq<E>, T> toEither() { return isValid() ? Either.right(get()) : Either.left(getErrors()); }
Source:
<code>AcquireTokenInteractiveRequest(final Context context, final AuthenticationRequest authRequest, final TokenCacheAccessor tokenCacheAccessor) { mContext = context; mTokenCacheAccessor = tokenCacheAccessor; mAuthRequest = authRequest; if (mTokenCacheAccessor != null) { <START> mTokenCacheAccessor.setAuthRequest(authRequest); <END> } }</code><technical_language>ah? token cache accessor needs auth request? #Closed</technical_language>

Target:
AcquireTokenInteractiveRequest(final Context context, final AuthenticationRequest authRequest, final TokenCacheAccessor tokenCacheAccessor) { mContext = context; mTokenCacheAccessor = tokenCacheAccessor; mAuthRequest = authRequest; }
Source:
<code>private void startForegroundService() { <START> startForeground(1, NotificationHelpers.getNotification(this)); <END> }</code><technical_language>I sense put notification id a constant</technical_language>

Target:
private void startForegroundService() { startForeground(NotificationHelpers.APPIUM_NOTIFICATION_IDENTIFIER, NotificationHelpers.getNotification(this)); }
Source:
<code>public void testValidTimeRange() throws Exception { <START> String args = {"--deleteall", "--starttime", "1" , "--endtime", "10"}; <END> runIndexTool(args, 0); Assert.assertEquals(5, countRowsInIndex()); }</code><technical_language>Nice set of tests @swaroopak! Is error-case test starttime > endtime</technical_language>

Target:
public void testValidTimeRange() throws Exception { String args = {"--deleteall", "--starttime", "1" , "--endtime", "9"}; runIndexTool(args, 0); Assert.assertEquals(5, countRowsInIndex()); }
Source:
<code>public static String removeNewLine(String hash) { <START> if (hash != null && hash.contains("\n")) { <END> return hash.substring(0, hash.lastIndexOf("\n")); } return hash; }</code><technical_language>do hash.endsWith("\n") target trailing newline</technical_language>

Target:
public static String removeNewLine(String hash) { if (hash != null && hash.endsWith("\n")) { return hash.substring(0, hash.lastIndexOf("\n")); } return hash; }
Source:
<code>public User createAccountWithHashedPassword(String userName, String hashedPassword) throws IOException { <START> if (!hashedPassword.startsWith(JBCRYPT_HEADER)) { <END> throw new IllegalArgumentException("Hashed passwords must start with: "+ JBCRYPT_HEADER); } User user = User.getById(userName, true); user.addProperty(Details.fromHashedPassword(hashedPassword)); return user; }</code><technical_language>I this method duplicated string. check is needed a minimum isPasswordHashed() method</technical_language>

Target:
public User createAccountWithHashedPassword(String userName, String hashedPassword) throws IOException { if (!PASSWORD_ENCODER.isPasswordHashed(hashedPassword)) { throw new IllegalArgumentException("this method should only be called with a pre-hashed password"); } User user = User.getById(userName, true); user.addProperty(Details.fromHashedPassword(hashedPassword)); return user; }
Source:
<code>public SentimentSample(String sentiment, String[] sentence, boolean clearAdaptiveData) { <START> if (sentiment == null) { <END> throw new IllegalArgumentException("sentiment must not be null"); } if (sentence == null) { throw new IllegalArgumentException("sentence must not be null"); } this.sentiment = sentiment; this.sentence = Collections .unmodifiableList(new ArrayList<String>(Arrays.asList(sentence))); this.isClearAdaptiveData = clearAdaptiveData; }</code><technical_language>Objects.requireNotNull</technical_language>

Target:
public SentimentSample(String sentiment, String[] sentence, boolean clearAdaptiveData) { this.sentiment = Objects.requireNonNull(sentiment, "sentiment must not be null"); Objects.requireNonNull(sentence, "sentence must not be null"); this.sentence = Collections.unmodifiableList(Arrays.asList(sentence)); this.isClearAdaptiveData = clearAdaptiveData; }
Source:
<code>public byte[] toBytes(Schema toSchema, Object o) { if (toSchema != null && toSchema.getType() == Type.UNION) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); org.apache.avro.io.BinaryEncoder avroEncoder = EncoderFactory.get().binaryEncoder(baos, null); int unionIndex = 0; try { if (o == null) { unionIndex = firstNullSchemaTypeIndex(toSchema); avroEncoder.writeIndex(unionIndex); avroEncoder.writeNull(); } else { unionIndex = firstNotNullSchemaTypeIndex(toSchema); avroEncoder.writeIndex(unionIndex); avroEncoder.writeBytes(toBytes(o)); } avroEncoder.flush(); return baos.toByteArray(); } catch (IOException e) { return toBytes(o); <START> } <END> } else { return toBytes(o); } }</code><technical_language>printing exception here? I print out a message wrong, I missing anything? good @lewismc ! Thanks</technical_language>

Target:
public byte[] toBytes(Schema toSchema, Object o) { if (toSchema != null && toSchema.getType() == Type.UNION) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); org.apache.avro.io.BinaryEncoder avroEncoder = EncoderFactory.get().binaryEncoder(baos, null); int unionIndex = 0; try { if (o == null) { unionIndex = firstNullSchemaTypeIndex(toSchema); avroEncoder.writeIndex(unionIndex); avroEncoder.writeNull(); } else { unionIndex = firstNotNullSchemaTypeIndex(toSchema); avroEncoder.writeIndex(unionIndex); avroEncoder.writeBytes(toBytes(o)); } avroEncoder.flush(); return baos.toByteArray(); } catch (IOException e) { LOG.error(e.getMessage()); return toBytes(o); } } else { return toBytes(o); } }
Source:
<code>protected ClearcutClient(String url) { boolean isExternalUser = !isInternalUser(); if <START> (isExternalUser) { <END> mLogSource = EXTERNAL_LOG_SOURCE; } else { mLogSource = INTERNAL_LOG_SOURCE; } if (url == null) { mUrl = CLEARCUT_PROD_URL; } else { mUrl = url; } mRunId = UUID.randomUUID().toString(); if (isExternalUser) { mUserType = UserType.EXTERNAL; } else { mUserType = UserType.GOOGLE; } mExternalEventQueue = new ArrayList<>(); mDisabled = isClearcutDisabled(); if (mDisabled) { return; } System.out.println(NoticeMessageUtil.getNoticeMessage(mUserType)); mExecutor = new ScheduledThreadPoolExecutor(1); Runnable command = new Runnable() { @Override public void run() { flushEvents(); } }; mExecutor.scheduleAtFixedRate( command, SCHEDULER_INITIAL_DELAY_SECONDS, SCHEDULER_PERDIOC_SECONDS, TimeUnit.SECONDS); }</code><technical_language>if isInternalUser() create another variable isExternalUser better</technical_language>

Target:
protected ClearcutClient(String url) { if (isInternalUser()) { mLogSource = INTERNAL_LOG_SOURCE; mUserType = UserType.GOOGLE; } else { mLogSource = EXTERNAL_LOG_SOURCE; mUserType = UserType.EXTERNAL; } if (url == null) { mUrl = CLEARCUT_PROD_URL; } else { mUrl = url; } mRunId = UUID.randomUUID().toString(); mExternalEventQueue = new ArrayList<>(); mDisabled = isClearcutDisabled(); if (mDisabled) { return; } System.out.println(NoticeMessageUtil.getNoticeMessage(mUserType)); mExecutor = new ScheduledThreadPoolExecutor(1); Runnable command = new Runnable() { @Override public void run() { flushEvents(); } }; mExecutor.scheduleAtFixedRate( command, SCHEDULER_INITIAL_DELAY_SECONDS, SCHEDULER_PERDIOC_SECONDS, TimeUnit.SECONDS); }
Source:
<code>public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MODE_ARCHIVE, 0, Localization.get("menu.archive")).setIcon(android.R.drawable.ic_menu_upload); <START> menu.add(0, MODE_SMS, 1, Localization.get("menu.sms")).setIcon(android.R.drawable.ic_menu_upload); <END> return true; }</code><technical_language>icon is set is archive menu entry above. This is relevant Android 2 devices, is worth choosing other ic_menu_upload. stat_notify_chat ![image](<LINK_0> else <LINK_1></technical_language>

Target:
public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MODE_ARCHIVE, 0, Localization.get("menu.archive")).setIcon(android.R.drawable.ic_menu_upload); menu.add(0, MODE_SMS, 1, Localization.get("menu.sms")).setIcon(android.R.drawable.stat_notify_chat); return true; }
Source:
<code>public IntegrationFlow lines() { return f -> f.enrichHeaders(h -> h.headerExpression( <START> FileHeaders.FILENAME, "payload.substring(1, 4) + '.txt'", true)) <END> .handle(Files.outboundAdapter("'/tmp/out'") .appendNewLine(true) .fileExistsMode(FileExistsMode.APPEND_NO_FLUSH), e -> e.id("fileOut")); }</code><technical_language>WDYT, if change this .enrichHeaders() .fileNameExpression("payload.substring(1, 4) + '.txt'")? work test somehow... I in debug proper expression expected file name result</technical_language>

Target:
public IntegrationFlow lines() { return f -> f.handle(fileOut()); }
Source:
<code>private boolean updateLeaseInfoIfNeeded() { boolean updateLeaseInfo = false; Guid SnapshotLeaseDomainId = null; if (isLeaseInfoUpdateNeeded(activeBeforeSnapshotLeaseDomainId, previewedSnapshotLeaseDomainId)) { updateLeaseInfo = true; SnapshotLeaseDomainId = getParameters().getSnapshotAction() == SnapshotActionEnum.UNDO ? activeBeforeSnapshotLeaseDomainId : previewedSnapshotLeaseDomainId; } else if (getParameters().getSnapshotAction() == SnapshotActionEnum.RESTORE_STATELESS && previewedSnapshotLeaseDomainId != null) { updateLeaseInfo = true; SnapshotLeaseDomainId = activeBeforeSnapshotLeaseDomainId; } <START> return !updateLeaseInfo || updateLeaseInfo(SnapshotLeaseDomainId); <END> }</code><technical_language>similarly, add additional logic isLeaseInfoUpdateNeeded</technical_language>

Target:
private boolean updateLeaseInfoIfNeeded() { if (isLeaseInfoUpdateNeeded(activeBeforeSnapshotLeaseDomainId, previewedSnapshotLeaseDomainId)) { Guid snapshotLeaseDomainId = getParameters().getSnapshotAction() != SnapshotActionEnum.COMMIT ? activeBeforeSnapshotLeaseDomainId : previewedSnapshotLeaseDomainId; return updateLeaseInfo(snapshotLeaseDomainId); } return true; }
Source:
<code>private String fieldTypeUnwrapped() { if (fieldDMNType.isCollection()) { <START> String typeName = index.asJava(fieldDMNType.getBaseType()); <END> return typeName; } throw new IllegalArgumentException(); }</code><technical_language>1) inline statement 2) split significant statements (index.asJava fieldDMNType.getBaseType)</technical_language>

Target:
private String fieldTypeUnwrapped() { if (fieldDMNType.isCollection()) { return index.asJava(fieldDMNType.getBaseType()); } throw new IllegalArgumentException(); }
Source:
<code>public void deliverMessages() { delivering = true; for (Tuple group : queue.keySet()) { DefaultMailbox mailbox = queue.get(group); Map<Tuple, Integer> contents = mailbox.getQueue(); List<Tuple> keys = new ArrayList<Tuple>(contents.keySet()); int i = 0; boolean monotoneChange; while (i < keys.size()) { monotoneChange = false; Tuple current = keys.get(i); int currentCount = contents.get(current); <START> Tuple next = (i + 1 < keys.size()) ? keys.get(i + 1) : null; <END> if (next != null) { int nextCount = contents.get(next); if (currentCount == -1 && nextCount == 1) { Tuple currentComputed = receiver.getPosetMask().transform(current); Tuple nextComputed = receiver.getPosetMask().transform(next); monotoneChange = receiver.getPosetComparator().isLessOrEqual(currentComputed, nextComputed); } } if (monotoneChange) { assert next != null; receiver.update(Direction.REVOKE, current, true); receiver.update(Direction.INSERT, next, true); i += 2; } else { Direction direction = currentCount < 0 ? Direction.REVOKE : Direction.INSERT; for (int j = 0; j < Math.abs(currentCount); j++) { receiver.update(direction, current); } i++; } } } delivering = false; Map<Tuple, DefaultMailbox> tmp = queue; queue = buffer; buffer = tmp; buffer.clear(); }</code><technical_language>work if is deletion insertion group, is general... in case, I assumption deletion iterated first.</technical_language>

Target:
public void deliverMessages() { delivering = true; for (Tuple group : queue.keySet()) { DefaultMailbox mailbox = queue.get(group); Map<Tuple, Integer> contents = mailbox.getQueue(); List<Tuple> keys = new ArrayList<Tuple>(contents.keySet()); int i = 0; boolean monotoneChange; while (i < keys.size()) { monotoneChange = false; Tuple current = keys.get(i); int currentCount = contents.get(current); Tuple next = (i + 1 < keys.size()) ? keys.get(i + 1) : null; if (next != null) { int nextCount = contents.get(next); if (currentCount < 0 && nextCount > 0 && -currentCount == nextCount) { Tuple currentComputed = receiver.getPosetMask().transform(current); Tuple nextComputed = receiver.getPosetMask().transform(next); monotoneChange = receiver.getPosetComparator().isLessOrEqual(currentComputed, nextComputed); } } if (monotoneChange) { assert next != null; for (int j = 0; j < -currentCount; j++) { receiver.update(Direction.REVOKE, current, true); } for (int j = 0; j < -currentCount; j++) { receiver.update(Direction.INSERT, next, true); } i += 2; } else { Direction direction = currentCount < 0 ? Direction.REVOKE : Direction.INSERT; for (int j = 0; j < Math.abs(currentCount); j++) { receiver.update(direction, current); } i++; } } } delivering = false; Map<Tuple, DefaultMailbox> tmp = queue; queue = buffer; buffer = tmp; buffer.clear(); }