Example usage for java.util Arrays sort

List of usage examples for java.util Arrays sort

Introduction

In this page you can find the example usage for java.util Arrays sort.

Prototype

public static void sort(Object[] a) 

Source Link

Document

Sorts the specified array of objects into ascending order, according to the Comparable natural ordering of its elements.

Usage

From source file:Util.java

/**
 * Retrive the quartile value from an array
 * .//from   www  . j a  v a 2  s  . com
 * @param values THe array of data
 * @param lowerPercent The percent cut off. For the lower quartile use 25,
 *      for the upper-quartile use 75
 * @return
 */
public static double quartile(double[] values, double lowerPercent) {

    if (values == null || values.length == 0) {
        throw new IllegalArgumentException("The data array either is null or does not contain any data.");
    }

    // Rank order the values
    double[] v = new double[values.length];
    System.arraycopy(values, 0, v, 0, values.length);
    Arrays.sort(v);

    int n = (int) Math.round(v.length * lowerPercent / 100);

    return v[n];

}

From source file:de.unihannover.se.processSimulation.dataGenerator.StatisticsUtil.java

/**
 * Computes the median and its confidence interval for the given data and p-value.
 * When there is enough data, the confidence interval is conservative. The caller
 * has to ensure that there is enough data (the minimum length depens only on p, not
 * on the data)./*from ww w. j a va  2s . c  om*/
 */
public static MedianWithConfidenceInterval median(double[] data, double p) {
    Arrays.sort(data);
    //When the array is really short, the intended p value can possibly not be reached. This is not checked here
    //  and has to be taken care of by the researcher.
    return new MedianWithConfidenceInterval(
            data.length % 2 == 0 ? ((data[data.length / 2 - 1] + data[data.length / 2]) / 2.0)
                    : data[data.length / 2],
            data[qBinom(p / 2.0, data.length, 0.5) - 1],
            data[Math.min(qBinom(1.0 - p / 2.0, data.length, 0.5), data.length - 1)]);
}

From source file:com.voa.weixin.utils.WeixinUtils.java

/**
 * ??//from   w w  w .  j a va2  s.  c o  m
 * @param signature
 * @param timestamp
 * @param nonce
 * @param echostr
 * @param token
 * @return
 */
public static boolean checkAuthentication(String signature, String timestamp, String nonce, String echostr,
        String token) {
    //String result = "";
    boolean result = false;
    // ??
    String[] ArrTmp = { token, timestamp, nonce };
    // ????
    Arrays.sort(ArrTmp);
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < ArrTmp.length; i++) {
        sb.append(ArrTmp[i]);
    }
    // ??SHA-1
    String pwd = "";
    try {
        pwd = DigestUtils.sha1Hex(sb.toString());

    } catch (Exception e) {
        e.printStackTrace();
    }
    result = pwd.equals(signature);
    return result;
}

From source file:com.roncoo.pay.permission.utils.RonCooSignUtil.java

/**
 * @param timeStamp//  ww  w  .  j  a va2s  . c o  m
 * @param userName
 * @param userPwd
 * @return
 */
public static String getSign(String token, long timeStamp, String userName) {

    String[] arr = new String[] { token, String.valueOf(timeStamp), userName };
    // token?timestamp?nonce?userPwd???
    Arrays.sort(arr);
    StringBuilder content = new StringBuilder();
    for (int i = 0; i < arr.length; i++) {
        content.append(arr[i]);
    }
    MessageDigest md = null;
    String tmpStr = null;

    try {
        md = MessageDigest.getInstance("SHA-1");
        // ??sha1
        byte[] digest = md.digest(content.toString().getBytes());
        tmpStr = byteToStr(digest);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e);
    }
    return tmpStr;
}

From source file:Main.java

/**
 * //from   w  ww .j  a  v  a2s  . co  m
 * pre: takes a valid resultSet List, a columnName to group by, a valid
 * comparator for the columnName's value<br>
 * post: separates the list into a List of List with each sub-list having the
 * same columnName value sorted by the keyComparator
 * 
 * @param resultSet
 * @param columnName
 * @param keyComparator
 * @return null if resultSet is null
 */
@SuppressWarnings("rawtypes")
public static List<List<Map>> splitSqlList(List<Map> resultSet, String columnName, Comparator keyComparator) {

    if (resultSet == null)
        return null;

    Map<Object, List<Map>> map = sqlMapListToMap(resultSet, columnName);
    Set keys = map.keySet();
    Object[] keyArray = keys.toArray();
    if (keyComparator == null) {
        Arrays.sort(keyArray);
    } else {
        Arrays.sort(keyArray, keyComparator);
    }

    List<List<Map>> rs = new ArrayList<List<Map>>(keyArray.length);
    for (Object key : keyArray) {
        rs.add(map.get(key));
    }
    return rs;
}

From source file:gov.noaa.pfel.coastwatch.pointdata.MakeErdJavaZip.java

/**
 * This runs MakeErdJava.zip in <contextdirectory>
 * (usually <tomcat>/webapps/cwexperimental).
 *
 * @param args is ignored/*from w  w  w.jav a 2  s  .com*/
 */
public static void main(String args[]) throws Exception {
    String2.log("\n*** MakeErdJavaZip");
    String errorInMethod = String2.ERROR + " while generating ErdJava.zip:\n";

    //define directories
    String baseDir = SSR.getContextDirectory() + //with / separator and / at the end
            "WEB-INF/";
    String classPath = baseDir + "classes/";
    String coastWatchDir = classPath + "gov/noaa/pfel/coastwatch/";

    //make the JavaDocs
    String coastWatchClass = "gov.noaa.pfel.coastwatch.";
    String commandLine0 = "C:\\Progra~1\\Java\\jdk1.8.0_144\\bin\\javadoc" +
    //" -source 1.4" + //use 1.4 for the DODS classes that use "enum" //2011-02-22 Bob Simons changed enum to en.
            " -sourcepath " + classPath + //root directory of the classes
            " -d "; //+ baseDir + "ConvertTableDoc" + //dir to hold results
    String commandLine2 =
            //space separated .java files
            " " + coastWatchDir + "pointdata/ConvertTable.java " + coastWatchDir + "pointdata/DigirHelper.java "
                    + coastWatchDir + "pointdata/DigirIobisTDSP.java " + coastWatchDir
                    + "pointdata/DigirObisTDSP.java " + coastWatchDir + "pointdata/Table.java " + coastWatchDir
                    + "TimePeriods.java " + coastWatchDir + "ValidateDataSetProperties.java " +
                    //recursively searched packages
                    "-classpath " + //';' separated;  //external packages are important here
                    //baseDir + "lib/activation.jar;" +
                    baseDir + "lib/commons-compress.jar;" +
                    //baseDir + "lib/commons-discovery.jar;" + 
                    //baseDir + "lib/commons-codec-1.3.jar;" +     //these 3 now in netcdfAll-latest
                    //baseDir + "lib/commons-httpclient-3.0.1.jar;" + 
                    //baseDir + "lib/commons-logging-1.1.jar;" + 
                    baseDir + "lib/mail.jar;" + baseDir + "lib/slf4j.jar;" + baseDir
                    + "lib/netcdfAll-latest.jar " + //space after last one
                    "-subpackages " + //the packages to be doc'd   // ':' separated
                    //adding a package? add it to dirName below, too
                    //"com.sshtools:org.apache.commons.logging:" +  //this external package not very relevant
                    "dods:" + //this external package is relevant
                    "com.cohort.array:" + "com.cohort.util:" + coastWatchClass + "griddata:" + coastWatchClass
                    + "netcheck:" + coastWatchClass + "util";

    //generate javadocs once so it will be in zip file
    String tDir = baseDir + "docs/ErdJavaDoc"; //dir to hold results
    SSR.dosShell("del /s /q " + //delete (/s=recursive /q=quiet) previous results
            String2.replaceAll(tDir, "/", "\\"), 60);
    String checkNames[] = { "/index.html", "/com/cohort/array/DoubleArray.html",
            "/gov/noaa/pfel/coastwatch/pointdata/ConvertTable.html",
            "/gov/noaa/pfel/coastwatch/netcheck/NetCheck.html",
            "/gov/noaa/pfel/coastwatch/griddata/GenerateThreddsXml.html",
            "/gov/noaa/pfel/coastwatch/griddata/GridSaveAs.html" };
    for (int i = 0; i < checkNames.length; i++)
        Test.ensureTrue(!File2.isFile(tDir + checkNames[i]),
                errorInMethod + tDir + checkNames[i] + " not deleted.");
    try {
        String2.log(String2.toNewlineString(SSR.dosShell(commandLine0 + tDir + commandLine2, 120).toArray()));
    } catch (Exception e) {
        String2.log(MustBe.throwable(errorInMethod + "(expected) [for zip]:", e));
    }
    for (int i = 0; i < checkNames.length; i++)
        Test.ensureTrue(File2.isFile(tDir + checkNames[i]),
                errorInMethod + tDir + checkNames[i] + " not found.");

    //generate javadocs again for online use
    tDir = SSR.getContextDirectory() + //with / separator and / at the end
            "ErdJavaDoc"; //dir to hold results
    SSR.dosShell("del /s /q " + //delete (/s=recursive /q=quiet) previous results
            String2.replaceAll(tDir, "/", "\\"), 60);
    for (int i = 0; i < checkNames.length; i++)
        Test.ensureTrue(!File2.isFile(tDir + checkNames[i]),
                errorInMethod + tDir + checkNames[i] + " not deleted.");
    try {
        String2.log(String2.toNewlineString(SSR.dosShell(commandLine0 + tDir + commandLine2, 120).toArray()));
    } catch (Exception e) {
        String2.log(MustBe.throwable(errorInMethod + " (expected) [for online]:", e));
    }
    for (int i = 0; i < checkNames.length; i++)
        Test.ensureTrue(File2.isFile(tDir + checkNames[i]),
                errorInMethod + tDir + checkNames[i] + " not found.");

    //make sure relevant files are compiled
    ConvertTable convertTable = new ConvertTable();
    GenerateThreddsXml gtdsh = new GenerateThreddsXml();
    GridSaveAs gridSaveAs = new GridSaveAs();
    ValidateDataSetProperties validateDataSetProperties = new ValidateDataSetProperties();
    DoubleCenterGrids doubleCenterGrids = new DoubleCenterGrids();
    try {
        NetCheck netCheck = new NetCheck(baseDir + "DoesntExist.xml", true);
    } catch (Exception e) {
        //don't care if error. deployment may be on another computer
        //String2.log(MustBe.throwable(
        //    "MakeNetCheckZip.main test constructors. Ignore this exception:\n", e));
    }
    //I think that is what generates the .xml.log file: delete it
    File2.delete(baseDir + "DoesntExit.xml.log");

    //delete the log created by DoubleCenterGrids.test
    File2.delete("c:/programs/_tomcat/webapps/cwexperimental/WEB-INF/DoubleCenterGrids.log");

    //delete the test file from ConvertTable
    File2.delete("c:/programs/_tomcat/webapps/cwexperimental/WEB-INF/result.nc");

    //accumulate the file names to be zipped
    ArrayList<String> dirNames = new ArrayList();
    dirNames.add(baseDir + "ConvertTable.sh");
    dirNames.add(baseDir + "ConvertTable.bat");
    dirNames.add(baseDir + "DoubleCenterGrids.sh");
    dirNames.add(baseDir + "GridSaveAs.sh");
    dirNames.add(baseDir + "GridSaveAs.bat");
    dirNames.add(baseDir + "GenerateOceanwatchThreddsXml.sh");
    dirNames.add(baseDir + "GenerateOtterThreddsXml.sh");
    dirNames.add(baseDir + "GenerateThredds1ThreddsXml.sh");
    dirNames.add(baseDir + "GenerateThreddsXml.sh");
    dirNames.add(baseDir + "incompleteMainCatalog.xml");
    dirNames.add(baseDir + "iobis.m");
    dirNames.add(baseDir + "NetCheck.sh");
    dirNames.add(baseDir + "NetCheck.bat");
    dirNames.add(baseDir + "NetCheck.xml");
    dirNames.add(baseDir + "obis.m");
    dirNames.add(baseDir + "QN2005193_2005193_ux10_westus.grd");
    dirNames.add(baseDir + "ValidateDataSetProperties.sh");
    dirNames.add(baseDir + "ValidateDataSetProperties.bat");
    //dirNames.add(baseDir + "lib/activation.jar");
    dirNames.add(baseDir + "lib/commons-compress.jar");
    //dirNames.add(baseDir + "lib/commons-discovery.jar"); 
    //dirNames.add(baseDir + "lib/commons-codec-1.3.jar"); //these 3 are now in netcdfAll-latest
    //dirNames.add(baseDir + "lib/commons-httpclient-3.0.1.jar"); 
    //dirNames.add(baseDir + "lib/commons-logging-1.1.jar"); 
    dirNames.add(baseDir + "lib/mail.jar");
    dirNames.add(baseDir + "lib/netcdfAll-latest.jar");
    dirNames.add(baseDir + "lib/slf4j.jar");
    String2.add(dirNames, RegexFilenameFilter.recursiveFullNameList(baseDir + "docs/ErdJavaDoc/", ".+", false)); //javadocs
    String2.add(dirNames, RegexFilenameFilter.recursiveFullNameList(baseDir + "classes/dods/", ".+", false));
    String2.add(dirNames,
            RegexFilenameFilter.recursiveFullNameList(baseDir + "classes/com/sshtools/", ".+", false));
    String2.add(dirNames,
            RegexFilenameFilter.recursiveFullNameList(baseDir + "classes/org/jdom/", ".+", false));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(baseDir + "classes/com/cohort/array/", ".+"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(baseDir + "classes/com/cohort/util/", ".+"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir, "CWBrowser.properties"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir, "BrowserDefault.properties"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir, "DataSet.properties"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir, "LICENSE\\.txt"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir, "OneOf.+"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir, "TimePeriods.+"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir, "ValidateDataSetProperties.+"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir + "griddata/", ".+"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir + "hdf/", ".+"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir + "netcheck/", ".+"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir + "pointdata/", "ConvertTable.+"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir + "pointdata/", "Digir.+"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir + "pointdata/", "Table.+"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir + "pointdata/", "LICENSE\\.txt"));
    String2.add(dirNames, RegexFilenameFilter.fullNameList(coastWatchDir + "util/", ".+"));

    //convert to sorted String array
    String dirNameArray[] = dirNames.toArray(new String[0]);
    Arrays.sort(dirNameArray);
    //String2.log(String2.toNewlineString(dirNameArray));

    //make the zip file
    String zipName = SSR.getContextDirectory() + //with / separator and / at the end
            "ErdJava.zip";
    String2.log("MakeErdJavaZip is making " + zipName + ".");
    File2.delete(zipName);
    SSR.zip(zipName, dirNameArray, 60, baseDir);
    String2.log("\nMakeErdJavaZip successfully finished making " + zipName + ".\nnFiles=" + dirNames.size());
}

From source file:cn.edu.pku.cbi.mosaichunter.math.WilcoxonRankSumTest.java

public static double twoSided(double[] x, double[] y) {
    int nx = x.length;
    int ny = y.length;
    double[] v = new double[nx + ny];
    Arrays.sort(x);
    System.arraycopy(x, 0, v, 0, nx);
    System.arraycopy(y, 0, v, nx, ny);
    Arrays.sort(v);// www.  j  av  a 2  s.  com

    double[] u = new double[v.length];
    double[] rank = new double[v.length];
    int[] cnt = new int[v.length];
    int n = 0;
    for (int i = 0; i < v.length; ++i) {
        if (i == 0 || v[i] - v[i - 1] > EPS) {
            u[n] = v[i];
            n++;
        }
        cnt[n - 1]++;
        rank[n - 1] += i + 1;
    }
    for (int i = 0; i < n; ++i) {
        rank[i] /= cnt[i];
    }

    double stats = 0;
    int j = 0;
    for (int i = 0; i < nx; ++i) {
        while (x[i] > u[j] + EPS) {
            j++;
        }
        stats += rank[j];
    }
    stats -= nx * (nx + 1) / 2;
    double z = stats - x.length * y.length / 2;

    double tmp = 0;
    for (int i = 0; i < n; ++i) {
        tmp += (double) cnt[i] * cnt[i] * cnt[i] - cnt[i];
    }
    double sigma = Math.sqrt(((double) nx * ny / 12) * (nx + ny + 1 - tmp / (nx + ny) / (nx + ny - 1)));
    if (z > EPS) {
        z -= 0.5;
    } else if (z < -EPS) {
        z += 0.5;
    }
    z /= sigma;

    double p = new NormalDistribution().cumulativeProbability(z);
    double pValue = 2 * Math.min(p, 1 - p);
    if (Double.isNaN(pValue)) {
        return 1;
    }
    return pValue;
}

From source file:de.unisb.cs.st.javaslicer.slicing.Slicer.java

public static void main(String[] args) throws InterruptedException {
    Options options = createOptions();//from w  ww . ja v  a 2s .c  om
    CommandLineParser parser = new GnuParser();
    CommandLine cmdLine;

    try {
        cmdLine = parser.parse(options, args, true);
    } catch (ParseException e) {
        System.err.println("Error parsing the command line arguments: " + e.getMessage());
        return;
    }

    if (cmdLine.hasOption('h')) {
        printHelp(options, System.out);
        System.exit(0);
    }

    String[] additionalArgs = cmdLine.getArgs();
    if (additionalArgs.length != 2) {
        printHelp(options, System.err);
        System.exit(-1);
    }
    // ?? 1. ? 2.?
    File traceFile = new File(additionalArgs[0]);
    String slicingCriterionString = additionalArgs[1];

    Long threadId = null;
    if (cmdLine.hasOption('t')) { // the interesting thread id for slicing 
        try {
            threadId = Long.parseLong(cmdLine.getOptionValue('t'));
        } catch (NumberFormatException e) {
            System.err.println("Illegal thread id: " + cmdLine.getOptionValue('t'));
            System.exit(-1);
        }
    }

    TraceResult trace;
    try {
        trace = TraceResult.readFrom(traceFile);
    } catch (IOException e) {
        System.err.format("Could not read the trace file \"%s\": %s%n", traceFile, e);
        System.exit(-1);
        return;
    }

    List<SlicingCriterion> sc = null; // a list contains the instruction's info corresponds to the slicing criterion
    //slicingCriterionString get from additionalArgs[1]
    try {
        sc = StaticSlicingCriterion.parseAll(slicingCriterionString, trace.getReadClasses());
    } catch (IllegalArgumentException e) {
        System.err.println("Error parsing slicing criterion: " + e.getMessage());
        System.exit(-1);
        return;
    }

    List<ThreadId> threads = trace.getThreads(); // the threads that generate the traces
    if (threads.size() == 0) {
        System.err.println("The trace file contains no tracing information.");
        System.exit(-1);
    }

    // threadID is used to mark the interesting thread
    ThreadId tracing = null;
    for (ThreadId t : threads) {
        if (threadId == null) {
            if ("main".equals(t.getThreadName())
                    && (tracing == null || t.getJavaThreadId() < tracing.getJavaThreadId()))
                tracing = t;
        } else if (t.getJavaThreadId() == threadId.longValue()) {
            tracing = t;
        }
    }

    if (tracing == null) {
        System.err.println(threadId == null ? "Couldn't find the main thread."
                : "The thread you specified was not found.");
        System.exit(-1);
        return;
    }

    long startTime = System.nanoTime();
    Slicer slicer = new Slicer(trace);
    if (cmdLine.hasOption("progress")) // the parameter process indicates that we need to monitor the process of slicing
        slicer.addProgressMonitor(new ConsoleProgressMonitor());
    boolean multithreaded;
    if (cmdLine.hasOption("multithreaded")) {
        String multithreadedStr = cmdLine.getOptionValue("multithreaded");
        multithreaded = ("1".equals(multithreadedStr) || "true".equals(multithreadedStr));
    } else {
        multithreaded = Runtime.getRuntime().availableProcessors() > 1;
    }

    boolean warnUntracedMethods = cmdLine.hasOption("warn-untraced"); // give some warns when encounters untraced functions

    //sliceInstructionCollector implements the interface slice visitor, which travel the dependence graph
    SliceInstructionsCollector collector = new SliceInstructionsCollector(); // the collector is used to collect the instructions in the dependence graph according to the slice criterion. 
    slicer.addSliceVisitor(collector);
    // zhushi by yhb

    if (warnUntracedMethods)
        slicer.addUntracedCallVisitor(new PrintUniqueUntracedMethods()); // the user need the untraced function info, so add untraced call visitor

    slicer.process(tracing, sc, multithreaded); //----------------------the key process of slicing!!!
    Set<InstructionInstance> slice = collector.getDynamicSlice(); // return the slice result from the collector
    long endTime = System.nanoTime();

    Instruction[] sliceArray = slice.toArray(new Instruction[slice.size()]); // convert the set to array
    Arrays.sort(sliceArray); // in order to ensure the sequence of dynamic execution

    // show the slicing result
    System.out.println("The dynamic slice for criterion " + sc + ":");
    for (Instruction insn : sliceArray) {
        System.out.format((Locale) null, "%s.%s:%d %s%n", insn.getMethod().getReadClass().getName(),
                insn.getMethod().getName(), insn.getLineNumber(), insn.toString());
    }
    System.out.format((Locale) null, "%nSlice consists of %d bytecode instructions.%n", sliceArray.length);
    System.out.format((Locale) null, "Computation took %.2f seconds.%n", 1e-9 * (endTime - startTime));
}

From source file:com.opengamma.maths.lowlevelapi.functions.utilities.Sort.java

/**
 * Sorts values statelessly in ascending order
 * @param v1 the values to sort (a native backed array)
 * @return tmp the sorted values//from   w w w  .j ava 2s  . c o  m
 */
public static long[] stateless(long[] v1) {
    Validate.notNull(v1);
    long[] tmp = Arrays.copyOf(v1, v1.length);
    Arrays.sort(tmp);
    return tmp;
}

From source file:Main.java

static String composeFilesString(final String dirPath, final List<String> subDirPaths, final String pattern,
        int skip) {
    final StringBuilder sb = new StringBuilder();
    final List<File> allFiles = new ArrayList<>();
    final FilenameFilter filter = new FilenameFilter() {
        @Override//from w ww  .  java 2  s.co m
        public boolean accept(File dir, String name) {
            return name.matches(pattern);
        }
    };
    for (final String subDirPath : subDirPaths) {
        final File subDir = new File(dirPath, subDirPath);
        final File[] files = subDir.listFiles(filter);
        if (files == null) {
            throw new RuntimeException(String.format("%s directory does not exist", subDir.getPath()));
        }
        Arrays.sort(files);
        Collections.addAll(allFiles, files);
    }
    final int m;
    final int n;
    if (skip >= 0) {
        m = skip;
        n = allFiles.size();
    } else {
        m = 0;
        n = allFiles.size() + skip;
    }
    for (int i = m; i < n; i++) {
        final File file = allFiles.get(i);
        if (sb.length() > 0) {
            sb.append(' ');
        }
        sb.append(file.getPath());
    }
    return sb.toString();
}