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.music.Generator.java

public static void main(String[] args) throws Exception {
    Score score1 = new Score();
    Read.midi(score1, "c:/tmp/gen.midi");
    for (Part part : score1.getPartArray()) {
        System.out.println(part.getInstrument());
    }// ww  w.j  a  v  a  2s  .com
    new StartupListener().contextInitialized(null);
    Generator generator = new Generator();
    generator.configLocation = "c:/config/music";
    generator.maxConcurrentGenerations = 5;
    generator.init();

    UserPreferences prefs = new UserPreferences();
    prefs.setElectronic(Ternary.YES);
    //prefs.setSimpleMotif(Ternary.YES);
    //prefs.setMood(Mood.MAJOR);
    //prefs.setDrums(Ternary.YES);
    //prefs.setClassical(true);
    prefs.setAccompaniment(Ternary.YES);
    prefs.setElectronic(Ternary.YES);
    final ScoreContext ctx = generator.generatePiece();
    Score score = ctx.getScore();
    for (Part part : score.getPartArray()) {
        System.out.println(part.getTitle() + ": " + part.getInstrument());
    }

    System.out.println("Metre: " + ctx.getMetre()[0] + "/" + ctx.getMetre()[1]);
    System.out.println(ctx);
    Write.midi(score, "c:/tmp/gen.midi");

    new Thread(new Runnable() {

        @Override
        public void run() {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setBounds(0, 0, 500, 500);
            frame.setVisible(true);
            Part part = ctx.getParts().get(PartType.MAIN);
            Note[] notes = part.getPhrase(0).getNoteArray();
            List<Integer> pitches = new ArrayList<Integer>();
            for (Note note : notes) {
                if (!note.isRest()) {
                    pitches.add(note.getPitch());
                }
            }
            GraphicsPanel gp = new GraphicsPanel(pitches);
            frame.setContentPane(gp);
        }
    }).start();

    DecimalFormat df = new DecimalFormat("#.##");

    for (Part part : score.getPartArray()) {
        StringBuilder sb = new StringBuilder();
        printStatistics(ctx, part);
        System.out.println("------------ " + part.getTitle() + "-----------------");
        Phrase[] phrases = part.getPhraseArray();
        for (Phrase phr : phrases) {
            if (phr instanceof ExtendedPhrase) {
                sb.append("Contour=" + ((ExtendedPhrase) phr).getContour() + " ");
            }
            double measureSize = 0;
            int measures = 0;
            double totalLength = 0;
            List<String> pitches = new ArrayList<String>();
            List<String> lengths = new ArrayList<String>();
            System.out.println("((Phrase notes: " + phr.getNoteArray().length + ")");
            for (Note note : phr.getNoteArray()) {
                if (!note.isRest()) {
                    int degree = 0;
                    if (phr instanceof ExtendedPhrase) {
                        degree = Arrays.binarySearch(((ExtendedPhrase) phr).getScale().getDefinition(),
                                note.getPitch() % 12);
                    }
                    pitches.add(String.valueOf(note.getPitch() + " (" + degree + ") "));
                } else {
                    pitches.add(" R ");
                }
                lengths.add(df.format(note.getRhythmValue()));
                measureSize += note.getRhythmValue();
                totalLength += note.getRhythmValue();
                ;
                if (measureSize >= ctx.getNormalizedMeasureSize()) {
                    pitches.add(" || ");
                    lengths.add(" || " + (measureSize > ctx.getNormalizedMeasureSize() ? "!" : ""));
                    measureSize = 0;
                    measures++;
                }
            }
            sb.append(pitches.toString() + "\r\n");
            sb.append(lengths.toString() + "\r\n");
            if (part.getTitle().equals(PartType.MAIN.getTitle())) {
                sb.append("\r\n");
            }
            System.out.println("Phrase measures: " + measures);
            System.out.println("Phrase length: " + totalLength);
        }
        System.out.println(sb.toString());
    }

    MutingPrintStream.ignore.set(true);
    Write.midi(score, "c:/tmp/gen.midi");
    MutingPrintStream.ignore.set(null);
    Play.midi(score);

    generator.toMp3(FileUtils.readFileToByteArray(new File("c:/tmp/gen.midi")));
}

From source file:org.catrobat.catroid.pocketmusic.ui.TrackView.java

public void colorGridColumn(int column) {
    column = columnSanityCheck(column);//w  w w . j a  va 2 s  .c  om

    for (int i = 0; i < ROW_COUNT; i++) {
        boolean isBlackRow = Arrays.binarySearch(BLACK_KEY_INDICES, i) > -1;
        int noteColorId;
        if (isBlackRow) {
            noteColorId = R.color.opaque_turquoise_play_line_dark;
        } else {
            noteColorId = R.color.opaque_turquoise_play_line;
        }
        trackRowViews.get(i).getChildAt(column)
                .setBackgroundColor(ContextCompat.getColor(getContext(), noteColorId));
    }
}

From source file:com.orange.mmp.module.osgi.MMPOSGiContainer.java

/**
 * Reload the list of widgets//from ww  w. j  av  a2  s  .c  o m
 *
 */
public void refresh() throws MMPException {
    try {
        //Lock Thread
        this.lock.lock();
        long lastDAOUpdate = DaoManagerFactory.getInstance().getDaoManager().getDao("module")
                .getLastUpdateTimestamp();
        if (this.lastUpdate < lastDAOUpdate) {
            this.lastUpdate = lastDAOUpdate;
            //Get list of installed modules
            Module[] installedModules = (Module[]) DaoManagerFactory.getInstance().getDaoManager()
                    .getDao("module").list();
            Arrays.sort(installedModules);

            //Search removed modules
            for (Module runningModule : this.runningModules) {
                //Module removed
                if (Arrays.binarySearch(installedModules, runningModule) < 0) {
                    this.removeModule(runningModule);
                }
            }

            //Search added and updates modules
            for (Module installedModule : installedModules) {
                int moduleIndex = Arrays.binarySearch(runningModules, installedModule);
                //Module added
                if (moduleIndex < 0) {
                    this.addModule(installedModule);
                } else {
                    //Get current running module
                    Module runningModule = runningModules[moduleIndex];
                    //Check if module has been updated
                    boolean mustUpdate = false;
                    //Check version
                    if (installedModule.getVersion() != null && runningModule.getVersion() != null) {
                        mustUpdate = (installedModule.getVersion().compareTo(runningModule.getVersion()) != 0);
                    }

                    //Make update if needed
                    if (mustUpdate) {
                        this.removeModule(runningModule);
                        this.addModule(installedModule);
                    }
                }
            }
            this.runningModules = installedModules;
        }
    } finally {
        //Unlock thread
        this.lock.unlock();
    }
}

From source file:ch.algotrader.future.FutureSymbol.java

/**
 * Converts from future month symbol to month ordinal number from {@code 0} to {@code 11}.
 * @param month future month symbol//from  www . j  a  v  a2s .  c o  m
 * @return value from {@code 0} to {@code 11} in case of a successful symbol conversion,
 *  {@code -1} if case of a failure.
 */
public static int convertMonth(final String month) {
    return Arrays.binarySearch(monthEnc, month);
}

From source file:com.commonsware.android.sensor.monitor.MainActivity.java

@TargetApi(Build.VERSION_CODES.KITKAT)
private boolean isTriggerSensor(Sensor s) {
    int[] triggers = { Sensor.TYPE_SIGNIFICANT_MOTION, Sensor.TYPE_STEP_DETECTOR, Sensor.TYPE_STEP_COUNTER };

    return (Arrays.binarySearch(triggers, s.getType()) >= 0);
}

From source file:org.calrissian.accumulorecipes.commons.hadoop.GroupedKeyRangePartitioner.java

int findPartition(String group, Text key, Text[] array, int numSubBins) {

    // find the bin for the range, and guarantee it is positive
    int index = Arrays.binarySearch(array, new Text(group + NULL_BYTE + key));
    index = index < 0 ? (index + 1) * -1 : index;

    // both conditions work with numSubBins == 1, but this check is to avoid
    // hashing, when we don't need to, for speed
    if (numSubBins < 2)
        return index;
    return (key.toString().hashCode() & Integer.MAX_VALUE) % numSubBins + index * numSubBins;
}

From source file:com.esofthead.mycollab.core.utils.FileUtils.java

public static boolean isValidFileName(String name) {
    if (name.equals(".") || name.equals("..")) //$NON-NLS-1$ //$NON-NLS-2$
        return false;
    //empty names are not valid
    final int length = name.length();
    if (length == 0)
        return false;
    final char lastChar = name.charAt(length - 1);
    // filenames ending in dot are not valid
    if (lastChar == '.')
        return false;
    // file names ending with whitespace are truncated (bug 118997)
    if (Character.isWhitespace(lastChar))
        return false;
    int dot = name.indexOf('.');
    //on windows, filename suffixes are not relevant to name validity
    String basename = dot == -1 ? name : name.substring(0, dot);
    if (Arrays.binarySearch(INVALID_RESOURCE_BASENAMES, basename.toLowerCase()) >= 0)
        return false;
    return Arrays.binarySearch(INVALID_RESOURCE_FULLNAMES, name.toLowerCase()) < 0;
}

From source file:com.reactive.hzdfs.utils.EntityFinder.java

/**
 * Find implementation classes for the given interface.
 * @param <T>//  w w  w.j a v  a2 s .  c  om
 * @param basePkg
 * @param baseInterface
 * @return
 * @throws ClassNotFoundException
 */
@SuppressWarnings("unchecked")
public static <T> List<Class<T>> findImplementationClasses(String basePkg, final Class<T> baseInterface)
        throws ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.addIncludeFilter(new TypeFilter() {

        @Override
        public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                throws IOException {
            ClassMetadata aMeta = metadataReader.getClassMetadata();
            String[] intf = aMeta.getInterfaceNames();
            Arrays.sort(intf);
            return Arrays.binarySearch(intf, baseInterface.getName()) >= 0;
        }
    });

    Set<Class<?>> collection = findComponents(provider, basePkg);
    List<Class<T>> list = new ArrayList<>(collection.size());
    for (Class<?> c : collection) {
        list.add((Class<T>) c);
    }
    return list;

}

From source file:org.jblogcms.core.common.service.ItemServiceToolImpl.java

@Override
public List<I> addItemRatesToItemList(List<I> items, Long accountId) {
    if (items != null && !items.isEmpty() && accountId != null) {
        List<IRA> itemRates = itemRateRepository.getItemRates(items, accountId);

        if (!itemRates.isEmpty()) {
            long[] sortedPostRates = new long[itemRates.size()];
            int i = 0;
            for (IRA itemRate : itemRates) {
                sortedPostRates[i++] = itemRate.getItem().getId();
            }/*from w w  w  . jav a 2  s. c  o m*/
            Arrays.sort(sortedPostRates);

            for (I item : items) {
                int k = Arrays.binarySearch(sortedPostRates, item.getId());
                if (k >= 0) {
                    item.setCurrentItemRate(itemRates.get(k));
                }
            }
        }
    }
    return items;
}

From source file:edu.cmu.cs.lti.ark.fn.parsing.LocalFeatureReading.java

private List<FrameFeatures> readLocalEventsFile(InputStream inputStream,
        List<FrameFeatures> frameFeaturesList) {
    int currentFrameFeaturesIndex = 0;
    int currentFEIndex = 0;
    int[] line = readALine(inputStream);
    boolean skip = false;
    while (line.length > 0 || skip) {
        final ArrayList<int[]> temp = Lists.newArrayList();
        if (!skip) {
            while (line.length > 0) {
                temp.add(line);//  w  ww  .jav  a  2s.c o  m
                line = readALine(inputStream);
            }
        } else {
            skip = false;
        }
        final FrameFeatures f = frameFeaturesList.get(currentFrameFeaturesIndex);
        if (f.fElements.size() == 0) {
            System.out.println(f.frameName + ". No frame elements for the frame.");
            currentFrameFeaturesIndex++;
            if (currentFrameFeaturesIndex == frameFeaturesList.size()) {
                break;
            }
            currentFEIndex = 0;
            skip = true;
            continue;
        }
        final SpanAndCorrespondingFeatures[] spans = f.fElementSpansAndFeatures.get(currentFEIndex);
        for (int k = 0; k < temp.size(); k++) {
            spans[k].features = temp.get(k);
        }
        final SpanAndCorrespondingFeatures goldSpan = spans[0];
        Arrays.sort(spans);
        f.goldSpanIdxs.add(Arrays.binarySearch(spans, goldSpan));
        if (currentFEIndex == f.fElements.size() - 1) {
            currentFrameFeaturesIndex++;
            currentFEIndex = 0;
        } else {
            currentFEIndex++;
        }
        line = readALine(inputStream);
    }
    return frameFeaturesList;
}