Java Code Examples for java.util.Collections#nCopies()

The following examples show how to use java.util.Collections#nCopies() . 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: DeploymentManagementTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("An assignment request is not accepted if it would lead to a target exceeding the max actions per target quota.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
        @Expect(type = DistributionSetCreatedEvent.class, count = 1),
        @Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
        @Expect(type = TargetAssignDistributionSetEvent.class, count = 0) })
public void maxActionsPerTargetIsCheckedBeforeAssignmentExecution() {
    final int maxActions = quotaManagement.getMaxActionsPerTarget();
    final String controllerId = testdataFactory.createTarget().getControllerId();
    final Long dsId = testdataFactory.createDistributionSet().getId();

    final List<DeploymentRequest> deploymentRequests = Collections.nCopies(maxActions + 1,
            DeploymentManagement.deploymentRequest(controllerId, dsId).setWeight(24).build());

    enableMultiAssignments();
    Assertions.assertThatExceptionOfType(AssignmentQuotaExceededException.class)
            .isThrownBy(() -> deploymentManagement.assignDistributionSets(deploymentRequests));
    assertThat(actionRepository.countByTargetControllerId(controllerId)).isEqualTo(0);
}
 
Example 2
Source File: DefaultNodeFactory.java    From besu with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Node<V> createBranch(
    final byte leftIndex, final Node<V> left, final byte rightIndex, final Node<V> right) {
  assert (leftIndex <= BranchNode.RADIX);
  assert (rightIndex <= BranchNode.RADIX);
  assert (leftIndex != rightIndex);

  final ArrayList<Node<V>> children =
      new ArrayList<>(Collections.nCopies(BranchNode.RADIX, (Node<V>) NULL_NODE));
  if (leftIndex == BranchNode.RADIX) {
    children.set(rightIndex, right);
    return createBranch(children, left.getValue());
  } else if (rightIndex == BranchNode.RADIX) {
    children.set(leftIndex, left);
    return createBranch(children, right.getValue());
  } else {
    children.set(leftIndex, left);
    children.set(rightIndex, right);
    return createBranch(children, Optional.empty());
  }
}
 
Example 3
Source File: TestLinearModel.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void getInstanceTest() {
  final Map<String,Object> weights = new HashMap<>();
  weights.put("constant1", 1d);
  weights.put("constant5", 1d);

  Map<String,Object> params = new HashMap<String,Object>();
  final List<Feature> features = getFeatures(new String[] {
      "constant1", "constant5"});
  final List<Normalizer> norms =
      new ArrayList<Normalizer>(
          Collections.nCopies(features.size(),IdentityNormalizer.INSTANCE));
  params.put("weights", weights);
  final LTRScoringModel ltrScoringModel = createLinearModel("test1",
      features, norms, "test", fstore.getFeatures(),
      params);

  store.addModel(ltrScoringModel);
  final LTRScoringModel m = store.getModel("test1");
  assertEquals(ltrScoringModel, m);
}
 
Example 4
Source File: StepsProfiles.java    From PaySim with GNU General Public License v3.0 5 votes vote down vote up
public StepsProfiles(String filename, double multiplier, int nbSteps) {
    ArrayList<String[]> parameters = CSVReader.read(filename);

    profilePerStep = new ArrayList<>();
    for (int i = 0; i < nbSteps; i++) {
        profilePerStep.add(new HashMap<>());
    }

    stepTargetCount = new ArrayList<>(Collections.nCopies(nbSteps, 0));

    for (String[] line : parameters) {
        if (ActionTypes.isValidAction(line[COLUMN_ACTION])) {
            int step = Integer.parseInt(line[COLUMN_STEP]);
            int count = Integer.parseInt(line[COLUMN_COUNT]);

            if (step < nbSteps) {
                StepActionProfile actionProfile = new StepActionProfile(step,
                        line[COLUMN_ACTION],
                        Integer.parseInt(line[COLUMN_MONTH]),
                        Integer.parseInt(line[COLUMN_DAY]),
                        Integer.parseInt(line[COLUMN_HOUR]),
                        count,
                        Double.parseDouble(line[COLUMN_SUM]),
                        Double.parseDouble(line[COLUMN_AVERAGE]),
                        Double.parseDouble(line[COLUMN_STD]));

                profilePerStep.get(step).put(line[COLUMN_ACTION], actionProfile);
                stepTargetCount.set(step, stepTargetCount.get(step) + count);
            }
        }
    }


    computeProbabilitiesPerStep();
    modifyWithMultiplier(multiplier);
}
 
Example 5
Source File: CsvBuilder.java    From topic-modeling-tool with Eclipse Public License 2.0 5 votes vote down vote up
private ArrayList<String> topicRowCells(String[] inCells) {
    ArrayList<String> outCells =
        new ArrayList<String>(Collections.nCopies(numTopics, "0.0"));
    int topic;
    for (int i = 2; i < inCells.length - 1; i = i + 2) {
        topic = Integer.parseInt(inCells[i]);
        outCells.set(topic, inCells[i + 1]);
    }
    return outCells;
}
 
Example 6
Source File: CrossSpliteratorTest.java    From streamex with Apache License 2.0 5 votes vote down vote up
@Test
public void testCrossReduce() {
    for (int limit : new int[] { 1, 2, 4, 9 }) {
        List<List<Integer>> input = Collections.nCopies(3, IntStreamEx.range(limit).boxed().toList());
        List<String> expected = IntStreamEx.range(limit * limit * limit).mapToObj(
            i -> "" + (i / limit / limit) + (i / limit % limit) + (i % limit)).toList();
        checkSpliterator("cross", expected, () -> new CrossSpliterator.Reducing<>(input, "", (s, b) -> s + b));
    }
}
 
Example 7
Source File: ParameterizedStateUnitTest.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testUpdateSubstateParameterAndCopyState() {
    final Substate substate = new Substate(Collections.nCopies(10, 1.));
    final Substate newSubstate = new Substate(Collections.nCopies(10, 2.));
    final ParameterizedState<TestParameter> testStateWithSubstate =
            new ParameterizedState<>(Arrays.asList(new Parameter<>(TestParameter.PARAMETER_1, 1.), new Parameter<>(TestParameter.PARAMETER_2, substate)));
    final ParameterizedState<TestParameter> stateCopyBeforeUpdate = testStateWithSubstate.copy();
    testStateWithSubstate.update(TestParameter.PARAMETER_2, newSubstate);
    final ParameterizedState<TestParameter> stateCopyAfterUpdate = testStateWithSubstate.copy();
    double sumOfCopyBeforeUpdate = stateCopyBeforeUpdate.get(TestParameter.PARAMETER_2, Substate.class).stream().mapToDouble(Double::doubleValue).sum();
    double sumOfCopyAfterUpdate = stateCopyAfterUpdate.get(TestParameter.PARAMETER_2, Substate.class).stream().mapToDouble(Double::doubleValue).sum();
    Assert.assertEquals(sumOfCopyBeforeUpdate, 10.);
    Assert.assertEquals(sumOfCopyAfterUpdate, 20.);
}
 
Example 8
Source File: BigArityTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static MethodHandle MH_hashArguments(Class<? extends Object[]> arrayClass, int arity) {
    if (arrayClass == Object[].class)
        return MH_hashArguments(arity);
    ArrayList<Class<?>> ptypes = new ArrayList<>(Collections.<Class<?>>nCopies(arity, arrayClass.getComponentType()));
    MethodType mt = MethodType.methodType(Object.class, ptypes);
    return MH_hashArguments_VA.asType(mt);
}
 
Example 9
Source File: BenchmarkGroupByHash.java    From presto with Apache License 2.0 5 votes vote down vote up
@Setup
public void setup()
{
    pages = createBigintPages(POSITIONS, GROUP_COUNT, channelCount, hashEnabled);
    types = Collections.nCopies(1, BIGINT);
    channels = new int[1];
    for (int i = 0; i < 1; i++) {
        channels[i] = i;
    }
}
 
Example 10
Source File: BigArityTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
static MethodHandle MH_hashArguments(Class<? extends Object[]> arrayClass, int arity) {
    if (arrayClass == Object[].class)
        return MH_hashArguments(arity);
    ArrayList<Class<?>> ptypes = new ArrayList<>(Collections.<Class<?>>nCopies(arity, arrayClass.getComponentType()));
    MethodType mt = MethodType.methodType(Object.class, ptypes);
    return MH_hashArguments_VA.asType(mt);
}
 
Example 11
Source File: BigArityTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
static MethodHandle MH_hashArguments(Class<? extends Object[]> arrayClass, int arity) {
    if (arrayClass == Object[].class)
        return MH_hashArguments(arity);
    ArrayList<Class<?>> ptypes = new ArrayList<>(Collections.<Class<?>>nCopies(arity, arrayClass.getComponentType()));
    MethodType mt = MethodType.methodType(Object.class, ptypes);
    return MH_hashArguments_VA.asType(mt);
}
 
Example 12
Source File: Mutect2VariantFilter.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Converts the single probability calculated for the site to be the probability for each allele
 * @param vc
 * @param filteringEngine
 * @param referenceContext
 * @return
 */
@Override
public List<Double> errorProbabilities(final VariantContext vc, final Mutect2FilteringEngine filteringEngine, ReferenceContext referenceContext) {
    int numAltAlleles = vc.getNAlleles() - 1;
    final double result = Mutect2FilteringEngine.roundFinitePrecisionErrors(requiredInfoAnnotations().stream().allMatch(vc::hasAttribute) ?
            calculateErrorProbability(vc, filteringEngine, referenceContext) : 0.0);
    return Collections.nCopies(numAltAlleles, result);
}
 
Example 13
Source File: AbstractRuntimeObjectSchemaTest.java    From protostuff with Apache License 2.0 5 votes vote down vote up
PojoWithObjectCollectionNullKV fill()
{
    String v = null;

    singletonSetNullValue = Collections.singleton(v);
    singletonListNullValue = Collections.singletonList(v);
    copiesListNullValue = Collections.nCopies(10, v);

    return this;
}
 
Example 14
Source File: DefaultLogger.java    From das with Apache License 2.0 5 votes vote down vote up
private List<StackTraceElement> getDasClientCaller() {
	StackTraceElement[] callers = Thread.currentThread().getStackTrace();
	for (int i = callers.length -1 ; i >=0; i--) {
		if (callers[i].getClassName().equals(DasClient.class.getName())) {
			if (i + 1 < callers.length) {
				return Lists.newArrayList(callers[i + 1], callers[i]);
			}
		}
	}
	return Collections.nCopies(2, new StackTraceElement("N/A", "N/A", "N/A", -1));
}
 
Example 15
Source File: NumericIdStrategy.java    From protostuff with Apache License 2.0 4 votes vote down vote up
protected static <T> ArrayList<T> newList(int size)
{
    List<T> l = Collections.nCopies(size, null);
    return new ArrayList<T>(l);
}
 
Example 16
Source File: TaskManagerServices.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Creates and returns the task manager services.
 *
 * @param taskManagerServicesConfiguration task manager configuration
 * @param taskManagerMetricGroup metric group of the task manager
 * @param taskIOExecutor executor for async IO operations
 * @return task manager components
 * @throws Exception
 */
public static TaskManagerServices fromConfiguration(
		TaskManagerServicesConfiguration taskManagerServicesConfiguration,
		MetricGroup taskManagerMetricGroup,
		Executor taskIOExecutor) throws Exception {

	// pre-start checks
	checkTempDirs(taskManagerServicesConfiguration.getTmpDirPaths());

	final TaskEventDispatcher taskEventDispatcher = new TaskEventDispatcher();

	// start the I/O manager, it will create some temp directories.
	final IOManager ioManager = new IOManagerAsync(taskManagerServicesConfiguration.getTmpDirPaths());

	final ShuffleEnvironment<?, ?> shuffleEnvironment = createShuffleEnvironment(
		taskManagerServicesConfiguration,
		taskEventDispatcher,
		taskManagerMetricGroup);
	final int dataPort = shuffleEnvironment.start();

	final KvStateService kvStateService = KvStateService.fromConfiguration(taskManagerServicesConfiguration);
	kvStateService.start();

	final TaskManagerLocation taskManagerLocation = new TaskManagerLocation(
		taskManagerServicesConfiguration.getResourceID(),
		taskManagerServicesConfiguration.getTaskManagerAddress(),
		dataPort);

	// this call has to happen strictly after the network stack has been initialized
	final MemoryManager memoryManager = createMemoryManager(taskManagerServicesConfiguration);
	final long managedMemorySize = memoryManager.getMemorySize();

	final BroadcastVariableManager broadcastVariableManager = new BroadcastVariableManager();

	final int numOfSlots = taskManagerServicesConfiguration.getNumberOfSlots();
	final List<ResourceProfile> resourceProfiles =
		Collections.nCopies(numOfSlots, computeSlotResourceProfile(numOfSlots, managedMemorySize));

	final TimerService<AllocationID> timerService = new TimerService<>(
		new ScheduledThreadPoolExecutor(1),
		taskManagerServicesConfiguration.getTimerServiceShutdownTimeout());

	final TaskSlotTable taskSlotTable = new TaskSlotTable(resourceProfiles, timerService);

	final JobManagerTable jobManagerTable = new JobManagerTable();

	final JobLeaderService jobLeaderService = new JobLeaderService(taskManagerLocation, taskManagerServicesConfiguration.getRetryingRegistrationConfiguration());

	final String[] stateRootDirectoryStrings = taskManagerServicesConfiguration.getLocalRecoveryStateRootDirectories();

	final File[] stateRootDirectoryFiles = new File[stateRootDirectoryStrings.length];

	for (int i = 0; i < stateRootDirectoryStrings.length; ++i) {
		stateRootDirectoryFiles[i] = new File(stateRootDirectoryStrings[i], LOCAL_STATE_SUB_DIRECTORY_ROOT);
	}

	final TaskExecutorLocalStateStoresManager taskStateManager = new TaskExecutorLocalStateStoresManager(
		taskManagerServicesConfiguration.isLocalRecoveryEnabled(),
		stateRootDirectoryFiles,
		taskIOExecutor);

	return new TaskManagerServices(
		taskManagerLocation,
		memoryManager,
		ioManager,
		shuffleEnvironment,
		kvStateService,
		broadcastVariableManager,
		taskSlotTable,
		jobManagerTable,
		jobLeaderService,
		taskStateManager,
		taskEventDispatcher);
}
 
Example 17
Source File: ZkCacheBaseDataAccessor.java    From helix with Apache License 2.0 4 votes vote down vote up
@Override
public List<T> get(List<String> paths, List<Stat> stats, int options, boolean throwException)
    throws HelixException {
  if (paths == null || paths.isEmpty()) {
    return Collections.emptyList();
  }

  final int size = paths.size();
  List<String> serverPaths = prependChroot(paths);

  List<T> records = new ArrayList<T>(Collections.<T>nCopies(size, null));
  List<Stat> readStats = new ArrayList<Stat>(Collections.<Stat>nCopies(size, null));

  boolean needRead = false;
  boolean needReads[] = new boolean[size]; // init to false

  Cache<T> cache = getCache(serverPaths);
  if (cache != null) {
    try {
      cache.lockRead();
      for (int i = 0; i < size; i++) {
        ZNode zNode = cache.get(serverPaths.get(i));
        if (zNode != null) {
          // TODO: shall return a deep copy instead of reference
          records.set(i, (T) zNode.getData());
          readStats.set(i, zNode.getStat());
        } else {
          needRead = true;
          needReads[i] = true;
        }
      }
    } finally {
      cache.unlockRead();
    }

    // cache miss, fall back to zk and update cache
    if (needRead) {
      cache.lockWrite();
      try {
        List<T> readRecords =
            _baseAccessor.get(serverPaths, readStats, needReads, throwException);
        for (int i = 0; i < size; i++) {
          if (needReads[i]) {
            records.set(i, readRecords.get(i));
            cache.update(serverPaths.get(i), readRecords.get(i), readStats.get(i));
          }
        }
      } finally {
        cache.unlockWrite();
      }
    }

    if (stats != null) {
      stats.clear();
      stats.addAll(readStats);
    }

    return records;
  }

  // no cache
  return _baseAccessor.get(serverPaths, stats, options, throwException);
}
 
Example 18
Source File: SplitKeyExpression.java    From fdb-record-layer with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public List<KeyExpression> normalizeKeyForPositions() {
    return Collections.nCopies(splitSize, getJoined());
}
 
Example 19
Source File: IdentifierNamespace.java    From Quicksql with MIT License 4 votes vote down vote up
public RelDataType validateImpl(RelDataType targetRowType) {
  resolvedNamespace = Objects.requireNonNull(resolveImpl(id));
  if (resolvedNamespace instanceof TableNamespace) {
    SqlValidatorTable table = resolvedNamespace.getTable();
    if (validator.shouldExpandIdentifiers()) {
      // TODO:  expand qualifiers for column references also
      List<String> qualifiedNames = table.getQualifiedName();
      if (qualifiedNames != null) {
        // Assign positions to the components of the fully-qualified
        // identifier, as best we can. We assume that qualification
        // adds names to the front, e.g. FOO.BAR becomes BAZ.FOO.BAR.
        List<SqlParserPos> poses =
            new ArrayList<>(
                Collections.nCopies(
                    qualifiedNames.size(), id.getParserPosition()));
        int offset = qualifiedNames.size() - id.names.size();

        // Test offset in case catalog supports fewer qualifiers than catalog
        // reader.
        if (offset >= 0) {
          for (int i = 0; i < id.names.size(); i++) {
            poses.set(i + offset, id.getComponentParserPosition(i));
          }
        }
        id.setNames(qualifiedNames, poses);
      }
    }
  }

  RelDataType rowType = resolvedNamespace.getRowType();

  if (extendList != null) {
    if (!(resolvedNamespace instanceof TableNamespace)) {
      throw new RuntimeException("cannot convert");
    }
    resolvedNamespace =
        ((TableNamespace) resolvedNamespace).extend(extendList);
    rowType = resolvedNamespace.getRowType();
  }

  // Build a list of monotonic expressions.
  final ImmutableList.Builder<Pair<SqlNode, SqlMonotonicity>> builder =
      ImmutableList.builder();
  List<RelDataTypeField> fields = rowType.getFieldList();
  for (RelDataTypeField field : fields) {
    final String fieldName = field.getName();
    final SqlMonotonicity monotonicity =
        resolvedNamespace.getMonotonicity(fieldName);
    if (monotonicity != SqlMonotonicity.NOT_MONOTONIC) {
      builder.add(
          Pair.of((SqlNode) new SqlIdentifier(fieldName, SqlParserPos.ZERO),
              monotonicity));
    }
  }
  monotonicExprs = builder.build();

  // Validation successful.
  return rowType;
}
 
Example 20
Source File: GridTestUtils.java    From ignite with Apache License 2.0 2 votes vote down vote up
/**
 * Runs callable object in specified number of threads.
 *
 * @param call Callable.
 * @param threadNum Number of threads.
 * @param threadName Thread names.
 * @return Execution time in milliseconds.
 * @throws Exception If failed.
 */
public static long runMultiThreaded(Callable<?> call, int threadNum, String threadName) throws Exception {
    List<Callable<?>> calls = Collections.<Callable<?>>nCopies(threadNum, call);

    return runMultiThreaded(calls, threadName);
}