Example usage for org.apache.commons.lang ArrayUtils toObject

List of usage examples for org.apache.commons.lang ArrayUtils toObject

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils toObject.

Prototype

public static Boolean[] toObject(boolean[] array) 

Source Link

Document

Converts an array of primitive booleans to objects.

Usage

From source file:ch.epfl.data.squall.components.DataSourceComponent.java

@Override
public DataSourceComponent setOutputPartKey(int... hashIndexes) {
    return setOutputPartKey(Arrays.asList(ArrayUtils.toObject(hashIndexes)));
}

From source file:cfa.vo.iris.sed.ExtSed.java

public void checkChar() {
    for (int i = 0; i < this.getNumberOfSegments(); i++) {
        Segment segment = this.getSegment(i);
        List<Double> spectral;
        try {/*w  ww . jav  a2s .co  m*/
            spectral = Arrays.asList(ArrayUtils.toObject(segment.getSpectralAxisValues()));
            double min = Collections.min(spectral);
            double max = Collections.max(spectral);
            segment.createChar().createSpectralAxis().createCoverage().createBounds().createRange().createMin()
                    .setValue(min);
            segment.createChar().createSpectralAxis().createCoverage().createBounds().createRange().createMax()
                    .setValue(max);
            segment.createChar().createSpectralAxis().createCoverage().createBounds().createExtent()
                    .setValue(max - min);
        } catch (SedNoDataException ex) {
            Logger.getLogger(ExtSed.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

From source file:ch.epfl.data.squall.connectors.hdfs.HDFSmaterializer.java

@Override
public HDFSmaterializer setOutputPartKey(int... hashIndexes) {
    return setOutputPartKey(Arrays.asList(ArrayUtils.toObject(hashIndexes)));
}

From source file:edu.isi.misd.scanner.network.modules.worker.processors.glore.GloreProcessor.java

/**
 * Performs the statistical analysis (logistic regression) using GLORE.
 * //  w  ww.  jav a 2s .  com
 * @param exchange The current exchange.
 * @return The formatted response.
 */
protected ServiceResponse executeAnalysis(Exchange exchange) {
    // Create the service response object
    ServiceResponse response = new ServiceResponse();

    try {
        GloreLogisticRegressionRequest request = (GloreLogisticRegressionRequest) exchange.getIn()
                .getBody(GloreLogisticRegressionRequest.class);

        GloreData data = request.getGloreData();
        if (data == null) {
            data = new GloreData();
            request.setGloreData(data);
        }

        // Create the service response metadata object
        ServiceResponseMetadata responseMetadata = MessageUtils.createServiceResponseMetadata(exchange,
                ServiceRequestStateType.PROCESSING, "The GLORE computational request is in process.");

        GloreStateData state = getState(exchange);
        synchronized (this) {
            if (!state.dataLoaded) {
                readDataFile(exchange);
                state.beta = new Matrix(state.columns, 1, 0.0);
                state.cov_matrix = new Matrix(state.columns, state.columns);

                // convert data into arrays to be passed to Matrix's constructor
                state.Xa = GloreUtils.two_dim_list_to_arr(state.Xv);
                state.Ya = GloreUtils.one_dim_list_to_arr(state.Yv);

                // create X and Y matrices
                state.X = new Matrix(state.Xa);
                state.Y = new Matrix(state.Ya, state.Ya.length);

                data.setColumns(state.columns);
                data.setRows(state.rows);

                state.dataLoaded = true;
            }
        }

        if ("computeCovarianceMatrix".equalsIgnoreCase(data.getState())) {
            if (log.isDebugEnabled()) {
                log.debug("Compute covariance matrix");
            }
            state.beta = GloreUtils.convertMatrixTypeToMatrix(data.getBeta());
            state.hat_beta = state.beta.copy();

            state.P = (state.X.times(-1)).times(state.hat_beta);
            GloreUtils.exp(state.P.getArray());
            GloreUtils.add_one(state.P.getArray());
            GloreUtils.div_one(state.P.getArray());

            state.W = state.P.copy();
            state.W.timesEquals(-1.0);
            GloreUtils.add_one(state.W.getArray());
            state.W.arrayTimesEquals(state.P);
            state.W = state.W.transpose();
            state.W = GloreUtils.diag(state.W.getArray()[0]);

            state.D = ((state.X.transpose()).times(state.W)).times(state.X);
            data.setD(GloreUtils.convertMatrixToMatrixType(state.D));
            responseMetadata.setRequestStateDetail(
                    "The GLORE computational request is in process." + "  Current state: " + data.getState());
        } else if ("computeSDMatrix".equalsIgnoreCase(data.getState())) {
            state.cov_matrix = GloreUtils.convertMatrixTypeToMatrix(data.getCovarianceMatrix());
            if (log.isDebugEnabled()) {
                log.debug("Covariance matrix: " + GloreUtils.matrixToString(state.cov_matrix, 8, 6));
            }

            if (log.isDebugEnabled()) {
                log.debug("Compute SD matrix");
            }
            state.SD = new Matrix(1, state.columns);
            for (int i = 0; i < state.columns; i++) {
                state.SD.set(0, i, Math.sqrt(state.cov_matrix.get(i, i)));
            }

            // compute the M and STD since SD matrix is only computed 
            // when model converges, and therefore, only once
            calMandSTD(state);
            data.getM().addAll(Arrays.asList(ArrayUtils.toObject(state.Ma)));
            if (log.isDebugEnabled()) {
                log.debug("M: " + data.getM());
            }
            data.getSTD().addAll(Arrays.asList(ArrayUtils.toObject(state.STDa)));
            if (log.isDebugEnabled()) {
                log.debug("STD: " + data.getSTD());
            }
            if (log.isDebugEnabled()) {
                log.debug("SD matrix:" + GloreUtils.matrixToString(state.SD, 8, 6));
            }
            data.setSDMatrix(GloreUtils.convertMatrixToMatrixType(state.SD));
            removeState(exchange);

            responseMetadata.setRequestState(ServiceRequestStateType.COMPLETE);
            responseMetadata.setRequestStateDetail(
                    "GLORE computation completed successfully at iteration: " + data.getIteration());
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Compute beta value");
            }
            if (data.getBeta() != null) {
                state.beta = GloreUtils.convertMatrixTypeToMatrix(data.getBeta());
            }
            // P <- 1 + exp(-x%*%beta1)
            state.P = (state.X.times(-1)).times(state.beta);
            GloreUtils.exp(state.P.getArray());
            GloreUtils.add_one(state.P.getArray());
            GloreUtils.div_one(state.P.getArray());

            // w = diag(c(p*(1-p)))
            state.W = state.P.copy();
            state.W.timesEquals(-1.0);
            GloreUtils.add_one(state.W.getArray());
            state.W.arrayTimesEquals(state.P);
            state.W = state.W.transpose();
            state.W = GloreUtils.diag(state.W.getArray()[0]);

            // d <- t(x)%*%w%*%x
            state.D = ((state.X.transpose()).times(state.W)).times(state.X);
            // e <- t(x)%*%(y-p)
            state.E = (state.X.transpose()).times(state.Y.plus(state.P.uminus()));

            // D.print(10,3);
            // E.print(10,3);

            data.setD(GloreUtils.convertMatrixToMatrixType(state.D));
            data.setE(GloreUtils.convertMatrixToMatrixType(state.E));

            // print beta for this iteration
            if (log.isDebugEnabled()) {
                log.debug("Beta: " + GloreUtils.matrixToString(state.beta, 8, 8));
            }
            responseMetadata.setRequestStateDetail("The GLORE computational request is in process."
                    + "  Current state: " + data.getState() + " " + data.getIteration());
        }

        // Create the service response data object
        ServiceResponseData responseData = new ServiceResponseData();
        responseData.setAny(request);
        // Initialize the service response with response data and response metadata
        response.setServiceResponseData(responseData);
        response.setServiceResponseMetadata(responseMetadata);
    } catch (Exception e) {
        response.setServiceResponseMetadata(
                MessageUtils.createServiceResponseMetadata(exchange, ServiceRequestStateType.ERROR,
                        "Unhandled exception during GLORE processing. Caused by [" + e.toString() + "]"));
        removeState(exchange);
        log.warn("Unhandled exception during GLORE processing: ", e);
    }
    return response;
}

From source file:com.flexive.core.storage.genericSQL.GenericSQLFulltextIndexer.java

/**
 * {@inheritDoc}/*ww  w.  j  av a2  s . com*/
 */
@Override
public void index(FxPropertyData data) {
    initStatements();
    if (pk == null || psi == null || psu == null || psd == null || psd_all == null) {
        LOG.warn("Tried to index FxPropertyData with no pk provided!");
        return;
    }
    FxValue value = data.getValue();
    try {
        psi.setLong(4, data.getAssignmentId());
        psi.setString(5, StringUtils.join(ArrayUtils.toObject(data.getIndices()), ','));
        for (long lang : value.getTranslatedLanguages()) {
            String idata;
            try {
                if (value instanceof FxBinary)
                    idata = prepare(FxXMLUtils
                            .getElementData(((FxBinary) value).getTranslation(lang).getMetadata(), "text"));
                else
                    idata = prepare(String.valueOf(value.getTranslation(lang)));
            } catch (Exception e) {
                LOG.error("Failed to fetch indexing data for " + data);
                continue;
            }
            if (idata.length() == 0)
                continue;
            psi.setLong(3, lang);
            psi.setString(6, idata);
            psi.executeUpdate();
        }
    } catch (SQLException e) {
        LOG.error(e);
    }
}

From source file:com.mg.framework.utils.DatabaseUtils.java

/**
 * ?  ?  ?    ? , /*from   www . ja va 2 s. c  o m*/
 * ?  .
 *
 * @param criteria        
 * @param folderFieldName  ?    ?? ? ?
 * @param folderPart       
 * @return 
 */
public static Criteria generateFlatBrowseCriteria(final Criteria criteria, final String folderFieldName,
        final int folderPart) {
    DetachedCriteria dc = DetachedCriteria.forEntityName("com.mg.merp.core.model.FolderRights", "fr")
            .add(Property.forName("fr.FolderId").eqProperty(folderFieldName))
            .add(Restrictions.eq("fr.FolderPart", (short) folderPart))
            .add(Restrictions.eq("fr.Permission", true))
            .add(Restrictions.in("fr.SecGroups.Id",
                    (Object[]) ArrayUtils.toObject(ServerUtils.getUserProfile().getGroups())))
            .setProjection(Projections.property("fr.Id"));
    return criteria.add(Subqueries.exists(dc));
}

From source file:com.flexive.core.search.genericSQL.GenericSQLDataFilter.java

protected final String getBriefcaseIdSelect() {
    final long[] briefcaseIds = getStatement().getBriefcaseFilter();
    for (long briefcaseId : briefcaseIds) {
        try {//from   w w w .j a v a  2 s.  co  m
            EJBLookup.getBriefcaseEngine().load(briefcaseId);
        } catch (FxApplicationException e) {
            throw e.asRuntimeException();
        }
    }
    return "(SELECT id from " + DatabaseConst.TBL_BRIEFCASE_DATA + " WHERE briefcase_id "
            + (briefcaseIds.length == 1 ? ("=" + briefcaseIds[0])
                    : "IN (" + StringUtils.join(ArrayUtils.toObject(briefcaseIds), ',') + ")")
            + ")";
}

From source file:com.opengamma.financial.analytics.model.equity.indexoption.EquityIndexVanillaBarrierOptionVegaMatrixFunction.java

@Override
protected Object computeValues(Set<EquityIndexOption> vanillaOptions, StaticReplicationDataBundle market) {
    final NodalDoublesSurface vegaSurface;
    if (market.getVolatilitySurface() instanceof BlackVolatilitySurfaceMoneynessFcnBackedByGrid) {
        // unpack the market data, including the interpolators
        final BlackVolatilitySurfaceMoneynessFcnBackedByGrid surfaceBundle = (BlackVolatilitySurfaceMoneynessFcnBackedByGrid) market
                .getVolatilitySurface();
        final VolatilitySurfaceInterpolator surfaceInterpolator = surfaceBundle.getInterpolator();
        final GeneralSmileInterpolator strikeInterpolator = surfaceInterpolator.getSmileInterpolator();
        final SmileSurfaceDataBundle volGrid = surfaceBundle.getGridData();
        final double[] forwards = volGrid.getForwards();
        final double[] expiries = volGrid.getExpiries();
        final int nExpiries = volGrid.getNumExpiries();
        final double optionExpiry = vanillaOptions.iterator().next().getTimeToExpiry();
        final double[][] strikes = volGrid.getStrikes();
        final double[][] vols = volGrid.getVolatilities();

        // Prices of vanillas in base scenario
        final int nVanillas = vanillaOptions.size();
        EquityIndexOption[] vanillas = vanillaOptions.toArray(new EquityIndexOption[nVanillas]);
        final Double[] basePrices = new Double[nVanillas];
        for (int v = 0; v < nVanillas; v++) {
            basePrices[v] = PVC.visitEquityIndexOption(vanillas[v], market);
        }/* w  w w  .j  a  v a 2s . c o  m*/

        // Smile fits across strikes in base scenario, one per expiry
        Function1D<Double, Double>[] smileFitsBase = surfaceInterpolator.getIndependentSmileFits(volGrid);

        // Bump market at each expiry and strike scenario
        // In each scenario, reprice each of the underlying vanillaOptions
        // NOTE: Only computing down-shift as this appears to produce more stable risk, and is faster
        List<Triple<Double, Double, Double>> triplesExpiryStrikeVega = new ArrayList<Triple<Double, Double, Double>>();
        final int expiryIndex = SurfaceArrayUtils.getLowerBoundIndex(expiries, optionExpiry);
        for (int t = Math.max(0, expiryIndex - 3); t < Math.min(nExpiries, expiryIndex + 4); t++) {
            final int nStrikes = strikes[t].length;
            int idxLow = SurfaceArrayUtils.getLowerBoundIndex(strikes[t], vanillas[0].getStrike());
            int idxHigh = idxLow;
            for (int v = 1; v < nVanillas; v++) {
                int idxV = SurfaceArrayUtils.getLowerBoundIndex(strikes[t], vanillas[v].getStrike());
                idxLow = Math.min(idxLow, idxV);
                idxHigh = Math.max(idxHigh, idxV);
            }

            for (int k = Math.max(0, idxLow - 6); k < Math.min(nStrikes, idxHigh + 16); k++) {
                // Scenario (t,k)
                // TODO: REVIEW Each scenario only requires a single new smile fit in k. We only recompute the smile function for the expiry we are bumping..
                double[] bumpedVols = Arrays.copyOf(vols[t], nStrikes);
                bumpedVols[k] = vols[t][k] - SHIFT;
                final Function1D<Double, Double> thisExpirysSmile = strikeInterpolator
                        .getVolatilityFunction(forwards[t], strikes[t], expiries[t], bumpedVols);
                Function1D<Double, Double>[] scenarioSmileFits = Arrays.copyOf(smileFitsBase,
                        smileFitsBase.length);
                scenarioSmileFits[t] = thisExpirysSmile;
                BlackVolatilitySurfaceMoneynessFcnBackedByGrid shiftedSurface = surfaceInterpolator
                        .combineIndependentSmileFits(scenarioSmileFits, volGrid);
                StaticReplicationDataBundle shiftedMarket = market.withShiftedSurface(shiftedSurface);
                // Sensitivities
                for (int v = 0; v < nVanillas; v++) {
                    final Double shiftedPV = PVC.visit(vanillas[v], shiftedMarket);
                    Validate.notNull(shiftedPV,
                            "Null PV in shifted scenario, T = " + expiries[t] + ", k = " + strikes[t][k]);
                    final Double vega = (shiftedPV - basePrices[v]) / -SHIFT;
                    final Triple<Double, Double, Double> xyz = new Triple<Double, Double, Double>(expiries[t],
                            strikes[t][k], vega);
                    triplesExpiryStrikeVega.add(xyz);
                }
            }
        }
        vegaSurface = NodalDoublesSurface.from(triplesExpiryStrikeVega);

        // Repackage into DoubleLabelledMatrix2D
        // Find unique set of expiries,
        final Double[] uniqueX = ArrayUtils.toObject(expiries);
        // and strikes
        Set<Double> strikeSet = new HashSet<Double>();
        for (int i = 0; i < strikes.length; i++) {
            strikeSet.addAll(Arrays.asList(ArrayUtils.toObject(strikes[i])));
        }
        final Double[] uniqueY = strikeSet.toArray(new Double[0]);
        // Fill matrix with values, zero where no vega is available
        final double[][] values = new double[uniqueY.length][uniqueX.length];
        int i = 0;
        for (final Double x : uniqueX) {
            int j = 0;
            for (final Double y : uniqueY) {
                double vega;
                try {
                    vega = vegaSurface.getZValue(x, y);
                } catch (final IllegalArgumentException e) {
                    vega = 0;
                }
                values[j++][i] = vega;
            }
            i++;
        }
        final DoubleLabelledMatrix2D vegaMatrix = new DoubleLabelledMatrix2D(uniqueX, uniqueY, values);
        return vegaMatrix;

    } else {
        throw new OpenGammaRuntimeException(
                "Currently will only accept a VolatilitySurface of type: BlackVolatilitySurfaceMoneynessFcnBackedByGrid");
    }
}

From source file:com.ec.android.module.bluetooth40.base.BaseBluetoothControlActivity.java

/**
 * 
 * FIXME
 *
 * @param content
 */
protected void writeContent(String content) {
    writeContent(ArrayUtils.toObject(content.getBytes()));
}

From source file:net.mariottini.swing.JFontChooser.java

/**
 * Construct a font chooser with the specified fonts, optionally showing a sample to the user. The
 * sample text is a default text, you can change it by calling <code>setSampleText</code>.
 * /*from  w  w w  . j a  v  a2s  . c  o m*/
 * @param fontNames
 *          the font family names to show to the user.
 * @param showSample
 *          true to show a sample of the selected font to the user.
 * @see #setSampleText
 */
public JFontChooser(String[] fontNames, boolean showSample) {
    setLayout(new BorderLayout());

    JPanel centerPanel = new JPanel(new BorderLayout());

    // Uncomment one of the two lines below to use a standard layout manager
    // instead of my MeshLayout manager. The result is ugly.
    // JPanel listsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));/*
    // JPanel listsPanel = new JPanel(new GridLayout(0, 3));/*
    net.mariottini.layout.MeshLayout mesh = new net.mariottini.layout.MeshLayout(0, 3, 0);
    mesh.setExpandColumn(0);
    JPanel listsPanel = new JPanel(mesh);// */

    JPanel panel = new JPanel(new BorderLayout());
    panel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
    panel.add(new JLabel("Family name:"), BorderLayout.NORTH);
    fontList = new JList<>(fontNames);
    fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    fontList.setVisibleRowCount(7);
    fontList.setSelectedIndex(0);
    panel.add(new JScrollPane(fontList), BorderLayout.CENTER);
    listsPanel.add(panel);

    panel = new JPanel(new BorderLayout());
    panel.setBorder(BorderFactory.createEmptyBorder(8, 0, 8, 8));
    panel.add(new JLabel("Style:"), BorderLayout.NORTH);
    styleList = new JList<>(STYLE_NAMES);
    styleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    styleList.setVisibleRowCount(7);
    styleList.setSelectedIndex(0);
    panel.add(new JScrollPane(styleList), BorderLayout.CENTER);
    listsPanel.add(panel);

    panel = new JPanel(new BorderLayout());
    panel.setBorder(BorderFactory.createEmptyBorder(8, 0, 8, 8));
    panel.add(new JLabel("Size:"), BorderLayout.NORTH);
    JPanel sizePanel = new JPanel(new BorderLayout());
    sizeText = new JTextField(String.valueOf(SIZES[0]), 4);
    sizePanel.add(sizeText, BorderLayout.NORTH);
    sizeList = new JList<>(ArrayUtils.toObject(SIZES));
    sizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    sizeList.setVisibleRowCount(6);
    sizePanel.add(new JScrollPane(sizeList), BorderLayout.CENTER);
    panel.add(sizePanel, BorderLayout.CENTER);
    listsPanel.add(panel);

    centerPanel.add(listsPanel, BorderLayout.NORTH);

    samplePanel = new JPanel(new BorderLayout());
    samplePanel.setBorder(BorderFactory.createEmptyBorder(0, 8, 4, 8));
    samplePanel.add(new JLabel("Sample:"), BorderLayout.NORTH);
    sampleLabel = new JLabel(DEFAULT_SAMPLE_TEXT, JLabel.CENTER);
    sampleLabel.setMinimumSize(new Dimension(64, 48));
    sampleLabel.setOpaque(true);
    sampleLabel.setBackground(sizeList.getBackground());
    sampleLabel.setBorder(sizeText.getBorder());
    samplePanel.add(sampleLabel, BorderLayout.CENTER);
    samplePanel.setVisible(showSample);
    centerPanel.add(samplePanel, BorderLayout.CENTER);

    add(centerPanel, BorderLayout.CENTER);

    accessoryPanel = new JPanel(new BorderLayout());
    accessoryPanel.setBorder(BorderFactory.createEmptyBorder(8, 0, 4, 8));
    accessoryComponent = new JLabel("Accessory");
    accessoryComponent.setOpaque(true);
    accessoryComponent.setBackground(sizeList.getBackground());
    accessoryPanel.add(accessoryComponent, BorderLayout.CENTER);
    accessoryPanel.setVisible(false);
    add(accessoryPanel, BorderLayout.EAST);

    JPanel southPanel = new JPanel(new BorderLayout());
    southPanel.add(new JLabel(), BorderLayout.CENTER);
    JPanel buttonsPanel = new JPanel();
    ActionListener actionListener = new ButtonActionListener();
    JButton button = new JButton("OK");
    button.addActionListener(actionListener);
    button.setActionCommand(APPROVE_SELECTION);
    buttonsPanel.add(button);
    button = new JButton("Cancel");
    button.addActionListener(actionListener);
    button.setActionCommand(CANCEL_SELECTION);
    buttonsPanel.add(button);
    southPanel.add(buttonsPanel, BorderLayout.EAST);
    add(southPanel, BorderLayout.SOUTH);

    // * Fix list size (optional)
    Dimension d = fontList.getPreferredSize();
    d.width += 6;
    fontList.setPreferredSize(d);
    d = styleList.getPreferredSize();
    d.width += 6;
    styleList.setPreferredSize(d);
    d = sizeList.getPreferredSize();
    d.width += 6;
    sizeList.setPreferredSize(d);
    // */

    // Fix sample size
    Dimension pref = sampleLabel.getPreferredSize();
    Dimension min = sampleLabel.getMinimumSize();
    pref.width += 16;
    pref.height += 12;
    if (pref.width < min.width) {
        pref.width = min.width;
    }
    if (pref.height < min.height) {
        pref.height = min.height;
    }
    sampleLabel.setPreferredSize(pref);

    // set listener
    SampleListener pl = new SampleListener();
    fontList.addListSelectionListener(pl);
    styleList.addListSelectionListener(pl);
    sizeList.addListSelectionListener(pl);
    sizeList.addListSelectionListener(new SizeListListener());
    sizeText.getDocument().addDocumentListener(new SizeTextListener());
    sizeText.addFocusListener(new SizeTextFocusListener());
    sizeList.setSelectedIndex(5);
}