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:aula1.Aula1.java

public static String conversor(String entrada, String info) throws Exception {
    Pilha<String> input = new Pilha<>();
    Pilha<String> simbolos = new Pilha<>();
    Stack<Op> operadores = new Stack<>();
    Pilha<String> saida = new Pilha<>();
    String[] operadoresSuportados = { "+", "-", "*", "/", "^", "(", ")", "sen" };

    for (int i = 0; i < entrada.length(); i++) {
        String s = "";
        try {//  w  w  w . java 2s .c  om
            if (Character.isDigit(entrada.charAt(i))) {
                s = String.valueOf(entrada.charAt(i));
                while (Character.isDigit(entrada.charAt(i + 1))) {
                    s += String.valueOf(entrada.charAt(i + 1));
                    i++;
                }
            } else {
                if (entrada.charAt(i) == 's' && entrada.contains("sen")) {
                    int ind = entrada.indexOf("sen");
                    String ent = entrada.substring(ind);
                    int ini = ent.indexOf("sen(") + 4;
                    int fim = ent.indexOf(")/");
                    CharSequence x = ent.subSequence(ini, fim);
                    if (entrada.contains("sen(" + x + ")/" + x)) {
                        entrada = entrada.replace("sen(" + x + ")/" + x, "1");
                        s = "1";
                    } else {
                        ind += 2;
                        i = -1;
                        entrada = entrada.substring(ind + 1);
                        if (entrada.charAt(0) != '(')
                            throw new Exception("Falta de '(' aps sen");
                        s = "sen";
                    }
                } else
                    s = String.valueOf(entrada.charAt(i));
            }
            simbolos.push(s);
            input.push(s);
        } catch (IndexOutOfBoundsException ex) {
            s = String.valueOf(entrada.charAt(i));
            simbolos.push(s);
            input.push(s);
        }
    }
    while (!simbolos.isEMpty()) {
        String simbolo = simbolos.pop();

        if (Character.isDigit(simbolo.charAt(0)) || simbolo.charAt(0) == 'x')
            saida.push(simbolo);
        else if (Arrays.asList(operadoresSuportados).contains(simbolo)) {
            Op operador = new Op(simbolo);
            Op topOperador;
            try {
                topOperador = operadores.peek();
            } catch (EmptyStackException e) {
                topOperador = null;
            }
            if (simbolo.equals(")")) {
                while (topOperador != null && !topOperador.op().equals("(")) {
                    saida.push(topOperador.op());
                    operadores.pop();
                    topOperador = operadores.peek();
                }
                operadores.pop();
            } else if (simbolo.equals("(")) {
                operadores.push(operador);
            } else {
                while (topOperador != null && topOperador.Precedencia() > operador.Precedencia()) {
                    saida.push(topOperador.op());
                    operadores.pop();
                    try {
                        topOperador = operadores.peek();
                    } catch (EmptyStackException e) {
                        topOperador = null;
                    }
                }
                operadores.push(operador);
            }
        }
    }
    while (!operadores.isEmpty()) {
        Op operador = operadores.pop();
        saida.push(operador.op());
    }
    String resultado = "";
    for (String s : saida) {
        System.out.println("saida: " + s);
        resultado += s + " ";
    }
    resultado = calculaPolonesaINversa(resultado, info);
    return resultado;

}

From source file:de.betterform.agent.web.event.EventQueue.java

public List<XMLEvent> aggregateEventList() {
    // Stack is used to "navigate" through the event list
    LinkedList<XMLEvent> aggregatedFocusList = new LinkedList<XMLEvent>();
    Stack<XMLEvent> aggregatedInsertEventsStack = new Stack();
    Stack<XMLEvent> aggregatedEmbedEventsStack = new Stack();
    ArrayList<XMLEvent> aggregatedEventList = new ArrayList<XMLEvent>(eventList.size());

    for (XMLEvent xmlEvent : this.loadEmbedEventList) {
        aggregatedEventList.add(xmlEvent);
    }/*w  w  w.j  a v  a2s.  c o  m*/

    this.loadEmbedEventList.clear();

    for (int i = 0; i < eventList.size(); i++) {
        XercesXMLEvent xmlEvent = (XercesXMLEvent) eventList.get(i);

        XercesXMLEvent xmlEventToAdd = new XercesXMLEvent();
        // Map PROTOTYPE_CLONED event to betterform-insert-repeatitem or betterform-insert-itemset event
        // and copy event properties to new created XMLEvent
        if (xmlEvent.getType().equals(BetterFormEventNames.PROTOTYPE_CLONED)) {
            if (xmlEvent.getContextInfo("targetName").equals(XFormsConstants.ITEMSET)) {
                xmlEventToAdd.initXMLEvent("betterform-insert-itemset", xmlEvent.getBubbles(),
                        xmlEvent.getCancelable(), xmlEvent.getContextInfo());
            } else {
                xmlEventToAdd.initXMLEvent("betterform-insert-repeatitem", xmlEvent.getBubbles(),
                        xmlEvent.getCancelable(), xmlEvent.getContextInfo());
            }
            xmlEventToAdd.target = xmlEvent.target;
            xmlEvent.addProperty("generatedIds", new HashMap());
            aggregatedEventList.add(xmlEventToAdd);
            // push XMLEvent to Stack for further processing
            aggregatedInsertEventsStack.push(xmlEventToAdd);

        }
        // add all generated ids to surrounding betterform-insert-repeatitem or betterform-insert-itemset event
        else if (xmlEvent.getType().equals(BetterFormEventNames.ID_GENERATED)
                && aggregatedInsertEventsStack.size() > 0) {
            XMLEvent aggregatingInsertEvent = aggregatedInsertEventsStack.peek();
            ((HashMap) aggregatingInsertEvent.getContextInfo("generatedIds"))
                    .put(xmlEvent.getContextInfo("originalId"), xmlEvent.getContextInfo("targetId"));
        }
        // add insert position to surrounding betterform-insert-repeatitem or betterform-insert-itemset event
        else if (xmlEvent.getType().equals(BetterFormEventNames.ITEM_INSERTED)) {
            XMLEvent tmpEvent = aggregatedInsertEventsStack.pop();
            tmpEvent.addProperty("position", xmlEvent.getContextInfo("position"));
            tmpEvent.addProperty("label", xmlEvent.getContextInfo("label"));
            tmpEvent.addProperty("value", xmlEvent.getContextInfo("value"));

        } else if (xmlEvent.getType().equals(BetterFormEventNames.EMBED)) {
            aggregatedEventList.add(xmlEvent);
            aggregatedEmbedEventsStack.push(xmlEvent);
        } else if (xmlEvent.getType().equals(BetterFormEventNames.EMBED_DONE)) {
            aggregatedEmbedEventsStack.pop().addProperty("targetElement",
                    xmlEvent.getContextInfo("targetElement"));
            aggregatedEventList.add(xmlEvent);
        } else if (xmlEvent.getType().equals(XFormsEventNames.FOCUS)) {
            aggregatedFocusList.push(xmlEvent);
        }
        /* else if(xmlEvent.getType().equals(BetterFormEventNames.INDEX_CHANGED)){
        aggregatedFocusList.push(xmlEvent);
        }*/
        // all other events within eventList are simply copied to the new eventlist
        else {
            aggregatedEventList.add(xmlEvent);
        }
    }

    while (!aggregatedFocusList.isEmpty()) {
        aggregatedEventList.add(aggregatedFocusList.pollLast());
    }
    return aggregatedEventList;
}

From source file:alluxio.job.persist.PersistDefinition.java

@Override
public SerializableVoid runTask(PersistConfig config, SerializableVoid args, JobWorkerContext context)
        throws Exception {
    AlluxioURI uri = new AlluxioURI(config.getFilePath());
    String ufsPath = config.getUfsPath();

    // check if the file is persisted in UFS and delete it, if we are overwriting it
    UfsManager.UfsClient ufsClient = context.getUfsManager().get(config.getMountId());
    try (CloseableResource<UnderFileSystem> ufsResource = ufsClient.acquireUfsResource()) {
        UnderFileSystem ufs = ufsResource.get();
        if (ufs == null) {
            throw new IOException("Failed to create UFS instance for " + ufsPath);
        }//from   w w  w. j  ava 2 s  .  c o m
        if (ufs.exists(ufsPath)) {
            if (config.isOverwrite()) {
                LOG.info("File {} is already persisted in UFS. Removing it.", config.getFilePath());
                ufs.deleteFile(ufsPath);
            } else {
                throw new IOException("File " + config.getFilePath()
                        + " is already persisted in UFS, to overwrite the file, please set the overwrite flag"
                        + " in the config.");
            }
        }

        FileSystem fs = FileSystem.Factory.get();
        long bytesWritten;
        try (Closer closer = Closer.create()) {
            OpenFileOptions options = OpenFileOptions.defaults().setReadType(ReadType.NO_CACHE);
            FileInStream in = closer.register(fs.openFile(uri, options));
            AlluxioURI dstPath = new AlluxioURI(ufsPath);
            // Create ancestor directories from top to the bottom. We cannot use recursive create
            // parents here because the permission for the ancestors can be different.
            Stack<Pair<String, MkdirsOptions>> ufsDirsToMakeWithOptions = new Stack<>();
            AlluxioURI curAlluxioPath = uri.getParent();
            AlluxioURI curUfsPath = dstPath.getParent();
            // Stop at the Alluxio root because the mapped directory of Alluxio root in UFS may not
            // exist.
            while (!ufs.isDirectory(curUfsPath.toString()) && curAlluxioPath != null) {
                URIStatus curDirStatus = fs.getStatus(curAlluxioPath);
                ufsDirsToMakeWithOptions.push(new Pair<>(curUfsPath.toString(),
                        MkdirsOptions.defaults().setCreateParent(false).setOwner(curDirStatus.getOwner())
                                .setGroup(curDirStatus.getGroup())
                                .setMode(new Mode((short) curDirStatus.getMode()))));
                curAlluxioPath = curAlluxioPath.getParent();
                curUfsPath = curUfsPath.getParent();
            }
            while (!ufsDirsToMakeWithOptions.empty()) {
                Pair<String, MkdirsOptions> ufsDirAndPerm = ufsDirsToMakeWithOptions.pop();
                // UFS mkdirs might fail if the directory is already created. If so, skip the mkdirs
                // and assume the directory is already prepared, regardless of permission matching.
                if (!ufs.mkdirs(ufsDirAndPerm.getFirst(), ufsDirAndPerm.getSecond())
                        && !ufs.isDirectory(ufsDirAndPerm.getFirst())) {
                    throw new IOException("Failed to create " + ufsDirAndPerm.getFirst() + " with permission "
                            + ufsDirAndPerm.getSecond().toString());
                }
            }
            URIStatus uriStatus = fs.getStatus(uri);
            OutputStream out = closer.register(
                    ufs.create(dstPath.toString(), CreateOptions.defaults().setOwner(uriStatus.getOwner())
                            .setGroup(uriStatus.getGroup()).setMode(new Mode((short) uriStatus.getMode()))));
            bytesWritten = IOUtils.copyLarge(in, out);
            incrementPersistedMetric(ufsClient.getUfsMountPointUri(), bytesWritten);
        }
        LOG.info("Persisted file {} with size {}", ufsPath, bytesWritten);
    }
    return null;
}

From source file:com.madrobot.di.wizard.json.JSONSerializer.java

/**
 * Serializes the objType into valid JSON format <br/>
 * //from  ww  w. j a  va  2s . c om
 * If there is an error while serializes, if possible it will try to ignore it, otherwise returns a null value.
 * 
 * @param objType
 *            Java Object to write JSON to
 * 
 * @return String valid json string
 * 
 * @see #serializer(JSONObject, Stack)
 */
public String serializer(final Object objType) throws JSONException {

    Stack<Object> stack = new Stack<Object>();
    stack.push(objType);

    JSONObject jsonObject = new JSONObject();

    serializer(jsonObject, stack);

    return jsonObject.toString();
}

From source file:edu.mit.lib.tools.Modernize.java

private void communityManifest(Community comm) throws IOException, SQLException {
    Stack<Community> parents = new Stack<>();
    Community parent = comm.getParentCommunity();
    while (parent != null) {
        parents.push(parent);/*w  w w .ja va 2  s .  co  m*/
        parent = parent.getParentCommunity();
    }
    int level = manif.addParents(parents);
    manif.addCommunity(comm, level);
}

From source file:de.uni_hannover.dcsec.siafu.control.Simulation.java

/**
 * Build a <code>Simulation</code> object and start a thread that governs
 * it./*ww w  .  j  av a 2s  .c  o  m*/
 * 
 * @param simulationPath
 *            the path to the simulation data, which includes maps, sprites,
 *            behavior models, etc...
 * @param control
 *            the simulation <code>Controller</code>
 */
public Simulation(final String simulationPath, final Controller control) {
    this.simData = SimulationData.getInstance(simulationPath);
    this.siafuConfig = control.getSiafuConfig();
    this.simulationConfig = simData.getConfigFile();
    this.control = control;
    this.incommingAgents = new Stack<Agent>();

    World.setShouldPrefillCache(control.getSiafuConfig().getBoolean("ui.gradientcache.prefill"));

    World.setCacheSize(control.getSiafuConfig().getInt("ui.gradientcache.size"));

    if (this.simulationConfig.containsKey("automaticiteration")) {
        if (this.simulationConfig.getBoolean("automaticiteration"))
            this.isAutomaticIteration = true;
        else
            this.isAutomaticIteration = false;
    } else
        this.isAutomaticIteration = true;

    System.out.println("Auto Int:" + this.isAutomaticIteration);

    new Thread(this, "Simulation thread").start();
}

From source file:com.awrtechnologies.carbudgetsales.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    fragmentstack = new Stack<Fragment>();
    // creating connection detector class instance
    cd = new ConnectionDetector(MainActivity.this);
    rl_buttons = (RelativeLayout) findViewById(R.id.relative_layout_buttons);
    relativeprogress = (RelativeLayout) findViewById(R.id.relativelayoutprogressbarheader);
    news = (ImageView) findViewById(R.id.button_news);
    deals = (ImageView) findViewById(R.id.button_deals);
    tools = (ImageView) findViewById(R.id.button_tools);
    inventory = (ImageView) findViewById(R.id.button_inventroy);
    info = (ImageView) findViewById(R.id.button_information);
    service = (ImageView) findViewById(R.id.button_services);
    facebook = (Button) findViewById(R.id.button_facebook);
    twitter = (Button) findViewById(R.id.button_twitter);
    google = (Button) findViewById(R.id.button_google);
    digg = (Button) findViewById(R.id.button_digg);
    youtube = (Button) findViewById(R.id.button_youtube);

    java.io.File imageFile1 = new File(
            (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/."
                    + Constants.APPNAME + ""));
    imageFile1.mkdirs();// w  w  w. ja va2 s  . c o  m
    User user = User.getUser();
    if (user != null) {
        if (GeneralHelper.getInstance(MainActivity.this).isIscheck() == true
                || GeneralHelper.getInstance(MainActivity.this).isIscheckdonetime() == true) {

            //            openfragment();
            //            GeneralHelper.getInstance(com.awrtechnologies.carbudgetsales.MainActivity.this).setIscheckfragment(false);
            loadData();

        } else if (GeneralHelper.getInstance(MainActivity.this).isIscheck() == false
                || GeneralHelper.getInstance(MainActivity.this).isIscheckdonetime() == false) {

            loadData();
        }
    } else {
        //             openNewFragment(new ServiceFragment());
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
        ft.replace(R.id.contanier, new Signin_fragment());

        ft.commit();
    }

    deals.setOnClickListener(this);
    inventory.setOnClickListener(this);
    news.setOnClickListener(this);
    tools.setOnClickListener(this);
    info.setOnClickListener(this);
    service.setOnClickListener(this);
    facebook.setOnClickListener(this);
    twitter.setOnClickListener(this);
    google.setOnClickListener(this);
    digg.setOnClickListener(this);
    youtube.setOnClickListener(this);
}

From source file:com.bluexml.xforms.generator.forms.Renderable.java

/**
 * Recursive render.<br>/*from  www.  j  av  a  2s .co m*/
 * Initiate rendering
 * 
 * @return the rendered
 */
public Rendered recursiveRender() {
    logger.debug("-------------------------------------------------");
    logger.debug("RENDERING " + this.toString());
    logger.debug("-------------------------------------------------");
    return recursiveRender("", new Stack<Renderable>(), new Stack<Rendered>(), false);
}

From source file:com.schibsted.triathlon.operators.GroupByOperatorTest.java

@Test
public void testDeployTwoDataCentersOddNumberOfInstances() throws Exception {
    initializeInstanceInfos(2);//from   w  ww. j av a 2 s. co  m

    List<String> constraint = new ArrayList<String>() {
        {
            add("datacenter");
            add("GROUP_BY");
        }
    };
    TriathlonService triathlonService = new TriathlonServiceImpl();

    String content = IOUtils.toString(this.getClass().getResourceAsStream("group_by_operator_1.json"), "UTF-8");

    ByteBuf buffer = Unpooled.copiedBuffer(content.getBytes());

    Marathon appDefinition = triathlonService.parseJson(Observable.just(buffer)).toBlocking().toFuture().get();
    appDefinition.setInstances(5);

    ConstraintModel constraintModel = ConstraintModel.createConstraintModel(constraint);

    Operator cluster = new GroupByOperator(triathlonService, constraintModel);

    Operator spyCluster = Mockito.spy(cluster);
    doReturn(Observable.just(Unpooled.wrappedBuffer("TEST".getBytes()))).when(spyCluster)
            .getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString());

    Stack<Integer> values = new Stack<>();
    values.push(2);
    values.push(3);

    when(spyCluster.getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString()))
            .thenAnswer(invocation -> {
                Object[] args = invocation.getArguments();
                Observable<ByteBuf> val = Observable
                        .just(Unpooled.wrappedBuffer(((String) args[1]).getBytes()));
                Marathon appDef = triathlonService.parseJson(val).toBlocking().toFuture().get();
                Integer v = values.pop();
                assertEquals(v, appDef.getInstances());
                return val;
            });

    spyCluster.apply(appDefinition).subscribe();
    verify(spyCluster, times(2)).getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString());
}

From source file:com.intuit.tank.harness.functions.JexlStringFunctions.java

/**
 * @param minId/* w  w  w . java  2  s  .  c  o  m*/
 * @param maxId
 * @return
 */
private synchronized Stack<Integer> getStack(Integer minId, Integer maxId) {
    String key = getStackKey(minId, maxId);
    Stack<Integer> stack = stackMap.get(key);
    if (stack == null) {
        int blockSize = (maxId - minId) / APITestHarness.getInstance().getAgentRunData().getTotalAgents();
        int offset = APITestHarness.getInstance().getAgentRunData().getAgentInstanceNum() * blockSize;
        LOG.info(LogUtil.getLogMessage(
                "Creating userId Block starting at " + offset + " and containing  " + blockSize + " entries.",
                LogEventType.System));
        List<Integer> list = new ArrayList<Integer>();

        for (int i = 0; i < blockSize; i++) {
            int nextNum = i + minId + offset;
            list.add(nextNum);
        }
        Collections.shuffle(list);
        // Collections.reverse(list);
        stack = new Stack<Integer>();
        stack.addAll(list);
        stackMap.put(key, stack);
    }
    return stack;
}