Example usage for java.util Vector get

List of usage examples for java.util Vector get

Introduction

In this page you can find the example usage for java.util Vector get.

Prototype

public synchronized E get(int index) 

Source Link

Document

Returns the element at the specified position in this Vector.

Usage

From source file:edu.ku.brc.specify.dbsupport.AccessionAutoNumberAlphaNum.java

@Override
protected String getHighestObject(final UIFieldFormatterIFace formatter, final Session session,
        final String value, final Pair<Integer, Integer> yearPos, final Pair<Integer, Integer> pos)
        throws Exception {
    Division currDivision = AppContextMgr.getInstance().getClassObject(Division.class);

    String ansSQL = "SELECT ans.AutonumberingSchemeID, ans.FormatName, ans.IsNumericOnly, ans.SchemeName, dv.Name, dv.DivisionID "
            + "FROM autonumberingscheme ans "
            + "Inner Join autonumsch_div ad ON ans.AutoNumberingSchemeID = ad.AutoNumberingSchemeID "
            + "Inner Join division dv ON ad.DivisionID = dv.UserGroupScopeId WHERE dv.UserGroupScopeId = %d AND FormatName = '%s'";
    String sql = String.format(ansSQL, currDivision.getId(), formatter.getName());
    log.debug(sql);//  w  w  w  .  ja va 2  s . c om

    Vector<Object[]> rows = BasicSQLUtils.query(sql);
    Integer ansID = null;
    if (rows.size() == 1) {
        ansID = (Integer) rows.get(0)[0];

    } else if (rows.size() == 0) {
        errorMsg = "There are NO formatters named [" + formatter.getName() + "]";
    } else {
        errorMsg = "Too many Formatters named [" + formatter.getName() + "]";
    }

    if (ansID == null) {
        log.debug(errorMsg);
        return null;
    }

    //String sql          = "SELECT autonumberingscheme.FormatName, autonumberingscheme.SchemeName, autonumberingscheme.IsNumericOnly, collection.CollectionName, discipline.Name, division.Name, accession.AccessionNumber FROM autonumberingscheme Inner Join autonumsch_coll ON autonumberingscheme.AutoNumberingSchemeID = autonumsch_coll.AutoNumberingSchemeID Inner Join collection ON autonumsch_coll.CollectionID = collection.UserGroupScopeId Inner Join discipline ON collection.DisciplineID = discipline.UserGroupScopeId Inner Join division ON discipline.DivisionID = division.UserGroupScopeId Inner Join accession ON division.UserGroupScopeId = accession.DivisionID ";
    //String ansToDivLong = "SELECT ans.FormatName, ans.SchemeName, ans.IsNumericOnly, c.CollectionName, ds.Name, dv.Name FROM autonumberingscheme ans Inner Join autonumsch_coll ac ON ans.AutoNumberingSchemeID = ac.AutoNumberingSchemeID Inner Join collection c ON ac.CollectionID = c.UserGroupScopeId Inner Join discipline ds ON c.DisciplineID = ds.UserGroupScopeId Inner Join division dv ON ds.DivisionID = dv.UserGroupScopeId ";
    String ansToDivSQL = "SELECT dv.UserGroupScopeId DivID FROM autonumberingscheme ans "
            + "Inner Join autonumsch_div ad ON ans.AutoNumberingSchemeID = ad.AutoNumberingSchemeID "
            + "Inner Join division dv ON ad.DivisionID = dv.UserGroupScopeId "
            + "WHERE ans.AutoNumberingSchemeID = %d";

    ansToDivSQL = String.format(ansToDivSQL, ansID);
    log.debug(ansToDivSQL);

    Vector<Integer> divIds = new Vector<Integer>();
    for (Object[] row : BasicSQLUtils.query(ansToDivSQL)) {
        divIds.add((Integer) row[0]);
    }

    Integer yearVal = null;
    if (yearPos != null && StringUtils.isNotEmpty(value) && value.length() >= yearPos.second) {
        yearVal = extractIntegerValue(yearPos, value).intValue();
    }

    StringBuilder sb = new StringBuilder(
            "SELECT a.accessionNumber FROM Accession a Join a.division dv Join dv.numberingSchemes ans WHERE ans.id = ");
    AutoNumberingScheme accessionAutoNumScheme = currDivision
            .getNumberingSchemesByType(Accession.getClassTableId());
    if (accessionAutoNumScheme != null && accessionAutoNumScheme.getAutoNumberingSchemeId() != null) {
        sb.append(accessionAutoNumScheme.getAutoNumberingSchemeId());
        sb.append(" AND dv.id in (");
        for (Integer dvId : divIds) {
            sb.append(dvId);
            sb.append(',');
        }
        sb.setLength(sb.length() - 1);
        sb.append(')');

    } else {
        UIRegistry.showError("There is no AutonumberingScheme for the Accession formatter!");
        return "";
    }

    if (yearVal != null) {
        sb.append(" AND ");
        sb.append(yearVal);
        sb.append(" = substring(" + fieldName + "," + (yearPos.first + 1) + ","
                + (yearPos.second - yearPos.first) + ")");
    }

    sb.append(" ORDER BY");

    try {
        if (yearPos != null) {
            sb.append(" substring(" + fieldName + "," + (yearPos.first + 1) + ","
                    + (yearPos.second - yearPos.first) + ") desc");
        }

        if (pos != null) {
            if (yearPos != null) {
                sb.append(", ");
            }
            sb.append(" substring(" + fieldName + "," + (pos.first + 1) + "," + (pos.second - pos.first)
                    + ") desc");
        }

        System.out.println("AccessionAutoNumberAlphaNum - " + sb.toString());

        List<?> list = session.createQuery(sb.toString()).setMaxResults(1).list();
        if (list.size() == 1) {
            return list.get(0).toString();
        }
    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(AccessionAutoNumberAlphaNum.class, ex);
        ex.printStackTrace();
    }
    return null;
}

From source file:de.ipbhalle.metfrag.main.CommandLineTool.java

/**
 * TODO adding inchi and inchi key generation
 * /*from w  ww  . j  a v  a2  s . co m*/
 * save the results of the metfrag run
 * 
 * @param results
 * @throws CDKException 
 */
public static void saveResults(List<MetFragResult> results) {
    if (results == null || results.size() == 0) {
        System.out.println("Error: No results.");
        return;
    }
    MoleculeSet setOfMolecules = new MoleculeSet();
    SmilesGenerator sg = new SmilesGenerator();
    //uncomment if inchi generation is avaiable on your system - jni-inchi
    /*org.openscience.cdk.inchi.InChIGeneratorFactory factory = null;
    try {
       factory = org.openscience.cdk.inchi.InChIGeneratorFactory.getInstance();
    } catch (CDKException e3) {
       e3.printStackTrace();
    }*/
    for (MetFragResult result : results) {
        IAtomContainer tmp = result.getStructure();
        tmp = AtomContainerManipulator.removeHydrogens(tmp);
        String smiles = sg.createSMILES(tmp);
        tmp.setProperty("DatabaseID", result.getCandidateID());
        tmp.setProperty("NoPeaksExplained", result.getPeaksExplained());
        tmp.setProperty("SMILES", smiles);
        //uncomment if inchi generation is avaiable on your system - jni-inchi
        /*   IAtomContainer tmp_clone = null;
           try {
              tmp_clone = (IAtomContainer)tmp.clone();
           } catch (CloneNotSupportedException e2) {
              e2.printStackTrace();
           }
           if(factory != null && tmp_clone != null) {   
              try {
                 AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(tmp_clone);
              } catch (CDKException e1) {
                         
              }
              org.openscience.cdk.tools.CDKHydrogenAdder hAdder = org.openscience.cdk.tools.CDKHydrogenAdder.getInstance(tmp_clone.getBuilder());
                for(int i = 0; i < tmp_clone.getAtomCount(); i++) {
         try {
            hAdder.addImplicitHydrogens(tmp_clone, tmp_clone.getAtom(i));
         } catch(Exception e) {
            continue;
         }
                }
                AtomContainerManipulator.convertImplicitToExplicitHydrogens(tmp_clone);
                try {
         org.openscience.cdk.inchi.InChIGenerator gen = factory.getInChIGenerator(tmp_clone);
                 if(gen != null) {
          String inchi = gen.getInchi();
          tmp.setProperty("InChI", inchi);
                 }
              } catch (CDKException e) {
                         
              }
           }*/

        tmp.setProperty("PeakScore", result.getRawPeakMatchScore());
        tmp.setProperty("BondEnergyScore", result.getRawBondEnergyScore());
        tmp.setProperty("Score", result.getScore());
        for (IBond bond : tmp.bonds()) {
            if (bond.getStereo() == null)
                bond.setStereo(Stereo.UP_OR_DOWN);
        }
        String matchedPeaksString = "";
        Vector<PeakMolPair> pairs = result.getFragments();
        for (int k = 0; k < pairs.size(); k++) {
            PeakMolPair fragment = pairs.get(k);
            if (k == result.getFragments().size())
                matchedPeaksString += fragment.getPeak().getMass() + " " + fragment.getPeak().getRelIntensity();
            else
                matchedPeaksString += fragment.getPeak().getMass() + " " + fragment.getPeak().getRelIntensity()
                        + " ";
        }
        if (!matchedPeaksString.equals(""))
            tmp.setProperty("PeaksExplained", matchedPeaksString);

        setOfMolecules.addAtomContainer(tmp);
    }
    try {
        SDFWriter writer = new SDFWriter(new FileWriter(new File(
                resultspath + System.getProperty("file.separator") + "results_" + sampleName + ".sdf")));
        try {
            writer.write(setOfMolecules);
        } catch (CDKException e) {
            System.out.println("Error: Could not write results file.");
        }
        writer.close();
    } catch (IOException e) {
        System.out.println("Error: Could not write results file.");
    }
    if (verbose)
        System.out.println("wrote " + setOfMolecules.getAtomContainerCount() + " molecules to " + resultspath);
}

From source file:edu.uga.cs.fluxbuster.clustering.hierarchicalclustering.DistanceMatrix.java

/**
 * Retrieves the distance between the clusters at the supplied indexes
 * /* w ww.ja  v  a  2  s .c  om*/
 * @param p
 *            the indexes of the clusters
 * @return the distance between the clusters, if the indexes are not within
 *         the bounds of the distance matrix Float.MAX_VALUE is returned
 */
private float distanceHelper(IndexPair p) {
    int i = p.getI();
    int j = p.getJ();
    if (i >= 0 && i < distMatrix.size() && j >= 0 && j < distMatrix.size()) {
        try {
            Vector<Float> row = distMatrix.get(i);
            return row.get(j);

        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("Error retrieving distance.", e);
            }
        }
    }
    return Float.MAX_VALUE;
}

From source file:edu.ku.brc.af.ui.db.TextFieldFromPickListTable.java

public void setValue(final Object value, final String defaultValue) {
    dataObj = value;// w w  w. j a va  2  s . c  o m

    if (value != null) {
        if (adapter == null) {
            setText(value.toString());
            return;
        }

        if (adapter.isTabledBased()) {
            String data = null;

            boolean isFormObjIFace = value instanceof FormDataObjIFace;
            Vector<PickListItemIFace> items = adapter.getList();

            for (int i = 0; i < items.size(); i++) {
                PickListItemIFace pli = items.get(i);
                Object valObj = pli.getValueObject();

                if (valObj != null) {
                    if (isFormObjIFace && valObj instanceof FormDataObjIFace) {
                        //System.out.println(((FormDataObjIFace)value).getId().longValue()+"  "+(((FormDataObjIFace)valObj).getId().longValue()));
                        if (((FormDataObjIFace) value).getId()
                                .intValue() == (((FormDataObjIFace) valObj).getId().intValue())) {
                            data = pli.getTitle();
                            break;
                        }
                    } else if (pli.getValue().equals(value.toString())) {
                        data = pli.getTitle();
                        break;
                    }
                }
            }

            if (data == null) {
                data = StringUtils.isNotEmpty(defaultValue) ? defaultValue : ""; //$NON-NLS-1$
            }

            setText(data);

        } else {
            boolean fnd = false;
            setText("");
            for (PickListItemIFace item : adapter.getList()) {
                if (item.getValue() == null && value == null) {
                    break;

                } else if (item.getValue() != null && value != null
                        && item.getValue().equals(value.toString())) {
                    setText(item.getTitle());
                    fnd = true;
                    break;
                }
            }

            if (!fnd && !adapter.isReadOnly()) {
                setText(value != null ? value.toString() : defaultValue);
            }
        }

        repaint();
    } else {
        if (nullIndex == null) {
            if (adapter != null) {
                int inx = 0;
                for (PickListItemIFace item : adapter.getList()) {
                    if (item != null && item.getValue() != null && item.getValue().equals("|null|")) {
                        nullIndex = inx;
                        setText(item.getTitle());
                        break;
                    }
                    inx++;
                }
                if (nullIndex == null) {
                    nullIndex = -1;
                }
            }
        } else if (nullIndex > -1) {
            PickListItemIFace item = adapter.getList().get(nullIndex);
            if (item != null) {
                setText(item.getTitle());
            }
            return;
        } else if (nullIndex == -1) {
            setText("");
        }
    }
}

From source file:peakmlviewer.view.IntensityView.java

public void update(int event) {
    graph.clear();/*from w  w w.  ja  v a2 s  .c o m*/
    if (event != Document.UPDATE_INIT) {
        Document document = getMainWnd().getDocument();
        IPeak peak = document.getCurrentPeak();
        if (peak == null)
            return;
        Vector<IPeak> peaks = IPeak.unpack(peak);

        Header header = document.getHeader();
        for (SetInfo setinfo : header.getSetInfos()) {
            // retrieve all the peaks for this set
            Vector<IPeak> set = IPeak.peaksOfMeasurements(peaks, setinfo.getAllMeasurementIDs());

            // grab the intensities and add to the data
            double intensities[] = new double[set.size()];
            for (int i = 0; i < set.size(); ++i)
                intensities[i] = set.get(i).getIntensity();
            graph.addData(setinfo.getID(), intensities);
        }
    }
}

From source file:com.feilong.commons.core.tools.json.JsonUtilTest.java

/**
 * Test vector.// w  ww  .ja  v  a  2s.  com
 */
@Test
public void testVector() {
    Vector<Integer> vector = new Vector<Integer>();
    vector.add(1);
    vector.add(2222);
    vector.add(3333);
    vector.add(55555);
    log.info("vector:{}", JsonUtil.format(vector));
    log.info("" + vector.get(0));
}

From source file:com.nidhinova.tools.ssh.SFTPClient.java

public void deleteRemoteFolder(String root, String relativepath) throws SftpException {
    this.sftp.cd(this.sftp.getHome());
    this.sftp.cd(root + "/" + relativepath);
    _logger.debug(">cd " + root + "/" + relativepath);
    String pwd = this.sftp.pwd();
    _logger.debug("pwd=" + pwd);
    //delete all files
    Vector<ChannelSftp.LsEntry> files;
    files = this.sftp.ls("*.*");
    _logger.debug("# files = " + (files == null ? "0" : files.size()));

    if (files != null) {
        for (int i = 0; i < files.size(); i++) {
            ChannelSftp.LsEntry file = files.get(i);
            this.sftp.rm(file.getFilename());
            _logger.debug("Deleted file " + file.getFilename());
        }/*from  www .j a v  a 2s.  c om*/

    }

    //delete the folder      
    String foldername = relativepath.substring(relativepath.lastIndexOf('/') + 1);
    this.sftp.cd("..");
    pwd = this.sftp.pwd();
    this.sftp.rmdir(foldername);
}

From source file:edu.stanford.cfuller.imageanalysistools.clustering.ObjectClustering.java

/**
 * Calculates a metric of clustering goodness, which is based upon the ratio of the average distance between objects withing a cluster to the maximal distance between objects in two different clusters.
 *
 * This is used to determine whether it is actually better to subdivide a cluster into multiple clusters or not; in general having more clusters will
 * produce a higher likelihood score from the Gaussian mixture model clustering, so some independent metric is needed to guess at what
 * the best number of clusters is.  Using this metric, clusters are only subdivided if the division can substantially reduce the ratio of
 * the distances between objects withing a cluster relative to distances of object between clusters.
 *
 * @param clusterObjects    A Vector containing the ClusterObjects currently being clustered.
 * @param clusters          A Vector containing the current cluster assignments on which the metric is to be calculated.
 * @param k                 The number of clusters.
 * @param n                 The number of cluster objects.
 * @return                  The result of applying the metric.  A lower score means the clustering is better.
 *///from  w  ww.  ja v a2  s. c  o  m
public static double getInterClusterDistances(Vector<ClusterObject> clusterObjects, Vector<Cluster> clusters,
        int k, int n) {

    double[] intraClusterDists = new double[k];
    int[] intraCounts = new int[k];
    double[] maxIntra = new double[k];

    java.util.Arrays.fill(intraClusterDists, 0.0);
    java.util.Arrays.fill(intraCounts, 0);
    java.util.Arrays.fill(maxIntra, 0.0);

    for (int i = 0; i < n; i++) {

        int i_ID = clusterObjects.get(i).getCurrentCluster().getID();

        for (int j = i + 1; j < n; j++) {

            int j_ID = clusterObjects.get(j).getCurrentCluster().getID();

            if (i_ID == j_ID) {

                double dist = clusterObjects.get(i).distanceTo(clusterObjects.get(j));

                intraClusterDists[i_ID - 1] += dist;

                intraCounts[i_ID - 1]++;

                if (dist > maxIntra[i_ID - 1]) {
                    maxIntra[i_ID - 1] = dist;
                }

            }

        }
    }

    double ratios = 0;
    int ratio_counts = 0;

    for (int i = 0; i < k; i++) {

        if (clusters.get(i).getObjectSet().size() == 0) {

            continue;

        }

        for (int j = i + 1; j < k; j++) {

            if (clusters.get(j).getObjectSet().size() == 0) {
                continue;
            }

            double maxDist = 0;

            for (ClusterObject i_obj : clusters.get(i).getObjectSet()) {

                for (ClusterObject j_obj : clusters.get(j).getObjectSet()) {

                    double dist = i_obj.distanceTo(j_obj);

                    if (dist > maxDist) {
                        maxDist = dist;
                    }

                }

            }

            final double zeroCountScalingFactor = 4;

            if (intraCounts[i] == 0) {
                intraCounts[i] = 1;
                intraClusterDists[i] = maxDist / zeroCountScalingFactor;
            }

            if (intraCounts[j] == 0) {
                intraCounts[j] = 1;
                intraClusterDists[j] = maxDist / zeroCountScalingFactor;
            }

            ratios += 2 * (intraClusterDists[i] / intraCounts[i] + intraClusterDists[j] / intraCounts[j])
                    / maxDist;
            ratio_counts++;

        }

    }

    if (ratio_counts == 0) {
        double maxElement = 0;

        for (double d : maxIntra) {
            if (d > maxElement)
                maxElement = d;
        }

        ratios = 4 * intraClusterDists[0] / (maxElement + 1e-9);
        ratio_counts = 1;
    }

    return ratios / ratio_counts;
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.config.fileextension.FileExtensionMainHandler.java

private String checkDependencies(FileExtensionImpl fileExtension, HttpSession session) {
    ResourceBundle bundle = PageHandler.getBundle(session);
    FileExtensionDependencyChecker depChecker = new FileExtensionDependencyChecker();

    Hashtable catDeps = depChecker.categorizeDependencies(fileExtension);

    StringBuffer deps = new StringBuffer();
    if (catDeps.size() == 0) {
        return null;
    }/*from w w w.j a  va 2 s. co  m*/

    deps.append("<span class=\"errorMsg\">");
    Object[] args = { bundle.getString("lb_file_extension") };
    deps.append(MessageFormat.format(bundle.getString("msg_dependency"), args));

    for (Enumeration e = catDeps.keys(); e.hasMoreElements();) {
        String key = (String) e.nextElement();
        deps.append("<p>*** " + bundle.getString(key) + " ***<br>");
        Vector values = (Vector) catDeps.get(key);
        for (int i = 0; i < values.size(); i++) {
            deps.append((String) values.get(i));
            deps.append("<br>");
        }
    }
    deps.append("</span>");
    return deps.toString();
}

From source file:eionet.gdem.dcm.business.WorkqueueManager.java

/**
 * Adds new jobs into the workqueue by the given XML Schema
 *
 * @param user/*www  .j  ava  2 s. co  m*/
 *            Loggedin user name.
 * @param sourceUrl
 *            Source URL of XML file.
 * @param schemaUrl
 *            XML Schema URL.
 * @return List of job IDs.
 * @throws DCMException
 */
public List<String> addSchemaScriptsToWorkqueue(String user, String sourceUrl, String schemaUrl)
        throws DCMException {

    List<String> result = new ArrayList<String>();
    try {
        if (!SecurityUtil.hasPerm(user, "/" + Names.ACL_WQ_PATH, "i")) {
            LOGGER.debug("You don't have permissions jobs into workqueue!");
            throw new DCMException(BusinessConstants.EXCEPTION_AUTORIZATION_QASCRIPT_UPDATE);
        }

    } catch (DCMException e) {
        throw e;
    } catch (Exception e) {
        LOGGER.error("Error adding job to workqueue", e);
        throw new DCMException(BusinessConstants.EXCEPTION_GENERAL);
    }
    XQueryService xqE = new XQueryService();
    xqE.setTrustedMode(false);
    try {
        Hashtable h = new Hashtable();
        Vector files = new Vector();
        files.add(sourceUrl);
        h.put(schemaUrl, files);
        Vector v_result = xqE.analyzeXMLFiles(h);
        if (v_result != null) {
            for (int i = 0; i < v_result.size(); i++) {
                Vector v = (Vector) v_result.get(i);
                result.add((String) v.get(0));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.error("Error adding job to workqueue", e);
        throw new DCMException(BusinessConstants.EXCEPTION_GENERAL);
    }
    return result;
}