Example usage for java.util HashSet contains

List of usage examples for java.util HashSet contains

Introduction

In this page you can find the example usage for java.util HashSet contains.

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:Main.java

@SuppressLint("NewApi")
public static List<Size> getCameraSupportedVideoSizes(android.hardware.Camera camera) {
    if (camera != null) {
        if ((Build.VERSION.SDK_INT >= 11) && camera.getParameters().getSupportedVideoSizes() != null) {
            return camera.getParameters().getSupportedVideoSizes();
        } else {//  w ww  . j  av  a 2  s. c  o m
            // Video sizes may be null, which indicates that all the supported
            // preview sizes are supported for video recording.
            HashSet<String> allSizesLiteral = new HashSet<>();
            for (Camera.Size sz : camera.getParameters().getSupportedPreviewSizes()) {
                allSizesLiteral.add(String.format("%dx%d", sz.width, sz.height));
            }

            // on Samsung Galaxy 3, the supported preview sizes are too many,
            // but it seems that not all of them can be used as recording video size.
            // the following set are used by the built-in camera app.
            Camera.Size[] preferredSizes = { camera.new Size(1920, 1080), camera.new Size(1280, 720),
                    camera.new Size(720, 480), camera.new Size(640, 480), camera.new Size(320, 240) };

            List<Size> result = new ArrayList<>(preferredSizes.length);
            for (Camera.Size sz : preferredSizes) {
                if (allSizesLiteral.contains(String.format("%dx%d", sz.width, sz.height)))
                    result.add(sz);
            }

            return result;
        }
    } else {
        return null;
    }
}

From source file:com.intellij.plugins.haxe.ide.annotator.HaxeSemanticAnnotator.java

public static void check(final HaxeVarDeclaration var, final AnnotationHolder holder) {
    HaxeFieldModel field = new HaxeFieldModel(var);
    if (field.isProperty()) {
        checkProperty(field, holder);/*  ww  w.jav  a2s.  co  m*/
    }
    if (field.hasInitializer() && field.hasTypeTag()) {
        TypeTagChecker.check(field.getPsi(), field.getTypeTagPsi(), field.getInitializerPsi(), false, holder);
    }

    // Checking for variable redefinition.
    HashSet<HaxeClassModel> classSet = new HashSet<HaxeClassModel>();
    HaxeClassModel fieldDeclaringClass = field.getDeclaringClass();
    classSet.add(fieldDeclaringClass);
    while (fieldDeclaringClass != null) {
        fieldDeclaringClass = fieldDeclaringClass.getParentClass();
        if (classSet.contains(fieldDeclaringClass)) {
            break;
        } else {
            classSet.add(fieldDeclaringClass);
        }
        if (fieldDeclaringClass != null) {
            for (HaxeFieldModel parentField : fieldDeclaringClass.getFields()) {
                if (parentField.getName().equals(field.getName())) {
                    if (parentField.isStatic()) {
                        holder.createWarningAnnotation(field.getNameOrBasePsi(),
                                "Field '" + field.getName() + "' overrides a static field of a superclass.");
                    } else {
                        holder.createErrorAnnotation(field.getDeclarationPsi(),
                                "Redefinition of variable '" + field.getName()
                                        + "' in subclass is not allowed. Previously declared at '"
                                        + fieldDeclaringClass.getName() + "'.");
                    }
                    break;
                }
            }
        }
    }
}

From source file:buildcraft.transport.ItemFacade.java

private static void generateFacadeStacks() {
    HashSet<IBlockState> states = new HashSet<>();

    for (Block b : Block.REGISTRY) {
        for (int i = 0; i < 16; i++) {
            try {
                Item item = Item.getItemFromBlock(b);
                if (item != null) {
                    IBlockState state = b.getStateFromMeta(i);
                    if (!states.contains(state) && isValidFacade(state)) {
                        states.add(state);
                        allStacks.add(BuildCraftTransport.facadeItem.getFacadeForBlock(state));
                    }//from  w  w  w. j  a va2 s  .  c om
                }
            } catch (Exception e) {

            }
        }
    }

    if (BuildCraftTransport.showAllFacadesCreative) {
        previewStacks = allStacks;
    } else {
        previewStacks = new ArrayList<>();

        List<ItemStack> hollowFacades = new ArrayList<>();
        for (Block b : PREVIEW_FACADES) {
            if (isValidFacade(b.getDefaultState()) && !blacklistedFacades.contains(b.getDefaultState())) {
                ItemStack facade = BuildCraftTransport.facadeItem.getFacadeForBlock(b.getDefaultState());
                previewStacks.add(facade);
                FacadeState state = getFacadeStates(facade)[0];
                hollowFacades.add(getFacade(new FacadeState(state.state, state.wire, true)));
            }
        }
        previewStacks.addAll(hollowFacades);
    }
}

From source file:eionet.cr.web.util.JstlFunctions.java

/**
 *
 * @param objectValue//from w  w w . ja  va2 s  . c o m
 * @param pageContext
 * @return
 */
public static boolean isObjectValueDisplayed(String predicate, String objectValue, PageContext pageContext) {

    boolean result = false;
    if (predicate != null) {

        String previousPredicate = (String) pageContext.getAttribute("prevPredicate");
        HashSet<String> objectValues = (HashSet<String>) pageContext.getAttribute("displayedObjectValues");
        if (objectValues == null || previousPredicate == null || !predicate.equals(previousPredicate)) {
            objectValues = new HashSet<String>();
            pageContext.setAttribute("displayedObjectValues", objectValues);
        }

        result = objectValues.contains(objectValue);
        pageContext.setAttribute("prevPredicate", predicate);
        objectValues.add(objectValue);
    }

    return result;
}

From source file:edu.illinois.cs.cogcomp.transliteration.WikiTransliteration.java

/**
 * This recursively finds all possible alignments between word1 and word2 and populates the alignments hashmap with them.
 *
 * @param word1 word or substring of a word
 * @param word2 word or substring of a word
 * @param maxSubstringLength1//from   ww  w  . j a  va  2  s. com
 * @param maxSubstringLength2
 * @param alignments this is the result
 * @param memoizationTable
 */
public static void FindAlignments(String word1, String word2, int maxSubstringLength1, int maxSubstringLength2,
        HashMap<Production, Double> alignments, HashSet<Production> memoizationTable) {
    if (memoizationTable.contains(new Production(word1, word2)))
        return; //done

    int maxSubstringLength1f = Math.min(word1.length(), maxSubstringLength1);
    int maxSubstringLength2f = Math.min(word2.length(), maxSubstringLength2);

    for (int i = 1; i <= maxSubstringLength1f; i++) //for each possible substring in the first word...
    {
        String substring1 = word1.substring(0, i);

        for (int j = 1; j <= maxSubstringLength2f; j++) //for possible substring in the second
        {
            //if we get rid of these characters, can we still cover the remainder of word2?
            if ((word1.length() - i) * maxSubstringLength2 >= word2.length() - j
                    && (word2.length() - j) * maxSubstringLength1 >= word1.length() - i) {
                alignments.put(new Production(substring1, word2.substring(0, j)), 1.0);
                FindAlignments(word1.substring(i), word2.substring(j), maxSubstringLength1, maxSubstringLength2,
                        alignments, memoizationTable);
            }
        }
    }

    memoizationTable.add(new Production(word1, word2));
}

From source file:com.altiscale.TcpProxy.HostPort.java

private static ProxyConfiguration assembleConfigFromCommandLine(Options options, String[] args) {
    CommandLine commandLine = null;// w w w .jav  a2s.  c  o  m
    try {
        commandLine = new GnuParser().parse(options, args);
    } catch (org.apache.commons.cli.ParseException e) {
        LOG.info("Parsing exception" + e.getMessage());
        printHelp(options);
        System.exit(1);
    }

    if (commandLine.hasOption("h")) {
        printHelp(options);
        System.exit(1);
    }

    if (commandLine.hasOption("version")) {
        LOG.info("Transfer Accelerator Version " + getProxyVersion());
        System.exit(1);
    }

    if (commandLine.hasOption("verbose")) {
        LogManager.getRootLogger().setLevel(Level.DEBUG);
    }

    ProxyConfiguration conf = new ProxyConfiguration();

    if (commandLine.hasOption("port")) {
        conf.listeningPort = Integer.parseInt(commandLine.getOptionValue("port"));
    }

    if (commandLine.hasOption("webstatus_port")) {
        conf.statusPort = Integer.parseInt(commandLine.getOptionValue("webstatus_port"));
    }

    // Maybe add jumphost.
    HostPort jumphostSshd = null;
    if (commandLine.hasOption("jumphost")) {
        String jumphostString = commandLine.getOptionValue("jumphost");
        try {
            jumphostSshd = conf.parseServerString(jumphostString);
        } catch (URISyntaxException e) {
            LOG.error("Server path parsing exception for jumphost: " + e.getMessage());
            printHelp(options);
            System.exit(1);
        }
    }

    // Add jumphostServer if we have a jumphost.
    HostPort jumphostServer = null;
    if (commandLine.hasOption("jumphost_server")) {
        if (!commandLine.hasOption("jumphost")) {
            LOG.error("You need to specify jumphost if you specify jumphost_server.");
            printHelp(options);
            System.exit(1);
        }
        String jumphostServerString = commandLine.getOptionValue("jumphost_server");
        try {
            jumphostServer = conf.parseServerString(jumphostServerString);
            if (jumphostServer.port == -1) {
                throw new URISyntaxException(jumphostServerString, "Jumphost server parameter missing port.");
            }
        } catch (URISyntaxException e) {
            LOG.error("Server path parsing exception for jumphost_server:" + e.getMessage());
            printHelp(options);
            System.exit(1);
        }
    }

    // Maybe add jumphostUser if we have a jumphost.
    String jumphostUser = null;
    if (commandLine.hasOption("jumphost_user")) {
        if (!commandLine.hasOption("jumphost")) {
            LOG.error("You need to specify jumphost if you specify jumphost_user.");
            printHelp(options);
            System.exit(1);
        }
        jumphostUser = commandLine.getOptionValue("jumphost_user");
    }

    // Maybe add jumphostCredentials if we have a jumphost.
    String jumphostCredentials = null;
    if (commandLine.hasOption("jumphost_credentials")) {
        if (!commandLine.hasOption("jumphost")) {
            LOG.error("You need to specify jumphost if you specify jumphost_credentials.");
            printHelp(options);
            System.exit(1);
        }
        jumphostCredentials = commandLine.getOptionValue("jumphost_credentials");
    }

    // Maybe set jumphostCompression if we have a jumphost.
    boolean jumphostCompression = false;
    if (commandLine.hasOption("jumphost_compression")) {
        if (!commandLine.hasOption("jumphost")) {
            LOG.error("You need to specify jumphost if you specify jumphost_compression.");
            printHelp(options);
            System.exit(1);
        }
        jumphostCompression = true;
    }

    // Maybe add jumphostCiphers if we have a jumphost.
    String jumphostCiphers = null;
    if (commandLine.hasOption("jumphost_ciphers")) {
        if (!commandLine.hasOption("jumphost")) {
            LOG.error("You need to specify jumphost if you specify jumphost_ciphers.");
            printHelp(options);
            System.exit(1);
        }
        jumphostCiphers = commandLine.getOptionValue("jumphost_ciphers");
    }

    // Maybe add sshBinary if we have a jumphost.
    String sshBinary = null;
    if (commandLine.hasOption("ssh_binary")) {
        if (!commandLine.hasOption("jumphost")) {
            LOG.error("You need to specify jumphost if you specify ssh_binary.");
            printHelp(options);
            System.exit(1);
        }
        sshBinary = commandLine.getOptionValue("ssh_binary");
    }
    boolean openInterfaces = false;
    if (commandLine.hasOption("openInterfaces")) {
        openInterfaces = true;
    }

    // Add jumphost to the config.
    if (null != jumphostSshd && null != jumphostServer) {
        conf.jumphost = new JumpHost(jumphostSshd, jumphostServer, jumphostUser, jumphostCredentials,
                jumphostCompression, jumphostCiphers, sshBinary, openInterfaces);
    }

    if (!commandLine.hasOption("num_servers") && !commandLine.hasOption("servers")) {
        LOG.error("You need to specify one of the num_servers or servers flags.");
        printHelp(options);
        System.exit(1);
    }

    if (commandLine.hasOption("num_servers") && commandLine.hasOption("servers")) {
        LOG.error("You need to specify one of the num_servers or servers flags, not both.");
        printHelp(options);
        System.exit(1);
    }

    // Add servers.
    if (commandLine.hasOption("num_servers")) {
        try {
            int num_servers = Integer.parseInt(commandLine.getOptionValue("num_servers"));
            if (num_servers > TcpProxyServer.MAX_NUM_SERVERS) {
                throw new Exception("Please specify -servers.");
            }
            for (int i = 0; i < num_servers; i++) {
                conf.parseServerStringAndAdd("localhost:" + (TcpProxyServer.START_PORT_RANGE + i));
            }
        } catch (Exception e) {
            LOG.error("num_servers parsing exception " + e.getMessage());
            printHelp(options);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("servers")) {
        String[] servers = commandLine.getOptionValues("servers");
        try {
            for (String server : servers) {
                conf.parseServerStringAndAdd(server);
            }
        } catch (URISyntaxException e) {
            LOG.error("Server path parsing exception " + e.getMessage());
            printHelp(options);
            System.exit(1);
        }
    }

    // Maybe set load balancer.
    if (commandLine.hasOption("load_balancer")) {
        HashSet<String> loadBalancers = new HashSet<String>(
                Arrays.asList("RoundRobin", "LeastUsed", "UniformRandom"));
        conf.loadBalancerString = commandLine.getOptionValue("load_balancer");
        if (!loadBalancers.contains(conf.loadBalancerString)) {
            LOG.error("Bad load_balancer value.");
            printHelp(options);
            System.exit(1);
        }
    }
    return conf;
}

From source file:RemoveDuplicateFiles.java

public static void addActionHandlers(Stage primaryStage) {
    //Sort Files Button Pressed.
    sortFilesButton.setOnAction((ActionEvent event) -> {
        //Move to the SortFiles window
        new FileSort(primaryStage);
    });//from   w  w w. j  a  va 2  s.  com

    //Batch Rename Button Pressed
    batchRenameButton.setOnAction((ActionEvent event) -> {
        //Move to the BatchRename window
        new BatchRename(primaryStage);
    });

    //Action Handler: remove the duplicate files in the directory.
    rmvButton.setOnAction((ActionEvent event) -> {
        //Clear the actionTarget
        actionTarget.setFill(Color.BLACK);
        actionTarget.setText("");

        //Make sure we have the right path
        selectedDirectory = new File(address.getText());

        if (selectedDirectory != null && selectedDirectory.isDirectory()) {
            //Grab the list of file types from the textbox
            String[] extensions = UtilFunctions.parseFileTypes(fileTypes.getText());

            //Grab the list of files in the selectedDirectory
            List<File> files = (List<File>) FileUtils.listFiles(selectedDirectory, extensions, true);
            HashSet<String> hashCodes = new HashSet<>();
            ArrayList<File> duplicates = new ArrayList<>();

            //Progress reporting values
            actionTarget.setFill(Color.BLACK);
            int totalFileCount = files.size();
            int filesProcessed = 0;

            //Find the duplicate files
            for (File f : files) {
                try {
                    //Update the status
                    filesProcessed++;
                    actionTarget.setText("Processing file " + filesProcessed + " of " + totalFileCount);

                    //Grab the file's hash code
                    String hash = UtilFunctions.makeHash(f);

                    //If we already have a file matching that hash code
                    if (hashCodes.contains(hash)) {
                        //Add the file to the list of files to be deleted
                        duplicates.add(f);
                    } else {
                        hashCodes.add(hash);
                    }

                } catch (Exception except) {
                }
            } //End for

            //Progress reporting
            filesProcessed = 0;
            totalFileCount = duplicates.size();
            Iterator<File> itr = duplicates.iterator();

            //Remove the duplicate files
            while (itr.hasNext()) {
                try {
                    //Update the status
                    filesProcessed++;
                    actionTarget.setText("Deleting file " + filesProcessed + " of " + totalFileCount);

                    //Grab the file
                    File file = itr.next();

                    if (!file.delete()) {
                        JOptionPane.showMessageDialog(null, file.getPath() + " not deleted.");
                    }

                } catch (Exception except) {
                }
            } //End while

            actionTarget.setText("Deleted: " + filesProcessed);

        } else {
            actionTarget.setFill(Color.FIREBRICK);
            actionTarget.setText("Invalid directory.");
        }
    });

}

From source file:at.treedb.util.SevenZip.java

/**
 * Extracts some data (files and directories) from the archive without
 * extracting the whole archive.//from   ww  w . java2s  .c om
 * 
 * @param archive
 *            7-zip archive
 * @param fileList
 *            file extraction list, a path with an ending '/' denotes a
 *            directory
 * @return file list as a map file name/file data
 * @throws IOException
 */
public static HashMap<String, byte[]> exctact(File archive, String... fileList) throws IOException {
    HashSet<String> fileSet = new HashSet<String>();
    ArrayList<String> dirList = new ArrayList<String>();
    for (String f : fileList) {
        if (!f.endsWith("/")) {
            fileSet.add(f);
        } else {
            dirList.add(f);
        }
    }
    HashMap<String, byte[]> resultMap = new HashMap<String, byte[]>();
    SevenZFile sevenZFile = new SevenZFile(archive);
    do {
        SevenZArchiveEntry entry = sevenZFile.getNextEntry();
        if (entry == null) {
            break;
        }
        // convert window path to unix style
        String name = entry.getName().replace('\\', '/');
        if (!entry.isDirectory()) {
            boolean storeFile = false;
            if (fileSet.contains(name)) {
                storeFile = true;
            } else {
                // search directories
                for (String s : dirList) {
                    if (name.startsWith(s)) {
                        storeFile = true;
                        break;
                    }
                }
            }
            // store the file
            if (storeFile) {
                int size = (int) entry.getSize();
                byte[] data = new byte[size];
                sevenZFile.read(data, 0, size);
                resultMap.put(name, data);
                // in this case we can finish the extraction loop
                if (dirList.isEmpty() && resultMap.size() == fileSet.size()) {
                    break;
                }
            }
        }
    } while (true);
    sevenZFile.close();
    return resultMap;
}

From source file:edu.harvard.i2b2.analysis.queryClient.CRCQueryClient.java

public static String getlldString(ArrayList<TimelineRow> tlrows, String patientRefId, int minPatient,
        int maxPatient, boolean bDisplayAll, boolean writeFile, boolean displayDemographics,
        ExplorerC explorer) {/*from  www .ja va2  s.c o  m*/

    try {
        HashSet<String> conceptPaths = new HashSet<String>();
        // HashSet<String> providerPaths = new HashSet<String>();
        // HashSet<String> visitPaths = new HashSet<String>();
        ArrayList<PDOItem> items = new ArrayList<PDOItem>();

        for (int i = 0; i < tlrows.size(); i++) {
            for (int j = 0; j < tlrows.get(i).pdoItems.size(); j++) {
                PDOItem pdoItem = tlrows.get(i).pdoItems.get(j);
                String path = pdoItem.fullPath;

                if (conceptPaths.contains(path)) {
                    continue;
                }
                conceptPaths.add(path);
                // for(int k=0; k<pdoItem.valDisplayProperties.size(); k++)
                // {
                items.add(pdoItem);
                // }
            }
        }

        PDORequestMessageModel pdoFactory = new PDORequestMessageModel();
        String pid = null;
        if (patientRefId.equalsIgnoreCase("All")) {
            pid = "-1";
        } else {
            pid = patientRefId;
        }
        String xmlStr = pdoFactory.requestXmlMessage(items, pid, new Integer(minPatient),
                new Integer(maxPatient), false);
        // explorer.lastRequestMessage(xmlStr);

        String result = null;// sendPDOQueryRequestREST(xmlStr);
        if (System.getProperty("webServiceMethod").equals("SOAP")) {
            result = CRCQueryClient.sendPDOQueryRequestSOAP(xmlStr);
        } else {
            result = CRCQueryClient.sendPDOQueryRequestREST(xmlStr);
        }

        if (result == null || result.equalsIgnoreCase("memory error")) {
            return result;
        }
        explorer.lastResponseMessage(result);

        return TimelineFactory.generateTimelineData(result, tlrows, writeFile, bDisplayAll,
                displayDemographics);
    }
    /*
     * catch(org.apache.axis2.AxisFault e) { e.printStackTrace();
     * java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
     * JOptionPane.showMessageDialog(null,
     * "Trouble with connection to the remote server, " +
     * "this is often a network error, please try again", "Network Error",
     * JOptionPane.INFORMATION_MESSAGE); } });
     * 
     * return null; }
     */
    catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.ng200.openolympus.controller.contest.ContestTaskRemovalController.java

@PreAuthorize(SecurityExpressionConstants.IS_ADMIN)
@CacheEvict(value = "contests", key = "#contest.id")
@RequestMapping(value = "/api/contest/{contest}/removeTask", method = RequestMethod.DELETE)
public void removeTask(@PathVariable(value = "contest") final Contest contest,
        @RequestParam(value = "task") final Task task, final Model model) {
    Assertions.resourceExists(contest);//from w  w  w .j  av a  2 s  . c o  m
    Assertions.resourceExists(task);
    HashSet<Task> tasks = new HashSet<>(contest.getTasks());
    if (tasks.contains(task)) {
        tasks.remove(task);
        contest.setTasks(tasks);
        this.contestService.saveContest(contest);
    }
}