Java Code Examples for org.apache.commons.lang3.ArrayUtils#toPrimitive()

The following examples show how to use org.apache.commons.lang3.ArrayUtils#toPrimitive() . 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: VectorPercentileBase.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Object aggregate( List<Double> values, List<Double> args )
{
    Double fraction = args.get( 0 );

    if ( values.size() == 0 || fraction == null || fraction < 0d || fraction > 1d )
    {
        return null;
    }

    Collections.sort( values );

    if ( fraction == 0d )
    {
        return values.get( 0 );
    }

    double[] vals = ArrayUtils.toPrimitive( values.toArray( new Double[0] ) );

    return percentile.evaluate( vals, fraction * 100. );
}
 
Example 2
Source File: Series.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a copy of the series with each distinct value of the
 * source series appearing exactly once.
 *
 * <br/><b>NOTE:</b> the values may be reordered
 *
 * @return series copy with distinct unique values
 */
public Series unique() {
  if(this.size() <= 1)
    return this;

  Series sorted = this.sorted();
  List<Integer> indices = new ArrayList<>();

  indices.add(0);
  for(int i=1; i<this.size(); i++) {
    if(!sorted.equals(sorted, i-1, i))
      indices.add(i);
  }

  int[] fromIndex = ArrayUtils.toPrimitive(indices.toArray(new Integer[indices.size()]));
  return sorted.project(fromIndex);
}
 
Example 3
Source File: ClusterUtils.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param info
 */
public static void deriveClusterInfoDistanceStatistics(ClusterInfo info) {
    int pointCount = info.getPointDistancesFromCenter().size();
    if (pointCount == 0)
        return;

    double[] distances =
                    ArrayUtils.toPrimitive(info.getPointDistancesFromCenter().values().toArray(new Double[] {}));
    double max = info.isInverse() ? MathUtils.min(distances) : MathUtils.max(distances);
    double total = MathUtils.sum(distances);
    info.setMaxPointDistanceFromCenter(max);
    info.setTotalPointDistanceFromCenter(total);
    info.setAveragePointDistanceFromCenter(total / pointCount);
    info.setPointDistanceFromCenterVariance(MathUtils.variance(distances));
}
 
Example 4
Source File: GenericArrayData.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public long[] toLongArray() {
	if (isPrimitiveArray) {
		return (long[]) array;
	}
	checkNoNull();
	return ArrayUtils.toPrimitive((Long[]) array);
}
 
Example 5
Source File: PageCollatorTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private int[] createMergedPage(int skip, int count, List<Integer> s1, int[] s2)
{
    int[] s1Primitive = (s1 == null || s1.isEmpty()) ? new int[] {} : ArrayUtils.toPrimitive((Integer[]) s1
                .toArray(new Integer[s1.size()]));

    return createMergedPage(skip,
                            count,
                            s1Primitive,
                            s2);
}
 
Example 6
Source File: FindPositionArray.java    From Wikidata-Toolkit with Apache License 2.0 5 votes vote down vote up
/**
 * This method updates the internal array only if the bit vector has been
 * changed since the last update or creation of this class.
 */
void updateCount() {
	if (this.hasChanged) {
		this.positionArray = ArrayUtils.toPrimitive(getPositionList()
				.toArray(new Long[0]));
		this.hasChanged = false;
	}
}
 
Example 7
Source File: NullAwareJoinHelper.java    From flink with Apache License 2.0 5 votes vote down vote up
public static int[] getNullFilterKeys(boolean[] filterNulls) {
	checkNotNull(filterNulls);
	List<Integer> nullFilterKeyList = new ArrayList<>();
	for (int i = 0; i < filterNulls.length; i++) {
		if (filterNulls[i]) {
			nullFilterKeyList.add(i);
		}
	}
	return ArrayUtils.toPrimitive(nullFilterKeyList.toArray(new Integer[0]));
}
 
Example 8
Source File: TestUtils.java    From jhdf with MIT License 5 votes vote down vote up
public static int[] getDimensions(Object data) {
    List<Integer> dims = new ArrayList<>();
    dims.add(Array.getLength(data));

    while (Array.get(data, 0).getClass().isArray()) {
        data = Array.get(data, 0);
        dims.add(Array.getLength(data));
    }
    return ArrayUtils.toPrimitive(dims.toArray(new Integer[0]));
}
 
Example 9
Source File: ByteShuffleChunkedDatasetTest.java    From jhdf with MIT License 5 votes vote down vote up
private int[] getDimensions(Object data) {
	List<Integer> dims = new ArrayList<>();
	dims.add(Array.getLength(data));

	while (Array.get(data, 0).getClass().isArray()) {
		data = Array.get(data, 0);
		dims.add(Array.getLength(data));
	}
	return ArrayUtils.toPrimitive(dims.toArray(new Integer[0]));
}
 
Example 10
Source File: GenericArrayData.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public float[] toFloatArray() {
	if (isPrimitiveArray) {
		return (float[]) array;
	}
	checkNoNull();
	return ArrayUtils.toPrimitive((Float[]) array);
}
 
Example 11
Source File: FullScreenImageViewFragment.java    From CameraV with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int[] getSpecs() {
	Log.d(LOG, "RECALCULATING FOR IMAGE");
	
	List<Integer> specs = new ArrayList<Integer>(Arrays.asList(ArrayUtils.toObject(super.getSpecs())));
	
	for(float i : matrixTranslate) {
		specs.add((int) i/2);
	}
	
	/*
	int[] locationInWindow = new int[2];
	mediaHolder_.getLocationInWindow(locationInWindow);
	for(int i : locationInWindow) {
		specs.add(i);
	}
	*/
	
	specs.add(mediaHolder_.getWidth());
	specs.add(mediaHolder_.getHeight());
	
	// these might not be needed
	specs.add(media_.width);
	specs.add(media_.height);
	
	return ArrayUtils.toPrimitive(specs.toArray(new Integer[specs.size()]));
}
 
Example 12
Source File: GenericArrayData.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public double[] toDoubleArray() {
	if (isPrimitiveArray) {
		return (double[]) array;
	}
	checkNoNull();
	return ArrayUtils.toPrimitive((Double[]) array);
}
 
Example 13
Source File: GenericArrayData.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public int[] toIntArray() {
	if (isPrimitiveArray) {
		return (int[]) array;
	}
	checkNoNull();
	return ArrayUtils.toPrimitive((Integer[]) array);
}
 
Example 14
Source File: BaseDataStore.java    From geowave with Apache License 2.0 4 votes vote down vote up
protected CloseableIterator<Object> queryConstraints(
    final List<Short> adapterIdsToQuery,
    final Index index,
    final QueryConstraints sanitizedQuery,
    final DedupeFilter filter,
    final BaseQueryOptions sanitizedQueryOptions,
    final PersistentAdapterStore tempAdapterStore,
    final boolean delete) {
  final BaseConstraintsQuery constraintsQuery =
      new BaseConstraintsQuery(
          ArrayUtils.toPrimitive(adapterIdsToQuery.toArray(new Short[0])),
          index,
          sanitizedQuery,
          filter,
          sanitizedQueryOptions.getScanCallback(),
          sanitizedQueryOptions.getAggregation(),
          sanitizedQueryOptions.getFieldIdsAdapterPair(),
          IndexMetaDataSet.getIndexMetadata(
              index,
              adapterIdsToQuery,
              statisticsStore,
              sanitizedQueryOptions.getAuthorizations()),
          DuplicateEntryCount.getDuplicateCounts(
              index,
              adapterIdsToQuery,
              statisticsStore,
              sanitizedQueryOptions.getAuthorizations()),
          DifferingFieldVisibilityEntryCount.getVisibilityCounts(
              index,
              adapterIdsToQuery,
              statisticsStore,
              sanitizedQueryOptions.getAuthorizations()),
          FieldVisibilityCount.getVisibilityCounts(
              index,
              adapterIdsToQuery,
              statisticsStore,
              sanitizedQueryOptions.getAuthorizations()),
          DataIndexUtils.getDataIndexRetrieval(
              baseOperations,
              adapterStore,
              internalAdapterStore,
              index,
              sanitizedQueryOptions.getFieldIdsAdapterPair(),
              sanitizedQueryOptions.getAggregation(),
              sanitizedQueryOptions.getAuthorizations(),
              baseOptions.getDataIndexBatchSize()),
          sanitizedQueryOptions.getAuthorizations());

  return constraintsQuery.query(
      baseOperations,
      baseOptions,
      tempAdapterStore,
      internalAdapterStore,
      sanitizedQueryOptions.getMaxResolutionSubsamplingPerDimension(),
      sanitizedQueryOptions.getTargetResolutionPerDimensionForHierarchicalIndex(),
      sanitizedQueryOptions.getLimit(),
      sanitizedQueryOptions.getMaxRangeDecomposition(),
      delete);
}
 
Example 15
Source File: JData.java    From konduit-serving with Apache License 2.0 4 votes vote down vote up
public static Data singleton(@NonNull String key, @NonNull Object data) {
        Data instance = new JData();
        if (data instanceof String) {
            instance.put(key, (String)data);
        }
        else if (data instanceof Boolean) {
            instance.put(key, (Boolean)data);
        }
        else if (data instanceof  Integer) {
            instance.put(key, ((Integer) data).longValue());
        }
        else if (data instanceof Long) {
            instance.put(key, (Long)data);
        }
        else if (data instanceof Float) {
            instance.put(key, ((Float) data).doubleValue());
        }
        else if (data instanceof Double) {
            instance.put(key, (Double)data);
        }
        else if (data instanceof Image) {
            instance.put(key, (Image)data);
        }
        else if (data instanceof Byte[]) {
            byte[] input = ArrayUtils.toPrimitive((Byte[])data);
            instance.put(key, input);
        }
        else if (data instanceof byte[]) {
            instance.put(key, (byte[]) data);
        }
        else if (data instanceof Data) {
            instance.put(key, (Data)data);
        }
        else if(data instanceof NDArray){
            instance.put(key, (NDArray)data);
        }
        else if (data instanceof Image) {
            instance.put(key, (Image)data);
        } else if(data instanceof BoundingBox){
            instance.put(key, (BoundingBox)data);
        } else if(data instanceof Point){
            instance.put(key, (Point)data);
        } else if (data instanceof NDArray) {
            instance.put(key, (NDArray) data);
        }
//        else if (data instanceof Object) {
//            instance.put(key, (Object)data);
//        }
        else {
            throw new IllegalStateException("Trying to put data of not supported type: " + data.getClass());
        }
        return instance;
    }
 
Example 16
Source File: DataBufferPersistenceUtils.java    From geowave with Apache License 2.0 4 votes vote down vote up
protected static int[] integerListToPrimitiveArray(final List<Integer> internalList) {
  return ArrayUtils.toPrimitive(internalList.toArray(new Integer[internalList.size()]));
}
 
Example 17
Source File: RelatedBinaryContentImpl.java    From Asqatasun with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public byte[] getContent() {
    return ArrayUtils.toPrimitive(binaryContent);
}
 
Example 18
Source File: AbstractRForecaster.java    From kieker with Apache License 2.0 4 votes vote down vote up
private ForecastResult forecastWithR(final int numForecastSteps) throws InvalidREvaluationResultException {
	final ITimeSeries<Double> history = this.getTsOriginal();
	final ITimeSeries<Double> tsForecast = this.prepareForecastTS();

	final String varNameValues = RBridgeControl.uniqueVarname();
	final String varNameModel = RBridgeControl.uniqueVarname();
	final String varNameForecast = RBridgeControl.uniqueVarname();

	final List<Double> allHistory = new ArrayList<>(history.getValues());
	final Double[] histValuesNotNull = AbstractRForecaster.removeNullValues(allHistory);
	final double[] values = ArrayUtils.toPrimitive(histValuesNotNull);

	double fcQuality = Double.NaN;
	// 0. Assign values to temporal variable

	AbstractRForecaster.RBRIDGE.assign(varNameValues, values);

	if (history.getFrequency() != 0) {
		if (this.strategy != ForecastMethod.ARIMA) {
			// frequency for time series object in R --> needed for MASE calculation.
			AbstractRForecaster.RBRIDGE.toTS(varNameValues, history.getFrequency());
		} else {
			AbstractRForecaster.RBRIDGE.toTS(varNameValues);
		}
	}

	// 1. Compute stochastic model for forecast

	if (this.modelFunc == null) {
		// In this case, the values are the model ...
		AbstractRForecaster.RBRIDGE.assign(varNameModel, values);
		if (history.getFrequency() != 0) {
			if (this.strategy != ForecastMethod.ARIMA) {
				// frequency for time series object in R --> needed for MASE calculation.
				AbstractRForecaster.RBRIDGE.toTS(varNameValues, history.getFrequency());
			} else {
				AbstractRForecaster.RBRIDGE.toTS(varNameValues);
			}
		}
	} else {
		final String[] additionalModelParams = this.getModelFuncParams();

		final StringBuffer params = new StringBuffer();
		params.append(varNameValues);
		if (null != additionalModelParams) {
			for (final String param : additionalModelParams) {
				params.append(',');
				params.append(param);
			}
		}
		AbstractRForecaster.RBRIDGE.evalWithR(String.format("%s <- %s(%s)", varNameModel, this.modelFunc, params));
	}
	// remove temporal variable:
	AbstractRForecaster.RBRIDGE.evalWithR(String.format("rm(%s)", varNameValues));

	// 2. Perform forecast based on stochastic model

	if ((this.getConfidenceLevel() == 0) || !this.supportsConfidence()) {
		AbstractRForecaster.RBRIDGE.evalWithR(String.format("%s <- %s(%s, h=%d)", varNameForecast, this.forecastFunc, varNameModel,
				numForecastSteps));
	} else {
		AbstractRForecaster.RBRIDGE.evalWithR(String.format("%s <- %s(%s, h=%d, level=c(%d))", varNameForecast, this.forecastFunc, varNameModel,
				numForecastSteps, this.getConfidenceLevel()));
	}

	final double[] forecastValues = AbstractRForecaster.RBRIDGE.eDblArr(this.forecastOperationOnResult(varNameForecast));

	// 3. Calculate Forecast Quality Metric

	if (forecastValues.length > 1) {
		if ((this.modelFunc == null)) { // Re-enable when TBATS included: || (this.strategy == ForecastMethod.TBATS)
			fcQuality = AbstractRForecaster.RBRIDGE.eDbl("accuracy(" + varNameForecast + ")[6]");
		} else {
			fcQuality = AbstractRForecaster.RBRIDGE.eDbl("accuracy(" + varNameModel + ")[6]");
		}
	}

	tsForecast.appendAll(ArrayUtils.toObject(forecastValues));
	final ITimeSeries<Double> tsLower;
	final ITimeSeries<Double> tsUpper;

	if ((this.getConfidenceLevel() == 0) || !this.supportsConfidence()) {
		tsLower = tsForecast;
		tsUpper = tsForecast;
	} else {
		final double[] lowerValues = AbstractRForecaster.RBRIDGE.eDblArr(this.lowerOperationOnResult(varNameForecast));
		final double[] upperValues = AbstractRForecaster.RBRIDGE.eDblArr(this.upperOperationOnResult(varNameForecast));
		tsLower = this.prepareForecastTS();
		tsLower.appendAll(ArrayUtils.toObject(lowerValues));
		tsUpper = this.prepareForecastTS();
		tsUpper.appendAll(ArrayUtils.toObject(upperValues));
	}

	// remove temporal variable:
	AbstractRForecaster.RBRIDGE.evalWithR(String.format("rm(%s)", varNameModel));
	AbstractRForecaster.RBRIDGE.evalWithR(String.format("rm(%s)", varNameValues));
	AbstractRForecaster.RBRIDGE.evalWithR(String.format("rm(%s)", varNameForecast));

	return new ForecastResult(tsForecast, this.getTsOriginal(), this.getConfidenceLevel(), fcQuality, tsLower, tsUpper, this.strategy);
}
 
Example 19
Source File: MultipleSelectionAndFocus.java    From pdfsam with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public int[] getRows() {
    // TODO this sucks
    return ArrayUtils.toPrimitive(rows.toArray(new Integer[rows.size()]));
}
 
Example 20
Source File: WorldProviderPlanet.java    From AdvancedRocketry with MIT License 4 votes vote down vote up
@Override
public int[] getDimensionsInOrbit(BlockPos pos) {
	Set<Integer> intSet = getDimensionProperties(pos).getChildPlanets();
	Integer[] intArray = new Integer[intSet.size()];
	return ArrayUtils.toPrimitive(getDimensionProperties(pos).getChildPlanets().toArray(intArray));
}