Java Code Examples for java.util.ArrayDeque#getLast()

The following examples show how to use java.util.ArrayDeque#getLast() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Solution5.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public int[] maxSlidingWindow(int[] nums, int k) {
    int len = nums.length;
    if (len == 0) {
        return new int[0];
    }
    int[] res = new int[len - k + 1];
    ArrayDeque<Integer> queue = new ArrayDeque<>(len);
    for (int i = 0; i < len; i++) {
        // 左边界滑出
        if (i >= k && queue.getFirst() == i - k) {
            queue.removeFirst();
        }

        // 在 nums[i] 加入之前考虑把不可能的值弹出
        while (!queue.isEmpty() && nums[queue.getLast()] <= nums[i]) {
            queue.removeLast();
        }

        queue.add(i);
        // 记录结果
        if (i >= k - 1) {
            res[i - k + 1] = nums[queue.getFirst()];
        }
    }
    return res;
}
 
Example 2
Source File: LuBottomMenu.java    From RichEditorView with Apache License 2.0 5 votes vote down vote up
/**
 * @param pathRecord 点击的展开路径记录
 *                   通过路径直接恢复视图序列
 */
private void restoreAllInfo(ArrayDeque<MenuItem> pathRecord) {
    mPathRecord.clear();
    while (!pathRecord.isEmpty()) {
        mCurMenuItem = pathRecord.getLast();
        addOneLevel();
        pathRecord.removeLast();
    }

}
 
Example 3
Source File: LinkageCheckTask.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
private void recordDependencyPaths(
    ImmutableListMultimap.Builder<String, String> output,
    ArrayDeque<ResolvedComponentResult> stack,
    ImmutableSet<String> targetCoordinates) {
  ResolvedComponentResult item = stack.getLast();
  ModuleVersionIdentifier identifier = item.getModuleVersion();
  String coordinates =
      String.format(
          "%s:%s:%s", identifier.getGroup(), identifier.getName(), identifier.getVersion());
  if (targetCoordinates.contains(coordinates)) {
    String dependencyPath =
        stack.stream().map(this::formatComponentResult).collect(Collectors.joining(" / "));
    output.put(coordinates, dependencyPath);
  }

  for (DependencyResult dependencyResult : item.getDependencies()) {
    if (dependencyResult instanceof ResolvedDependencyResult) {
      ResolvedDependencyResult resolvedDependencyResult =
          (ResolvedDependencyResult) dependencyResult;
      ResolvedComponentResult child = resolvedDependencyResult.getSelected();
      stack.add(child);
      recordDependencyPaths(output, stack, targetCoordinates);
    } else if (dependencyResult instanceof UnresolvedDependencyResult) {
      UnresolvedDependencyResult unresolvedResult = (UnresolvedDependencyResult) dependencyResult;
      getLogger()
          .error(
              "Could not resolve dependency: "
                  + unresolvedResult.getAttempted().getDisplayName());
    } else {
      throw new IllegalStateException("Unexpected dependency result type: " + dependencyResult);
    }
  }

  stack.removeLast();
}
 
Example 4
Source File: ArrayDequeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * getLast() returns last element, or throws NSEE if empty
 */
public void testLastElement() {
    ArrayDeque q = populatedDeque(SIZE);
    for (int i = SIZE - 1; i >= 0; --i) {
        assertEquals(i, q.getLast());
        assertEquals(i, q.pollLast());
    }
    try {
        q.getLast();
        shouldThrow();
    } catch (NoSuchElementException success) {}
    assertNull(q.peekLast());
}
 
Example 5
Source File: ArrayDequeTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * getLast() returns last element, or throws NSEE if empty
 */
public void testLastElement() {
    ArrayDeque q = populatedDeque(SIZE);
    for (int i = SIZE - 1; i >= 0; --i) {
        assertEquals(i, q.getLast());
        assertEquals(i, q.pollLast());
    }
    try {
        q.getLast();
        shouldThrow();
    } catch (NoSuchElementException success) {}
    assertNull(q.peekLast());
}
 
Example 6
Source File: RMQSourceTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
@Test
public void testCheckpointing() throws Exception {
	source.autoAck = false;

	StreamSource<String, RMQSource<String>> src = new StreamSource<>(source);
	AbstractStreamOperatorTestHarness<String> testHarness =
		new AbstractStreamOperatorTestHarness<>(src, 1, 1, 0);
	testHarness.open();

	sourceThread.start();

	Thread.sleep(5);

	final Random random = new Random(System.currentTimeMillis());
	int numSnapshots = 50;
	long previousSnapshotId;
	long lastSnapshotId = 0;

	long totalNumberOfAcks = 0;

	for (int i = 0; i < numSnapshots; i++) {
		long snapshotId = random.nextLong();
		OperatorSubtaskState data;

		synchronized (DummySourceContext.lock) {
			data = testHarness.snapshot(snapshotId, System.currentTimeMillis());
			previousSnapshotId = lastSnapshotId;
			lastSnapshotId = messageId;
		}
		// let some time pass
		Thread.sleep(5);

		// check if the correct number of messages have been snapshotted
		final long numIds = lastSnapshotId - previousSnapshotId;

		RMQTestSource sourceCopy = new RMQTestSource();
		StreamSource<String, RMQTestSource> srcCopy = new StreamSource<>(sourceCopy);
		AbstractStreamOperatorTestHarness<String> testHarnessCopy =
			new AbstractStreamOperatorTestHarness<>(srcCopy, 1, 1, 0);

		testHarnessCopy.setup();
		testHarnessCopy.initializeState(data);
		testHarnessCopy.open();

		ArrayDeque<Tuple2<Long, Set<String>>> deque = sourceCopy.getRestoredState();
		Set<String> messageIds = deque.getLast().f1;

		assertEquals(numIds, messageIds.size());
		if (messageIds.size() > 0) {
			assertTrue(messageIds.contains(Long.toString(lastSnapshotId)));
		}

		// check if the messages are being acknowledged and the transaction committed
		synchronized (DummySourceContext.lock) {
			source.notifyCheckpointComplete(snapshotId);
		}
		totalNumberOfAcks += numIds;

	}

	Mockito.verify(source.channel, Mockito.times((int) totalNumberOfAcks)).basicAck(Mockito.anyLong(), Mockito.eq(false));
	Mockito.verify(source.channel, Mockito.times(numSnapshots)).txCommit();

}
 
Example 7
Source File: RMQSourceTest.java    From flink with Apache License 2.0 4 votes vote down vote up
@Test
public void testCheckpointing() throws Exception {
	source.autoAck = false;

	StreamSource<String, RMQSource<String>> src = new StreamSource<>(source);
	AbstractStreamOperatorTestHarness<String> testHarness =
		new AbstractStreamOperatorTestHarness<>(src, 1, 1, 0);
	testHarness.open();

	sourceThread.start();

	Thread.sleep(5);

	final Random random = new Random(System.currentTimeMillis());
	int numSnapshots = 50;
	long previousSnapshotId;
	long lastSnapshotId = 0;

	long totalNumberOfAcks = 0;

	for (int i = 0; i < numSnapshots; i++) {
		long snapshotId = random.nextLong();
		OperatorSubtaskState data;

		synchronized (DummySourceContext.lock) {
			data = testHarness.snapshot(snapshotId, System.currentTimeMillis());
			previousSnapshotId = lastSnapshotId;
			lastSnapshotId = messageId;
		}
		// let some time pass
		Thread.sleep(5);

		// check if the correct number of messages have been snapshotted
		final long numIds = lastSnapshotId - previousSnapshotId;

		RMQTestSource sourceCopy = new RMQTestSource();
		StreamSource<String, RMQTestSource> srcCopy = new StreamSource<>(sourceCopy);
		AbstractStreamOperatorTestHarness<String> testHarnessCopy =
			new AbstractStreamOperatorTestHarness<>(srcCopy, 1, 1, 0);

		testHarnessCopy.setup();
		testHarnessCopy.initializeState(data);
		testHarnessCopy.open();

		ArrayDeque<Tuple2<Long, Set<String>>> deque = sourceCopy.getRestoredState();
		Set<String> messageIds = deque.getLast().f1;

		assertEquals(numIds, messageIds.size());
		if (messageIds.size() > 0) {
			assertTrue(messageIds.contains(Long.toString(lastSnapshotId)));
		}

		// check if the messages are being acknowledged and the transaction committed
		synchronized (DummySourceContext.lock) {
			source.notifyCheckpointComplete(snapshotId);
		}
		totalNumberOfAcks += numIds;

	}

	Mockito.verify(source.channel, Mockito.times((int) totalNumberOfAcks)).basicAck(Mockito.anyLong(), Mockito.eq(false));
	Mockito.verify(source.channel, Mockito.times(numSnapshots)).txCommit();

}
 
Example 8
Source File: DefaultTableElementFactory.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
private void buildColumn(PresentationEnvironment env, TableColumnsElement columns, MetaResource resource, boolean filtersEnabled, boolean sortingEnabled,
		ArrayDeque<MetaAttribute> attributePath) {
	MetaAttribute lastAttribute = attributePath.getLast();
	MetaType type = lastAttribute.getType();
	if (type == null) {
		return; // TODO support e.g. from other services
	}

	if (isIgnored(attributePath, env) || type.isCollection()) {
		return;
	}

	String label = PresentationBuilderUtils.getLabel(attributePath);

	if (type instanceof MetaDataObject && !lastAttribute.isAssociation()) {
		for (MetaAttribute nestedAttribute : type.asDataObject().getAttributes()) {
			if (!attributePath.contains(nestedAttribute)) {
				ArrayDeque nestedPath = new ArrayDeque();
				nestedPath.addAll(attributePath);
				nestedPath.add(nestedAttribute);
				buildColumn(env, columns, resource, filtersEnabled, sortingEnabled, nestedPath);
			}
		}
	} else {
		PresentationEnvironment cellEnv = env.clone();
		cellEnv.setAttributePath(attributePath);
		cellEnv.setAcceptedTypes(Arrays.asList(PresentationType.CELL, PresentationType.DISPLAY));
		cellEnv.setType(type);

		PresentationElement cellElement = env.createElement(cellEnv);


		boolean sortable = sortingEnabled && lastAttribute.isSortable();
		PathSpec pathSpec = PathSpec.of(attributePath.stream().map(it -> it.getName()).collect(Collectors.toList()));

		//String valuePath =  PresentationBuilderUtils.getValuePath(attributePath);
		String id = pathSpec.toString(); //valuePath.join(valuePath, '.');

		TableColumnElement column = new TableColumnElement();
		column.setId(id);
		column.setComponentId("column");
		column.setLabel(label);
		column.setAttributePath(pathSpec);
		column.setEditable(env.isEditable());
		column.setComponent(cellElement);
		//column.setEditComponent();
		// column.setFilter
		column.setSortable(sortable);
		// column.setWidth
		// column.setTyleClass
		columns.add(column);
	}


}
 
Example 9
Source File: DefaultTableElementFactory.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
private boolean isIgnored(ArrayDeque<MetaAttribute> attributePath, PresentationEnvironment env) {
	MetaAttribute last = attributePath.getLast();
	return last.isVersion() || last instanceof MetaResourceField && !((MetaResourceField) last).getVersionRange().contains(env.getRequestVersion());
}
 
Example 10
Source File: DefaultFormFactory.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
private void buildElement(PresentationEnvironment env, FormElements elements, ArrayDeque<MetaAttribute> attributePath) {
	MetaAttribute lastAttribute = attributePath.getLast();
	MetaType type = lastAttribute.getType();
	if (isIgnored(attributePath, env)) {
		return;
	}

	String label = PresentationBuilderUtils.getLabel(attributePath);

	if (type instanceof MetaDataObject && !lastAttribute.isAssociation()) {
		for (MetaAttribute nestedAttribute : type.asDataObject().getAttributes()) {
			if (!attributePath.contains(nestedAttribute)) {
				ArrayDeque nestedPath = new ArrayDeque();
				nestedPath.addAll(attributePath);
				nestedPath.add(nestedAttribute);
				buildElement(env, elements, nestedPath);
			}
		}
	} else {
		PresentationEnvironment elementEnv = env.clone();
		elementEnv.setAttributePath(attributePath);
		elementEnv.setAcceptedTypes(Arrays.asList(PresentationType.FORM_ELEMENT, PresentationType.DISPLAY));
		elementEnv.setType(type);
		PresentationElement element = env.createElement(elementEnv);

		PathSpec pathSpec = PathSpec.of(attributePath.stream().map(it -> it.getName()).collect(Collectors.toList()));

		//String valuePath =  PresentationBuilderUtils.getValuePath(attributePath);
		String id = pathSpec.toString(); //valuePath.join(valuePath, '.');

		FormElement formElement = new FormElement();
		formElement.setId(id);
		formElement.setComponentId("form");
		formElement.setLabel(label);
		formElement.setAttributePath(pathSpec);
		formElement.setEditable(env.isEditable());
		formElement.setComponent(element);
		//column.setEditComponent();
		// column.setFilter
		// column.setWidth
		// column.setTyleClass
		elements.add(formElement);
	}
}
 
Example 11
Source File: DefaultFormFactory.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
private boolean isIgnored(ArrayDeque<MetaAttribute> attributePath, PresentationEnvironment env) {
	MetaAttribute last = attributePath.getLast();
	return last.isVersion() || last instanceof MetaResourceField && !((MetaResourceField) last).getVersionRange().contains(env.getRequestVersion());
}
 
Example 12
Source File: RMQSourceTest.java    From flink with Apache License 2.0 4 votes vote down vote up
@Test
public void testCheckpointing() throws Exception {
	source.autoAck = false;

	StreamSource<String, RMQSource<String>> src = new StreamSource<>(source);
	AbstractStreamOperatorTestHarness<String> testHarness =
		new AbstractStreamOperatorTestHarness<>(src, 1, 1, 0);
	testHarness.open();

	sourceThread.start();

	Thread.sleep(5);

	final Random random = new Random(System.currentTimeMillis());
	int numSnapshots = 50;
	long previousSnapshotId;
	long lastSnapshotId = 0;

	long totalNumberOfAcks = 0;

	for (int i = 0; i < numSnapshots; i++) {
		long snapshotId = random.nextLong();
		OperatorSubtaskState data;

		synchronized (DummySourceContext.lock) {
			data = testHarness.snapshot(snapshotId, System.currentTimeMillis());
			previousSnapshotId = lastSnapshotId;
			lastSnapshotId = messageId;
		}
		// let some time pass
		Thread.sleep(5);

		// check if the correct number of messages have been snapshotted
		final long numIds = lastSnapshotId - previousSnapshotId;

		RMQTestSource sourceCopy = new RMQTestSource();
		StreamSource<String, RMQTestSource> srcCopy = new StreamSource<>(sourceCopy);
		AbstractStreamOperatorTestHarness<String> testHarnessCopy =
			new AbstractStreamOperatorTestHarness<>(srcCopy, 1, 1, 0);

		testHarnessCopy.setup();
		testHarnessCopy.initializeState(data);
		testHarnessCopy.open();

		ArrayDeque<Tuple2<Long, Set<String>>> deque = sourceCopy.getRestoredState();
		Set<String> messageIds = deque.getLast().f1;

		assertEquals(numIds, messageIds.size());
		if (messageIds.size() > 0) {
			assertTrue(messageIds.contains(Long.toString(lastSnapshotId)));
		}

		// check if the messages are being acknowledged and the transaction committed
		synchronized (DummySourceContext.lock) {
			source.notifyCheckpointComplete(snapshotId);
		}
		totalNumberOfAcks += numIds;

	}

	Mockito.verify(source.channel, Mockito.times((int) totalNumberOfAcks)).basicAck(Mockito.anyLong(), Mockito.eq(false));
	Mockito.verify(source.channel, Mockito.times(numSnapshots)).txCommit();

}