Example usage for java.util Arrays binarySearch

List of usage examples for java.util Arrays binarySearch

Introduction

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

Prototype

public static int binarySearch(Object[] a, Object key) 

Source Link

Document

Searches the specified array for the specified object using the binary search algorithm.

Usage

From source file:com.pactera.edg.am.metamanager.extractor.adapter.extract.db.impl.DBExtractBaseServiceImpl.java

/**
 * ??Schema/*from w  ww . jav a2 s.  c o  m*/
 * 
 * @param schName
 *            Schema Name
 * @return
 */
protected boolean isMatchExtractSchema(String schName) {
    String[] extractSchemas = super.getExtractSchemas().toUpperCase().split("\\s*,\\s*");
    Arrays.sort(extractSchemas);

    return Arrays.binarySearch(extractSchemas, schName.toUpperCase()) >= 0;
}

From source file:net.ljcomputing.gson.converter.impl.GsonConverterServiceImpl.java

/**
 * Merge values.// w ww. j  ava2 s  .c  om
 *
 * @param keysFrom the keys from
 * @param to the to Object
 * @param from the from Object
 * @param ignoredProperties the ignored properties
 */
@SuppressWarnings("rawtypes")
private void mergeValues(final List keysFrom, final Object to, final Object from,
        final String... ignoredProperties) {
    final Class toClass = to.getClass();
    final Class fromClass = from.getClass();

    if (null != ignoredProperties) {
        Arrays.sort(ignoredProperties);
    }

    for (final Object key : keysFrom) {
        try {
            if (null != ignoredProperties && Arrays.binarySearch(ignoredProperties, key.toString()) < 0) {
                final Field fieldTo = findField(toClass, key.toString());
                final Field fieldFrom = findField(fromClass, key.toString());

                if (null == fieldTo) {
                    LOGGER.debug("fieldTo is null for class {}, using key {}", toClass, key);
                }

                if (null == fieldFrom) {
                    LOGGER.debug("fieldFrom is null for class {}, using key {}", fromClass, key);
                }

                setFieldValues(to, fieldTo, from, fieldFrom);
            }
        } catch (IllegalArgumentException | IllegalAccessException exception) {
            LOGGER.error("Exception occured while setting value for key '{}' -  from ['{}'] ; to ['{}']:", key,
                    from, to, exception);
        }
    }
}

From source file:com.krawler.common.util.SchedulingUtilities.java

public static int nonWorkingDays(java.util.Date stdate, java.util.Date enddate, int[] NonWorkDays,
        String[] CmpHoliDays) throws ServiceException {
    Calendar c1 = Calendar.getInstance();
    int NonWorkingDaysBetween = 0;
    Date StDate = stdate;/*from w w w . ja  va2  s  . c  o  m*/
    Date EndDate = enddate;
    try {
        c1.setTime(stdate);
        while ((stdate.compareTo(enddate)) < 0) {
            if (Arrays.binarySearch(NonWorkDays, (c1.get(Calendar.DAY_OF_WEEK) - 1)) > -1) {
                NonWorkingDaysBetween += 1;
            }
            c1.add(Calendar.DATE, 1);
            stdate = c1.getTime();
        }
        NonWorkingDaysBetween += CountCmpHolidays(StDate, EndDate, CmpHoliDays);
    } catch (Exception e) {
        throw ServiceException.FAILURE("Exception while calculating non working days : " + e.getMessage(), e);
    }
    return NonWorkingDaysBetween;
}

From source file:com.indoqa.lang.util.StringUtils.java

public static String escapeSolr(String value) {
    StringBuilder stringBuilder = new StringBuilder(value);

    for (int i = 0; i < stringBuilder.length(); i++) {
        boolean isCharacterToBeEscaped = Arrays.binarySearch(CHARACTERS_TO_BE_ESCAPED_FOR_SOLR,
                stringBuilder.charAt(i)) >= 0;
        if (isCharacterToBeEscaped) {
            stringBuilder.insert(i, '\\');
            i++;/*w w w. j a  va2  s  .co m*/
        }
    }

    return stringBuilder.toString();
}

From source file:com.opengamma.analytics.math.curve.NodalObjectsCurve.java

@Override
public U getYValue(final T x) {
    Validate.notNull(x, "x");
    final int index = Arrays.binarySearch(getXData(), x);
    if (index < 0) {
        throw new IllegalArgumentException("Curve does not contain data for x point " + x);
    }/*from  www .  jav a2  s .  c  o  m*/
    return getYData()[index];
}

From source file:dk.dma.ais.packet.AisPacketFiltersStateful.java

/**
 * Return false if this message is known to be related to a target with an IMO outside the given list.
 *///from   ww  w .j  av a 2s . co m

public Predicate<AisPacket> filterOnTargetImo(Integer[] imos) {
    final int[] list = ArrayUtils.toPrimitive(imos);
    Arrays.sort(list);
    return new Predicate<AisPacket>() {
        public boolean test(AisPacket p) {
            aisPacketStream.add(p); // Update state
            final int mmsi = getMmsi(p); // Get MMSI in question
            final int imo = getImo(mmsi); // Extract IMO no. - if we know it
            return imo < 0 ? false : Arrays.binarySearch(list, imo) >= 0;
        }

        public String toString() {
            return "imo in " + skipBrackets(Arrays.toString(list));
        }
    };
}

From source file:de.vanita5.twittnuker.util.net.ssl.AbstractCheckSignatureVerifier.java

/**
 * @deprecated (4.3.1) should not be a part of public APIs.
 *///from   ww  w  .j ava 2s  .  com
@Deprecated
public static boolean acceptableCountryWildcard(final String cn) {
    final String parts[] = cn.split("\\.");// it's
    // not an attempt to wildcard a 2TLD within a country code
    if (parts.length != 3 || parts[2].length() != 2)
        return true;
    return Arrays.binarySearch(BAD_COUNTRY_2LDS, parts[1]) < 0;
}

From source file:org.acegisecurity.acl.basic.AbstractBasicAclEntry.java

public int deletePermissions(int[] permissionsToDelete) {
    if (logger.isDebugEnabled()) {
        logger.debug("BEFORE Permissions: " + printPermissionsBlock(mask) + " " + printBinary(mask) + " ("
                + mask + ")");
    }//from w  w  w  . j a  v  a  2 s  . co m

    for (int i = 0; i < permissionsToDelete.length; i++) {
        if (logger.isDebugEnabled()) {
            logger.debug("Delete  permission: " + printPermissionsBlock(permissionsToDelete[i]) + " "
                    + printBinary(permissionsToDelete[i]) + " (" + permissionsToDelete[i] + ")");
        }

        this.mask &= ~permissionsToDelete[i];
    }

    if (Arrays.binarySearch(validPermissions, this.mask) < 0) {
        throw new IllegalArgumentException("Resulting permission set will be invalid.");
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("AFTER  Permissions: " + printPermissionsBlock(mask) + " " + printBinary(mask) + " ("
                    + mask + ")");
        }

        return this.mask;
    }
}

From source file:com.opengamma.analytics.financial.interestrate.swaption.method.SwaptionPhysicalFixedIborLMMDDMethod.java

/**
 * Computes the present value of the Physical delivery swaption.
 * @param swaption The swaption./*from w w  w.java  2 s  .c o  m*/
 * @param lmmBundle The LMM parameters and the curves.
 * @return The present value.
 */
public CurrencyAmount presentValue(final SwaptionPhysicalFixedIbor swaption,
        final LiborMarketModelDisplacedDiffusionDataBundle lmmBundle) {
    // 1. Swaption CFE preparation
    AnnuityPaymentFixed cfe = CFEC.visit(swaption.getUnderlyingSwap(), lmmBundle);
    YieldAndDiscountCurve dsc = lmmBundle.getCurve(cfe.getDiscountCurve());
    int nbCFInit = cfe.getNumberOfPayments();
    double multFact = Math.signum(cfe.getNthPayment(0).getAmount());
    boolean isCall = (cfe.getNthPayment(0).getAmount() < 0);
    double[] cftInit = new double[nbCFInit];
    double[] cfaInit = new double[nbCFInit];
    for (int loopcf = 0; loopcf < nbCFInit; loopcf++) {
        cftInit[loopcf] = cfe.getNthPayment(loopcf).getPaymentTime();
        cfaInit[loopcf] = cfe.getNthPayment(loopcf).getAmount() * -multFact;
    }
    double timeToExpiry = swaption.getTimeToExpiry();
    // 2. Model data
    int nbFactor = lmmBundle.getLmmParameter().getNbFactor();
    double[][] volLMM = lmmBundle.getLmmParameter().getVolatility();
    double[] timeLMM = lmmBundle.getLmmParameter().getIborTime();
    // 3. Link cfe dates to lmm
    int[] indCFDate = new int[nbCFInit];
    int indStart = nbCFInit - 1;
    int indEnd = 0;
    for (int loopcf = 0; loopcf < nbCFInit; loopcf++) {
        indCFDate[loopcf] = Arrays.binarySearch(timeLMM, cftInit[loopcf]);
        if (indCFDate[loopcf] < 0) {
            if (timeLMM[-indCFDate[loopcf] - 1] - cftInit[loopcf] < TIME_TOLERANCE) {
                indCFDate[loopcf] = -indCFDate[loopcf] - 1;
            } else {
                if (cftInit[loopcf] - timeLMM[-indCFDate[loopcf] - 2] < TIME_TOLERANCE) {
                    indCFDate[loopcf] = -indCFDate[loopcf] - 2;
                } else {
                    Validate.isTrue(true, "Instrument time incompatible with LMM"); //TODO really?
                }
            }
        }
        if (indCFDate[loopcf] < indStart) {
            indStart = indCFDate[loopcf];
        }
        if (indCFDate[loopcf] > indEnd) {
            indEnd = indCFDate[loopcf];
        }
    }
    int nbCF = indEnd - indStart + 1;
    double[] cfa = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCFInit; loopcf++) {
        cfa[indCFDate[loopcf] - indStart] = cfaInit[loopcf];
    }
    double[] cft = new double[nbCF];
    System.arraycopy(timeLMM, indStart, cft, 0, nbCF);

    double[] dfLMM = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        dfLMM[loopcf] = dsc.getDiscountFactor(cft[loopcf]);
    }
    double[][] gammaLMM = new double[nbCF - 1][nbFactor];
    double[] deltaLMM = new double[nbCF - 1];
    System.arraycopy(lmmBundle.getLmmParameter().getAccrualFactor(), indStart, deltaLMM, 0, nbCF - 1);
    double[] aLMM = new double[nbCF - 1];
    System.arraycopy(lmmBundle.getLmmParameter().getDisplacement(), indStart, aLMM, 0, nbCF - 1);
    double[] liborLMM = new double[nbCF - 1];
    double amr = lmmBundle.getLmmParameter().getMeanReversion();
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        gammaLMM[loopcf] = volLMM[indStart + loopcf];
        liborLMM[loopcf] = (dfLMM[loopcf] / dfLMM[loopcf + 1] - 1.0d) / deltaLMM[loopcf];
    }
    // TODO: 4. cfe modification (for roller coasters)
    double[] cfaMod = new double[nbCF + 1];
    double cfaMod0 = cfa[0];
    cfaMod[0] = cfaMod0; // modified strike
    cfaMod[1] = 0.0;
    System.arraycopy(cfa, 1, cfaMod, 2, nbCF - 1);
    // 5. Pricing algorithm
    double[] p0 = new double[nbCF];
    double[] dP = new double[nbCF];
    double b0 = 0;
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        p0[loopcf] = dfLMM[loopcf] / dfLMM[0];
        dP[loopcf] = cfaMod[loopcf + 1] * p0[loopcf];
        b0 += dP[loopcf];
    }
    double bK = -cfaMod0;
    double bM = (b0 + bK) / 2.0d;
    double meanReversionImpact = Math.abs(amr) < 1.0E-6 ? timeToExpiry
            : (Math.exp(2.0d * amr * timeToExpiry) - 1.0d) / (2.0d * amr); // To handle 0 mean reversion.
    double[] rate0Ratio = new double[nbCF - 1];
    double[][] mu0 = new double[nbCF - 1][nbFactor];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        rate0Ratio[loopcf] = (liborLMM[loopcf] + aLMM[loopcf]) / (liborLMM[loopcf] + 1 / deltaLMM[loopcf]);
    }
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        mu0[0][loopfact] = rate0Ratio[0] * gammaLMM[0][loopfact];
    }
    for (int loopcf = 1; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            mu0[loopcf][loopfact] = mu0[loopcf - 1][loopfact] + rate0Ratio[loopcf] * gammaLMM[loopcf][loopfact];
        }
    }
    double[] tau = new double[nbCF];
    double[] tau2 = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            tau2[loopcf + 1] += mu0[loopcf][loopfact] * mu0[loopcf][loopfact];
        }
        tau2[loopcf + 1] = tau2[loopcf + 1] * meanReversionImpact;
        tau[loopcf + 1] = Math.sqrt(tau2[loopcf + 1]);
    }
    double sumNum = -bM;
    double sumDen = 0;
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        sumNum += dP[loopcf] - dP[loopcf] * tau2[loopcf] / 2.0;
        sumDen += dP[loopcf] * tau[loopcf];
    }
    double xBar = sumNum / sumDen;
    double[] pM = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        pM[loopcf] = p0[loopcf] * (1 - xBar * tau[loopcf] - tau2[loopcf] / 2.0);
    }
    double[] liborM = new double[nbCF - 1];
    double[] alphaM = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        liborM[loopcf] = (pM[loopcf] / pM[loopcf + 1] - 1.0d) / deltaLMM[loopcf];
    }
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        alphaM[loopcf] = cfaMod[loopcf + 1] * pM[loopcf] / bM;
    }
    double[] rateMRatio = new double[nbCF - 1];
    double[][] muM = new double[nbCF - 1][nbFactor];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        rateMRatio[loopcf] = (liborM[loopcf] + aLMM[loopcf]) / (liborM[loopcf] + 1 / deltaLMM[loopcf]);
    }
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        muM[0][loopfact] = rateMRatio[0] * gammaLMM[0][loopfact];
    }
    for (int loopcf = 1; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            muM[loopcf][loopfact] = muM[loopcf - 1][loopfact] + rateMRatio[loopcf] * gammaLMM[loopcf][loopfact];
        }
    }
    double normSigmaM = 0;
    double[] sigmaM = new double[nbFactor];
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
            sigmaM[loopfact] += alphaM[loopcf + 1] * muM[loopcf][loopfact];
        }
        normSigmaM += sigmaM[loopfact] * sigmaM[loopfact];
    }
    double impliedBlackVol = Math.sqrt(normSigmaM * meanReversionImpact);
    EuropeanVanillaOption option = new EuropeanVanillaOption(bK, 1, isCall);
    final BlackPriceFunction blackFunction = new BlackPriceFunction();
    final BlackFunctionData dataBlack = new BlackFunctionData(b0, 1.0, impliedBlackVol);
    final Function1D<BlackFunctionData, Double> func = blackFunction.getPriceFunction(option);
    final double pv = dfLMM[0] * func.evaluate(dataBlack);
    return CurrencyAmount.of(swaption.getUnderlyingSwap().getFirstLeg().getCurrency(),
            pv * (swaption.isLong() ? 1.0 : -1.0));
}

From source file:hu.unimiskolc.iit.distsys.TestHighAvailability.java

@Test(timeout = 30000)
public void hatest() throws Exception {
    int[] successCounters = new int[Constants.availabilityLevels.length];
    int[] totalCounters = new int[Constants.availabilityLevels.length];
    final IaaSService myIaaS = ExercisesBase.getComplexInfrastructure(100);
    Repository r = myIaaS.repositories.get(0);
    VirtualAppliance va = (VirtualAppliance) r.contents().iterator().next();
    AlterableResourceConstraints totCaps = AlterableResourceConstraints.getNoResources();
    double maxNodeProcs = 0;
    for (PhysicalMachine pm : myIaaS.machines) {
        totCaps.singleAdd(pm.getCapacities());
        maxNodeProcs = Math.max(maxNodeProcs, pm.getCapacities().getRequiredCPUs());
    }//from w ww .ja  v a 2s .  c o  m
    // IaaS is prepared

    // Doing preevaluation of the infrastructure
    VirtualMachine test = myIaaS.requestVM(va, myIaaS.machines.get(0).getCapacities(), r, 1)[0];
    long preTime = Timed.getFireCount();
    Timed.simulateUntilLastEvent();
    long pastTime = Timed.getFireCount();
    long vmCreationTime = pastTime - preTime;
    test.destroy(true);
    Timed.simulateUntilLastEvent();
    Timed.resetTimed();
    // Preevaluation completed

    // Preparing the jobs for the VMs
    RepetitiveRandomTraceGenerator rrtg = new RepetitiveRandomTraceGenerator(ComplexDCFJob.class);
    // total number of jobs
    rrtg.setJobNum(1000);
    // joblist properties
    rrtg.setExecmin(10);
    rrtg.setExecmax(3600);
    rrtg.setMaxgap(0);
    rrtg.setMingap(0);
    rrtg.setMaxStartSpread(3600);
    rrtg.setMaxTotalProcs((int) totCaps.getRequiredCPUs());
    rrtg.setMinNodeProcs(1);
    rrtg.setMaxNodeprocs((int) maxNodeProcs);
    rrtg.setParallel(25);
    final List<Job> jobs = rrtg.getAllJobs();
    final long lastTermination = JobListAnalyser.getLastTerminationTime(jobs) * 1000 * 2;
    for (Job j : jobs) {
        int index = RandomUtils.nextInt(0, Constants.availabilityLevels.length);
        ((ComplexDCFJob) j).setAvailabilityLevel(Constants.availabilityLevels[index]);
        totalCounters[index]++;
    }
    // Joblist is ready

    // Preparing the scheduling
    new JobtoVMScheduler(myIaaS, jobs);
    // Prepares the faulty PMs
    new FaultInjector(120000, 1 - Constants.pmAvailability, myIaaS);
    new DeferredEvent(lastTermination) {
        // Ensures that the fault injector code terminates
        @Override
        protected void eventAction() {
            FaultInjector.simulationisComplete = true;
        }
    };

    Timed.simulateUntilLastEvent();

    for (final Job j : jobs) {
        ComplexDCFJob jobconv = (ComplexDCFJob) j;
        if (j.getRealstopTime() >= 0) {
            successCounters[Arrays.binarySearch(Constants.availabilityLevels,
                    jobconv.getAvailabilityLevel())]++;
            // More complex tests:
            // Should not allow too slow execution time
            Assert.assertTrue(
                    "Every job should run faster or equal than it was originally expected but " + j
                            + " did not do so",
                    j.getExectimeSecs() * 3 > j.getRealstopTime() - j.getRealqueueTime());
            // Should not allow too long queueing time
            Assert.assertTrue(
                    "Jobs should not queue more than a VM instantiation time but " + j + " did not do so",
                    j.getRealqueueTime() < vmCreationTime * 3);
        }
    }

    for (int i = 0; i < Constants.availabilityLevels.length; i++) {
        System.out.println(Constants.availabilityLevels[i] + " " + successCounters[i] + " " + totalCounters[i]);
        Assert.assertEquals(
                "Jobs with availability level " + Constants.availabilityLevels[i]
                        + " did not get their expected qualities",
                Constants.availabilityLevels[i], (double) successCounters[i] / totalCounters[i],
                (1 - Constants.availabilityLevels[i]) * 0.5);
    }
}