Example usage for java.util Stack Stack

List of usage examples for java.util Stack Stack

Introduction

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

Prototype

public Stack() 

Source Link

Document

Creates an empty Stack.

Usage

From source file:de.codesourcery.gittimelapse.Main.java

public static void main(String[] args) throws IOException, RevisionSyntaxException, GitAPIException {
    final Stack<String> argStack = new Stack<>();

    final String testFile = "/home/tgierke/workspace/voipmanager/voipmngr/voipmngr/build.xml";
    if (ArrayUtils.isEmpty(args) && new File(testFile).exists()) {
        argStack.push(testFile);/*from  w w w . ja v  a2s.c o m*/
    }

    File file = null;
    while (!argStack.isEmpty()) {
        if ("-d".equals(argStack.peek())) {
            DEBUG_MODE = true;
            argStack.pop();
        } else {
            file = new File(argStack.pop());
        }
    }

    if (file == null) {
        System.err.println("ERROR: Invalid command line.");
        System.err.println("Usage: [-d] <versioned file>\n");
        return;
    }

    final GitHelper helper = new GitHelper(file.getParentFile());

    MyFrame frame = new MyFrame(file, helper);
    frame.setPreferredSize(new Dimension(640, 480));
    frame.pack();
    frame.setVisible(true);
}

From source file:FlightInfo.java

public static void main(String args[]) {
    String to, from;//from   ww  w  .j a  v  a2s  . c  om
    Optimal ob = new Optimal();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    boolean done = false;
    FlightInfo f;

    ob.setup();

    try {
        System.out.print("From? ");
        from = br.readLine();
        System.out.print("To? ");
        to = br.readLine();
        do {
            ob.isflight(from, to);

            if (ob.btStack.size() == 0)
                done = true;
            else {
                ob.route(to);
                ob.btStack = new Stack();
            }
        } while (!done);

        // Display optimal solution.
        if (ob.optimal != null) {
            System.out.println("Optimal solution is: ");

            int num = ob.optimal.size();
            for (int i = 0; i < num; i++) {
                f = (FlightInfo) ob.optimal.pop();
                System.out.print(f.from + " to ");
            }

            System.out.println(to);
            System.out.println("Distance is " + ob.minDist);
        }
    } catch (IOException exc) {
        System.out.println("Error on input.");
    }
}

From source file:StringReverse.java

public static void main(String[] argv) {
    //+/*  w w  w .j a  v a2  s .c o  m*/
    String s = "Father Charles Goes Down And Ends Battle";

    // Put it in the stack frontwards
    Stack myStack = new Stack();
    StringTokenizer st = new StringTokenizer(s);
    while (st.hasMoreTokens())
        myStack.push(st.nextElement());

    // Print the stack backwards
    System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
    while (!myStack.empty()) {
        System.out.print(myStack.pop());
        System.out.print(' ');
    }
    System.out.println('"');
    //-
}

From source file:edu.usc.squash.Main.java

public static void main(String[] args) {
    Stack<Module> modulesStack;
    Module module;/*w w  w  .jav  a 2s .c  o m*/

    if (parseInputs(args) == false) {
        System.exit(-1); //The input files do not exist
    }

    String separator = "----------------------------------------------";
    System.out.println("Squash v2.0");
    System.out.println(separator);
    long start = System.currentTimeMillis();

    // Parsing the input library
    Library library = QLib.readLib(libraryPath);
    library.setCurrentECC(currentECC);

    HashMap<String, Module> modules = parseQASMHF(library);
    Module mainModule = modules.get("main");

    //Finding max{A_L_i}
    int childModulesLogicalAncillaReq;
    int moduleAncillaReq;

    modulesStack = new Stack<Module>();

    modulesStack.add(mainModule);
    while (!modulesStack.isEmpty()) {
        module = modulesStack.peek();
        if (!module.isVisited() && module.isChildrenVisited()) {
            //Finding the maximum 
            childModulesLogicalAncillaReq = 0;
            for (Module child : module.getDFG().getModules()) {
                childModulesLogicalAncillaReq = Math.max(childModulesLogicalAncillaReq, child.getAncillaReq());
            }
            moduleAncillaReq = module.getAncillaQubitNo() + childModulesLogicalAncillaReq;
            module.setAncillaReq(moduleAncillaReq);
            //            System.out.println("Module "+module.getName()+" requires "+moduleAncillaReq+" ancilla.");

            modulesStack.pop();
            module.setVisited();
        } else if (module.isVisited()) {
            modulesStack.pop();
        } else if (!module.isChildrenVisited()) {
            modulesStack.addAll(module.getDFG().getModules());
            module.setChildrenVisited();
        }
    }

    int totalLogicalAncilla = mainModule.getAncillaReq();

    System.out.println("A_L_i_max: " + totalLogicalAncilla);

    final int Q_L = mainModule.getDataQubitNo();

    /* 
     * In order traversal of modules
     */
    //Making sure all of the modules are unvisited
    for (Module m : modules.values()) {
        m.setUnvisited();
    }
    modulesStack = new Stack<Module>();

    modulesStack.add(mainModule);
    while (!modulesStack.isEmpty()) {
        module = modulesStack.peek();
        if (!module.isVisited() && module.isChildrenVisited()) {
            System.out.println(separator);

            mapModule(module, k, physicalAncillaBudget, totalLogicalAncilla, Q_L, beta_pmd, alpha_int,
                    gamma_memory, library);

            modulesStack.pop();
            module.setVisited();
        } else if (module.isVisited()) {
            modulesStack.pop();
        } else if (!module.isChildrenVisited()) {
            modulesStack.addAll(module.getDFG().getModules());
            module.setChildrenVisited();
        }
    }

    System.out.println(separator);
    double runtime = (System.currentTimeMillis() - start) / 1000.0;
    System.out.println("B_P: " + B_P);
    System.out.println("Total Runtime:\t" + runtime + " sec");
}

From source file:enrichment.Disambiguate.java

/**prerequisites:
 * cd silk_2.5.3/*_links//from ww w. java  2s.  c  om
 * cat *.nt|sort  -t' ' -k3   > $filename
 * 
 * @param args $filename
 * @throws IOException
 * @throws URISyntaxException
 */
public static void main(String[] args) {
    File file = new File(args[0]);
    if (file.isDirectory()) {
        args = file.list(new OnlyExtFilenameFilter("nt"));
    }

    BufferedReader in;
    for (int q = 0; q < args.length; q++) {
        String filename = null;
        if (file.isDirectory()) {
            filename = file.getPath() + File.separator + args[q];
        } else {
            filename = args[q];
        }
        try {
            FileWriter output = new FileWriter(filename + "_disambiguated.nt");
            String prefix = "@prefix rdrel: <http://rdvocab.info/RDARelationshipsWEMI/> .\n"
                    + "@prefix dbpedia:    <http://de.dbpedia.org/resource/> .\n"
                    + "@prefix frbr:   <http://purl.org/vocab/frbr/core#> .\n"
                    + "@prefix lobid: <http://lobid.org/resource/> .\n"
                    + "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n"
                    + "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n"
                    + "@prefix mo: <http://purl.org/ontology/mo/> .\n"
                    + "@prefix wikipedia: <https://de.wikipedia.org/wiki/> .";
            output.append(prefix + "\n\n");
            in = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));

            HashMap<String, HashMap<String, ArrayList<String>>> hm = new HashMap<String, HashMap<String, ArrayList<String>>>();
            String s;
            HashMap<String, ArrayList<String>> hmLobid = new HashMap<String, ArrayList<String>>();
            Stack<String> old_object = new Stack<String>();

            while ((s = in.readLine()) != null) {
                String[] triples = s.split(" ");
                String object = triples[2].substring(1, triples[2].length() - 1);
                if (old_object.size() > 0 && !old_object.firstElement().equals(object)) {
                    hmLobid = new HashMap<String, ArrayList<String>>();
                    old_object = new Stack<String>();
                }
                old_object.push(object);
                String subject = triples[0].substring(1, triples[0].length() - 1);
                System.out.print("\nSubject=" + object);
                System.out.print("\ntriples[2]=" + triples[2]);
                hmLobid.put(subject, getAllCreators(new URI(subject)));
                hm.put(object, hmLobid);

            }
            // get all dbpedia resources
            for (String key_one : hm.keySet()) {
                System.out.print("\n==============\n==== " + key_one + "\n===============");
                int resources_cnt = hm.get(key_one).keySet().size();
                ArrayList<String>[] creators = new ArrayList[resources_cnt];
                HashMap<String, Integer> creators_backed = new HashMap<String, Integer>();
                int x = 0;
                // get all lobid_resources subsumed under the dbpedia resource
                for (String subject_uri : hm.get(key_one).keySet()) {
                    creators[x] = new ArrayList<String>();
                    System.out.print("\n     subject_uri=" + subject_uri);
                    Iterator<String> ite = hm.get(key_one).get(subject_uri).iterator();
                    int y = 0;
                    // get all creators of the lobid resource
                    while (ite.hasNext()) {
                        String creator = ite.next();
                        System.out.print("\n          " + creator);
                        if (creators_backed.containsKey(creator)) {
                            y = creators_backed.get(creator);
                        } else {
                            y = creators_backed.size();
                            creators_backed.put(creator, y);
                        }
                        while (creators[x].size() <= y) {
                            creators[x].add("-");
                        }
                        creators[x].set(y, creator);
                        y++;
                    }
                    x++;
                }
                if (creators_backed.size() == 1) {
                    System.out
                            .println("\n" + "Every resource pointing to " + key_one + " has the same creator!");
                    for (String key_two : hm.get(key_one).keySet()) {
                        output.append("<" + key_two + "> rdrel:workManifested <" + key_one + "> .\n");
                        output.append("<" + key_two + ">  mo:wikipedia <"
                                + key_one.replaceAll("dbpedia\\.org/resource", "wikipedia\\.org/wiki")
                                + "> .\n");
                    }
                } /*else  {
                    for (int a = 0; a < creators.length; a++) {
                       System.out.print(creators[a].toString()+",");
                    }
                  }*/
            }

            output.flush();
            if (output != null) {
                output.close();
            }
        } catch (Exception e) {
            System.out.print("Exception while working on " + filename + ": \n");
            e.printStackTrace(System.out);
        }
    }
}

From source file:com.github.fritaly.graphml4j.samples.GradleDependencies.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println(String.format("%s <output-file>", GradleDependencies.class.getSimpleName()));
        System.exit(1);/* w  w w.  ja  v a  2s .c  om*/
    }

    final File file = new File(args[0]);

    System.out.println("Writing GraphML file to " + file.getAbsolutePath() + " ...");

    FileWriter fileWriter = null;
    GraphMLWriter graphWriter = null;
    Reader reader = null;
    LineNumberReader lineReader = null;

    try {
        fileWriter = new FileWriter(file);
        graphWriter = new GraphMLWriter(fileWriter);

        // Customize the rendering of nodes
        final NodeStyle nodeStyle = graphWriter.getNodeStyle();
        nodeStyle.setWidth(250.0f);

        graphWriter.setNodeStyle(nodeStyle);

        // The dependency graph has been generated by Gradle with the
        // command "gradle dependencies". The output of this command has
        // been saved to a text file which will be parsed to rebuild the
        // dependency graph
        reader = new InputStreamReader(GradleDependencies.class.getResourceAsStream("gradle-dependencies.txt"));
        lineReader = new LineNumberReader(reader);

        String line = null;

        // Stack containing the node identifiers per depth inside the
        // dependency graph (the topmost dependency is the first one in the
        // stack)
        final Stack<String> parentIds = new Stack<String>();

        // Open the graph
        graphWriter.graph();

        // Map storing the node identifiers per label
        final Map<String, String> nodeIdsByLabel = new TreeMap<String, String>();

        while ((line = lineReader.readLine()) != null) {
            // Determine the depth of the current dependency inside the
            // graph. The depth can be inferred from the indentation used by
            // Gradle. Each level of depth adds 5 more characters of
            // indentation
            final int initialLength = line.length();

            // Remove the strings used by Gradle to indent dependencies
            line = StringUtils.replace(line, "+--- ", "");
            line = StringUtils.replace(line, "|    ", "");
            line = StringUtils.replace(line, "\\--- ", "");
            line = StringUtils.replace(line, "     ", "");

            // The depth can easily be inferred now
            final int depth = (initialLength - line.length()) / 5;

            // Remove unnecessary node ids
            while (depth <= parentIds.size()) {
                parentIds.pop();
            }

            // Compute a nice label from the dependency (group, artifact,
            // version) tuple
            final String label = computeLabel(line);

            // Has this dependency already been added to the graph ?
            if (!nodeIdsByLabel.containsKey(label)) {
                // No, add the node
                nodeIdsByLabel.put(label, graphWriter.node(label));
            }

            final String nodeId = nodeIdsByLabel.get(label);

            parentIds.push(nodeId);

            if (parentIds.size() > 1) {
                // Generate an edge between the current node and its parent
                graphWriter.edge(parentIds.get(parentIds.size() - 2), nodeId);
            }
        }

        // Close the graph
        graphWriter.closeGraph();

        System.out.println("Done");
    } finally {
        // Calling GraphMLWriter.close() is necessary to dispose the underlying resources
        graphWriter.close();
        fileWriter.close();
        lineReader.close();
        reader.close();
    }
}

From source file:com.github.fritaly.graphml4j.samples.GradleDependenciesWithGroupsAndBuffering.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println(String.format("%s <output-file>",
                GradleDependenciesWithGroupsAndBuffering.class.getSimpleName()));
        System.exit(1);//  w  w w. j a  v a 2  s.  com
    }

    final File file = new File(args[0]);

    System.out.println("Writing GraphML file to " + file.getAbsolutePath() + " ...");

    FileWriter fileWriter = null;
    Reader reader = null;
    LineNumberReader lineReader = null;

    try {
        fileWriter = new FileWriter(file);

        final com.github.fritaly.graphml4j.datastructure.Graph graph = new Graph();

        // The dependency graph has been generated by Gradle with the
        // command "gradle dependencies". The output of this command has
        // been saved to a text file which will be parsed to rebuild the
        // dependency graph
        reader = new InputStreamReader(
                GradleDependenciesWithGroupsAndBuffering.class.getResourceAsStream("gradle-dependencies.txt"));
        lineReader = new LineNumberReader(reader);

        String line = null;

        // Stack containing the nodes per depth inside the dependency graph
        // (the topmost dependency is the first one in the stack)
        final Stack<Node> parentNodes = new Stack<Node>();

        while ((line = lineReader.readLine()) != null) {
            // Determine the depth of the current dependency inside the
            // graph. The depth can be inferred from the indentation used by
            // Gradle. Each level of depth adds 5 more characters of
            // indentation
            final int initialLength = line.length();

            // Remove the strings used by Gradle to indent dependencies
            line = StringUtils.replace(line, "+--- ", "");
            line = StringUtils.replace(line, "|    ", "");
            line = StringUtils.replace(line, "\\--- ", "");
            line = StringUtils.replace(line, "     ", "");

            // The depth can easily be inferred now
            final int depth = (initialLength - line.length()) / 5;

            // Remove unnecessary node ids
            while (depth <= parentNodes.size()) {
                parentNodes.pop();
            }

            final Artifact artifact = createArtifact(line);

            Node node = graph.getNodeByData(artifact);

            // Has this dependency already been added to the graph ?
            if (node == null) {
                // No, add the node
                node = graph.addNode(artifact);
            }

            parentNodes.push(node);

            if (parentNodes.size() > 1) {
                // Generate an edge between the current node and its parent
                graph.addEdge("Depends on", parentNodes.get(parentNodes.size() - 2), node);
            }
        }

        // Create the groups after creating the nodes & edges
        for (Node node : graph.getNodes()) {
            final Artifact artifact = (Artifact) node.getData();

            final String groupId = artifact.group;

            Node groupNode = graph.getNodeByData(groupId);

            if (groupNode == null) {
                groupNode = graph.addNode(groupId);
            }

            // add the node to the group
            node.setParent(groupNode);
        }

        graph.toGraphML(fileWriter, new Renderer() {

            @Override
            public String getNodeLabel(Node node) {
                return node.isGroup() ? node.getData().toString() : ((Artifact) node.getData()).getLabel();
            }

            @Override
            public boolean isGroupOpen(Node node) {
                return true;
            }

            @Override
            public NodeStyle getNodeStyle(Node node) {
                // Customize the rendering of nodes
                final NodeStyle nodeStyle = new NodeStyle();
                nodeStyle.setWidth(250.0f);

                return nodeStyle;
            }

            @Override
            public GroupStyles getGroupStyles(Node node) {
                return new GroupStyles();
            }

            @Override
            public EdgeStyle getEdgeStyle(Edge edge) {
                return new EdgeStyle();
            }
        });

        System.out.println("Done");
    } finally {
        // Calling GraphMLWriter.close() is necessary to dispose the underlying resources
        fileWriter.close();
        lineReader.close();
        reader.close();
    }
}

From source file:com.github.fritaly.graphml4j.samples.GradleDependenciesWithGroups.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out//  w  w w  .  j av  a  2s .c om
                .println(String.format("%s <output-file>", GradleDependenciesWithGroups.class.getSimpleName()));
        System.exit(1);
    }

    final File file = new File(args[0]);

    System.out.println("Writing GraphML file to " + file.getAbsolutePath() + " ...");

    FileWriter fileWriter = null;
    GraphMLWriter graphWriter = null;
    Reader reader = null;
    LineNumberReader lineReader = null;

    try {
        fileWriter = new FileWriter(file);
        graphWriter = new GraphMLWriter(fileWriter);

        // Customize the rendering of nodes
        final NodeStyle nodeStyle = graphWriter.getNodeStyle();
        nodeStyle.setWidth(250.0f);
        nodeStyle.setHeight(50.0f);

        graphWriter.setNodeStyle(nodeStyle);

        // The dependency graph has been generated by Gradle with the
        // command "gradle dependencies". The output of this command has
        // been saved to a text file which will be parsed to rebuild the
        // dependency graph
        reader = new InputStreamReader(
                GradleDependenciesWithGroups.class.getResourceAsStream("gradle-dependencies.txt"));
        lineReader = new LineNumberReader(reader);

        String line = null;

        // Stack containing the artifacts per depth inside the dependency
        // graph (the topmost dependency is the first one in the stack)
        final Stack<Artifact> stack = new Stack<Artifact>();

        final Map<String, Set<Artifact>> artifactsByGroup = new HashMap<String, Set<Artifact>>();

        // List of parent/child relationships between artifacts
        final List<Relationship> relationships = new ArrayList<Relationship>();

        while ((line = lineReader.readLine()) != null) {
            // Determine the depth of the current dependency inside the
            // graph. The depth can be inferred from the indentation used by
            // Gradle. Each level of depth adds 5 more characters of
            // indentation
            final int initialLength = line.length();

            // Remove the strings used by Gradle to indent dependencies
            line = StringUtils.replace(line, "+--- ", "");
            line = StringUtils.replace(line, "|    ", "");
            line = StringUtils.replace(line, "\\--- ", "");
            line = StringUtils.replace(line, "     ", "");

            // The depth can easily be inferred now
            final int depth = (initialLength - line.length()) / 5;

            // Remove unnecessary artifacts
            while (depth <= stack.size()) {
                stack.pop();
            }

            // Create an artifact from the dependency (group, artifact,
            // version) tuple
            final Artifact artifact = createArtifact(line);

            stack.push(artifact);

            if (stack.size() > 1) {
                // Store the artifact and its parent
                relationships.add(new Relationship(stack.get(stack.size() - 2), artifact));
            }

            if (!artifactsByGroup.containsKey(artifact.group)) {
                artifactsByGroup.put(artifact.group, new HashSet<Artifact>());
            }

            artifactsByGroup.get(artifact.group).add(artifact);
        }

        // Open the graph
        graphWriter.graph();

        final Map<Artifact, String> nodeIdsByArtifact = new HashMap<Artifact, String>();

        // Loop over the groups and generate the associated nodes
        for (String group : artifactsByGroup.keySet()) {
            graphWriter.group(group, true);

            for (Artifact artifact : artifactsByGroup.get(group)) {
                final String nodeId = graphWriter.node(artifact.getLabel());

                nodeIdsByArtifact.put(artifact, nodeId);
            }

            graphWriter.closeGroup();
        }

        // Generate the edges
        for (Relationship relationship : relationships) {
            final String parentId = nodeIdsByArtifact.get(relationship.parent);
            final String childId = nodeIdsByArtifact.get(relationship.child);

            graphWriter.edge(parentId, childId);
        }

        // Close the graph
        graphWriter.closeGraph();

        System.out.println("Done");
    } finally {
        // Calling GraphMLWriter.close() is necessary to dispose the underlying resources
        graphWriter.close();
        fileWriter.close();
        lineReader.close();
        reader.close();
    }
}

From source file:Main.java

public static boolean isBalanced(String in) {
    Stack<Character> st = new Stack<Character>();

    for (char chr : in.toCharArray()) {
        switch (chr) {
        case '{':
        case '(':
        case '[':
            st.push(chr);//from ww w.  j av a  2s .c o  m
            break;
        case ']':
            if (st.isEmpty() || st.pop() != '[')
                return false;
            break;
        case ')':
            if (st.isEmpty() || st.pop() != '(')
                return false;
            break;
        case '}':
            if (st.isEmpty() || st.pop() != '{')
                return false;
            break;
        }
    }
    return st.isEmpty();
}

From source file:Main.java

/**
 * Type-safe initializer.//from  w ww  . j  av a  2  s.  com
 */

public static final <K> Stack<K> newStack() {

    return new Stack<K>();
}