text:
var Jii = require('jii');
require('jii-httpserver');
require('jii-view');
require('jii-urlmanager');
require('jii-comet');

require('./controllers/SiteController');

var custom = require('fs').existsSync(__dirname + '/config.js') ? require('./config') : {};

require('jii-workers')
    .setEnvironment(custom.environment)
    .application('comet', Jii.mergeConfigs(
        {
            workers: 2,
            application: {
                basePath: __dirname,
                components: {
                    comet: {
                        className: 'Jii.comet.server.Server',
                        port: 4401,

                        /**
                         *
                         * @param {Jii.comet.server.ConnectionEvent} event
                         */
                        'on addConnection': function(event) {
                            Jii.app.comet.subscribe(event.connection.id, 'chat');
                        }
                    }
                }
            }
        },
        custom.comet || {}
    ))
    .application('http', Jii.mergeConfigs(
        {
            application: {
                basePath: __dirname,
                viewPath: __dirname + '/../templates',
                components: {
                    urlManager: {
                        className: 'Jii.urlManager.UrlManager',
                        rules: {
                            '': 'site/index',
                            'chat': 'site/chat'
                        }
                    },
                    http: {
                        className: 'Jii.httpServer.HttpServer',
                        port: 4400,
                        staticDirs: __dirname + '/../public/'
                    },
                    view: {
                        className: 'Jii.view.ServerWebView'
                    }
                }
            }
        },
        custom.http || {}
    ));


text:
package gov.hhs.fha.nhinc.xmlCommon;

import gov.hhs.fha.nhinc.nhinclib.NullChecker;
import java.io.StringWriter;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathExpressionException;
import org.apache.log4j.Logger;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSException;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSParser;
import org.w3c.dom.ls.LSSerializer;

/**
 *
 * @author rayj
 */
public class XmlUtility {

    private static final Logger LOG = Logger.getLogger(XmlUtility.class);

    public static String getNodeValue(Node node) {
        String value = null;
        if (node != null) {
            value = node.getNodeValue();
            if (value == null) {
                value = node.getTextContent();
            }
        }
        return value;
    }

    protected static DOMImplementationLS getDOMImplementationLS(Node node) {
        Document document = node.getOwnerDocument();
        return (DOMImplementationLS) document.getImplementation();
    }

    public static String serializeElement(Element element) throws TransformerFactoryConfigurationError, TransformerException {
        String serializedElement = null;
        if (element != null) {
            StringWriter output = new StringWriter();

            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.transform(new DOMSource(element), new StreamResult(output));

            serializedElement = output.toString();
        }
        return serializedElement;
    }

    public static String serializeNode(Node node) throws LSException, IllegalAccessException, DOMException,
            InstantiationException, ClassNotFoundException, ClassCastException {
        String serializedElement = null;
        if (node != null) {
            DOMImplementationLS impl = getDOMImplementationLS(node);
            LSSerializer writer = impl.createLSSerializer();
            serializedElement = writer.writeToString(node);
        }
        return serializedElement;
    }

    /**
     * @deprecated Use {@link XpathHelper} instead
     * @param sourceXml
     * @param xpathQuery
     * @return
     * @throws javax.xml.xpath.XPathExpressionException
     */
    public static Node performXpathQuery(String sourceXml, String xpathQuery) throws XPathExpressionException {
        return XpathHelper.performXpathQuery(sourceXml, xpathQuery);
    }

    /**
     * @deprecated Use {@link XpathHelper} instead
     * @param sourceElement
     * @param xpathQuery
     * @return
     * @throws javax.xml.xpath.XPathExpressionException
     */
    public static Node performXpathQuery(Element sourceElement, String xpathQuery) throws XPathExpressionException {
        return XpathHelper.performXpathQuery(sourceElement, xpathQuery);
    }

    /**
     * @deprecated Use {@link XpathHelper} instead
     * @param sourceElement
     * @param xpathQuery
     * @param namespaceContext
     * @return
     * @throws javax.xml.xpath.XPathExpressionException
     */
    public static Node performXpathQuery(Element sourceElement, String xpathQuery, NamespaceContext namespaceContext)
            throws XPathExpressionException {
        return XpathHelper.performXpathQuery(sourceElement, xpathQuery, namespaceContext);
    }

    public static Element convertXmlToElement(String xml) throws Exception {
        Element element = null;

        if (NullChecker.isNotNullish(xml)) {
            if (XmlUtfHelper.isUtf16(xml)) {
                try {
                    element = convertXmlToElementWorker(xml);
                } catch (Exception ex) {
                    // Exception may be due to the encoding of the message being incorrect.
                    // retry using UTF-8
                    LOG.warn("failed to perform xml to element - retrying with UTF-8");
                    xml = XmlUtfHelper.convertToUtf8(xml);
                    element = convertXmlToElementWorker(xml);
                }
            } else {
                element = convertXmlToElementWorker(xml);
            }
        }
        return element;
    }

    private static Element initializeElement() {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        Document document = null;
        Element docElement = null;

        try {
            builder = factory.newDocumentBuilder();
            document = builder.newDocument();
            docElement = document.createElement("init");
        } catch (ParserConfigurationException e) {
            LOG.error("Error creating dom document builder", e);
        }

        return docElement;
    }

    private static Element convertXmlToElementWorker(String xml) throws Exception {
        Element element = initializeElement();

        DOMImplementationLS impl = getDOMImplementationLS(element);
        LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, "http://www.w3.org/2001/XMLSchema");
        LSInput lsInput = impl.createLSInput();
        lsInput.setStringData(xml);
        Document doc = parser.parse(lsInput);
        if (doc != null) {
            element = doc.getDocumentElement();
        }
        return element;
    }

    public static Element getSingleChildElement(Element element, String namespaceURI, String localName) {
        Element childElement = null;
        if ((element != null) && (NullChecker.isNotNullish(namespaceURI) && (NullChecker.isNotNullish(localName)))) {
            NodeList result = element.getElementsByTagNameNS(namespaceURI, localName);
            if ((result != null) && (result.getLength() >= 1)) {
                childElement = (Element) result.item(0);
            }
        }
        return childElement;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.ojb.odmg.collections;

import java.io.Serializable;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.Collection;

import org.apache.ojb.broker.PBKey;
import org.apache.ojb.broker.PersistenceBroker;
import org.apache.ojb.broker.PersistenceBrokerAware;
import org.apache.ojb.broker.PersistenceBrokerException;
import org.apache.ojb.broker.ManageableCollection;
import org.apache.ojb.broker.core.ValueContainer;
import org.apache.ojb.broker.metadata.ClassDescriptor;
import org.apache.ojb.broker.metadata.FieldDescriptor;
import org.apache.ojb.broker.query.Criteria;
import org.apache.ojb.broker.query.Query;
import org.apache.ojb.broker.query.QueryByCriteria;
import org.apache.ojb.broker.util.logging.Logger;
import org.apache.ojb.broker.util.logging.LoggerFactory;
import org.apache.ojb.odmg.PBCapsule;
import org.apache.ojb.odmg.TransactionImpl;
import org.apache.ojb.odmg.TxManagerFactory;
import org.apache.ojb.odmg.RuntimeObject;
import org.apache.ojb.odmg.oql.OQLQueryImpl;
import org.odmg.DCollection;
import org.odmg.DList;
import org.odmg.DSet;
import org.odmg.ODMGRuntimeException;
import org.odmg.OQLQuery;
import org.odmg.Transaction;

/**
 *
 */
public class DSetImpl extends AbstractSet implements DSet, Serializable, PersistenceBrokerAware, ManageableCollection
{
	private static final long serialVersionUID = -4459673364598652639L;

    private transient Logger log;

    private Integer id;
    private List elements;

    private PBKey pbKey;

    /**
     * Used by PB-Kernel to instantiate ManageableCollections
     * FOR INTERNAL USE ONLY
     */
    public DSetImpl()
    {
        super();
        elements = new ArrayList();
//        if(getTransaction() == null)
//        {
//            throw new TransactionNotInProgressException("Materialization of DCollection instances must be done" +
//                    " within a odmg-tx");
//        }
        getPBKey();
    }

    /**
     * DSetImpl constructor comment.
     */
    public DSetImpl(PBKey pbKey)
    {
        this();
        this.pbKey = pbKey;
    }

    protected Logger getLog()
    {
        if (log == null)
        {
            log = LoggerFactory.getLogger(DSetImpl.class);
        }
        return log;
    }

    private DSetEntry prepareEntry(Object obj)
    {
        return new DSetEntry(this, obj);
    }

    protected TransactionImpl getTransaction()
    {
        return TxManagerFactory.instance().getTransaction();
    }

    protected boolean checkForOpenTransaction(TransactionImpl tx)
    {
        boolean result = false;
        if(tx != null && tx.isOpen())
        {
            result = true;
        }
        return result;
    }

    public PBKey getPBKey()
    {
        if(pbKey == null)
        {
            TransactionImpl tx = getTransaction();
            if(tx != null && tx.isOpen())
            {
                pbKey = tx.getBroker().getPBKey();
            }
        }
        return pbKey;
    }

    public void setPBKey(PBKey pbKey)
    {
        this.pbKey = pbKey;
    }

    public boolean remove(Object o)
    {
        return super.remove(o);
    }

    public boolean removeAll(Collection c)
    {
        return super.removeAll(c);
    }

    public boolean add(Object o)
    {
        if (!this.contains(o))
        {
            DSetEntry entry = prepareEntry(o);
            elements.add(entry);
            // if we are in a transaction: get locks !
            TransactionImpl tx = getTransaction();
            if ((tx != null) && (tx.isOpen()))
            {
                List regList = tx.getRegistrationList();
                RuntimeObject rt = new RuntimeObject(this, tx);
                tx.lockAndRegister(rt, Transaction.WRITE, false, regList);

                rt = new RuntimeObject(o, tx);
                tx.lockAndRegister(rt, Transaction.READ, regList);

                rt = new RuntimeObject(entry, tx, true);
                tx.lockAndRegister(rt, Transaction.WRITE, false, regList);
            }
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * Create a new DSet object that contains the elements of this
     * collection minus the elements in otherSet.
     * @param	otherSet	A set containing elements that should not be in the result set.
     * @return	A newly created DSet instance that contains the elements
     * of this set minus those elements in otherSet.
     */
    public DSet difference(DSet otherSet)
    {
        DSetImpl result = new DSetImpl(getPBKey());
        Iterator iter = this.iterator();
        while (iter.hasNext())
        {
            Object candidate = iter.next();
            if (!otherSet.contains(candidate))
            {
                result.add(candidate);
            }
        }
        return result;
    }

    /**
     * Determines whether there is an element of the collection that evaluates to true
     * for the predicate.
     * @param	predicate	An OQL boolean query predicate.
     * @return	True if there is an element of the collection that evaluates to true
     * for the predicate, otherwise false.
     * @exception	org.odmg.QueryInvalidException	The query predicate is invalid.
     */
    public boolean existsElement(String predicate) throws org.odmg.QueryInvalidException
    {
        DList results = (DList) this.query(predicate);
        if (results == null || results.size() == 0)
            return false;
        else
            return true;
    }

    public List getElements()
    {
        return elements;
    }

    public void setElements(List elements)
    {
        this.elements = elements;
    }

    public Integer getId()
    {
        return id;
    }

    /**
     * Create a new DSet object that is the set intersection of this
     * DSet object and the set referenced by otherSet.
     * @param	otherSet	The other set to be used in the intersection operation.
     * @return	A newly created DSet instance that contains the
     * intersection of the two sets.
     */
    public DSet intersection(DSet otherSet)
    {
        DSet union = this.union(otherSet);
        DSetImpl result = new DSetImpl(getPBKey());
        Iterator iter = union.iterator();
        while (iter.hasNext())
        {
            Object candidate = iter.next();
            if (this.contains(candidate) && otherSet.contains(candidate))
            {
                result.add(candidate);
            }
        }
        return result;
    }

    /**
     * Returns an iterator over the elements in this collection.  There are no
     * guarantees concerning the order in which the elements are returned
     * (unless this collection is an instance of some class that provides a
     * guarantee).
     *
     * @return an <tt>Iterator</tt> over the elements in this collection
     */
    public Iterator iterator()
    {
        return new DSetIterator(this);
    }

    /**
     * Determine whether this set is a proper subset of the set referenced by
     * otherSet.
     * @param	otherSet	Another set.
     * @return True if this set is a proper subset of the set referenced by
     * otherSet, otherwise false.
     */
    public boolean properSubsetOf(org.odmg.DSet otherSet)
    {
        return (this.size() > 0 && this.size() < otherSet.size() && this.subsetOf(otherSet));
    }

    /**
     * Determine whether this set is a proper superset of the set referenced by
     * otherSet.
     * @param	otherSet	Another set.
     * @return True if this set is a proper superset of the set referenced by
     * otherSet, otherwise false.
     */
    public boolean properSupersetOf(org.odmg.DSet otherSet)
    {
        return (otherSet.size() > 0 && otherSet.size() < this.size() && this.supersetOf(otherSet));
    }

    /**
     * Evaluate the boolean query predicate for each element of the collection and
     * return a new collection that contains each element that evaluated to true.
     * @param	predicate	An OQL boolean query predicate.
     * @return	A new collection containing the elements that evaluated true for the predicate.
     * @exception	org.odmg.QueryInvalidException	The query predicate is invalid.
     */
    public DCollection query(String predicate) throws org.odmg.QueryInvalidException
    {
        // 1.build complete OQL statement
        String oql = "select all from java.lang.Object where " + predicate;
        TransactionImpl tx = getTransaction();

        OQLQuery predicateQuery = tx.getImplementation().newOQLQuery();

        PBCapsule capsule = new PBCapsule(tx.getImplementation().getCurrentPBKey(), tx);
        PersistenceBroker broker = capsule.getBroker();

        try
        {
            predicateQuery.create(oql);
            Query pQ = ((OQLQueryImpl) predicateQuery).getQuery();
            Criteria pCrit = pQ.getCriteria();

            Criteria allElementsCriteria = this.getPkCriteriaForAllElements(broker);
            // join selection of elements with predicate criteria:
            pCrit.addAndCriteria(allElementsCriteria);
            Class clazz = this.getElementsExtentClass(broker);
            Query q = new QueryByCriteria(clazz, pCrit);
            if (log.isDebugEnabled()) log.debug(q.toString());
            // 2. perfom query
            return (DSetImpl) broker.getCollectionByQuery(DSetImpl.class, q);
        }
        catch (PersistenceBrokerException e)
        {
            throw new ODMGRuntimeException(e.getMessage());
        }
        finally
        {
            capsule.destroy();
        }
    }

    private Criteria getPkCriteriaForAllElements(PersistenceBroker broker)
    {
        try
        {
            Criteria crit = null;
            for (int i = 0; i < elements.size(); i++)
            {
                DListEntry entry = (DListEntry) elements.get(i);
                Object obj = entry.getRealSubject();
                ClassDescriptor cld = broker.getClassDescriptor(obj.getClass());

                FieldDescriptor[] pkFields = cld.getPkFields();
                ValueContainer[] pkValues = broker.serviceBrokerHelper().getKeyValues(cld, obj);

                Criteria criteria = new Criteria();
                for (int j = 0; j < pkFields.length; j++)
                {
                    FieldDescriptor fld = pkFields[j];
                    criteria.addEqualTo(fld.getPersistentField().getName(), pkValues[j].getValue());
                }

                if (crit == null)
                    crit = criteria;
                else
                    crit.addOrCriteria(criteria);
            }
            return crit;
        }
        catch (PersistenceBrokerException e)
        {
            log.error(e);
            return null;
        }
    }

    private Class getElementsExtentClass(PersistenceBroker broker) throws PersistenceBrokerException
    {
        // we ll have to compute the most general extent class here !!!
        DListEntry entry = (DListEntry) elements.get(0);
        Class elementsClass = entry.getRealSubject().getClass();
        Class extentClass = broker.getTopLevelClass(elementsClass);
        return extentClass;
    }

    /**
     * Access all of the elements of the collection that evaluate to true for the
     * provided query predicate.
     * @param	predicate	An OQL boolean query predicate.
     * @return	An iterator used to iterate over the elements that evaluated true for the predicate.
     * @exception	org.odmg.QueryInvalidException	The query predicate is invalid.
     */
    public Iterator select(String predicate) throws org.odmg.QueryInvalidException
    {
        return this.query(predicate).iterator();
    }

    /**
     * Selects the single element of the collection for which the provided OQL query
     * predicate is true.
     * @param	predicate	An OQL boolean query predicate.
     * @return The element that evaluates to true for the predicate. If no element
     * evaluates to true, null is returned.
     * @exception	org.odmg.QueryInvalidException	The query predicate is invalid.
     */
    public Object selectElement(String predicate) throws org.odmg.QueryInvalidException
    {
        return ((DList) this.query(predicate)).get(0);
    }

    /**
     * Sets the elements.
     * @param elements The elements to set
     */
    public void setElements(Vector elements)
    {
        this.elements = elements;
    }

    /**
     * Sets the id.
     * @param id The id to set
     */
    public void setId(Integer id)
    {
        this.id = id;
    }

    /**
     * Returns the number of elements in this collection.  If this collection
     * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
     * <tt>Integer.MAX_VALUE</tt>.
     *
     * @return the number of elements in this collection
     */
    public int size()
    {
        return elements.size();
    }

    /**
     * Determine whether this set is a subset of the set referenced by otherSet.
     * @param	otherSet	Another set.
     * @return True if this set is a subset of the set referenced by otherSet,
     * otherwise false.
     */
    public boolean subsetOf(DSet otherSet)
    {
        return otherSet.containsAll(this);
    }

    /**
     * Determine whether this set is a superset of the set referenced by otherSet.
     * @param	otherSet	Another set.
     * @return True if this set is a superset of the set referenced by otherSet,
     * otherwise false.
     */
    public boolean supersetOf(DSet otherSet)
    {
        return this.containsAll(otherSet);
    }

    /**
     * Create a new DSet object that is the set union of this
     * DSet object and the set referenced by otherSet.
     * @param	otherSet	The other set to be used in the union operation.
     * @return	A newly created DSet instance that contains the union of the two sets.
     */
    public DSet union(DSet otherSet)
    {
        DSetImpl result = new DSetImpl(getPBKey());
        result.addAll(this);
        result.addAll(otherSet);
        return result;
    }

    //***************************************************************
    // ManageableCollection interface
    //***************************************************************

    /**
     * add a single Object to the Collection. This method is used during reading Collection elements
     * from the database. Thus it is is save to cast anObject to the underlying element type of the
     * collection.
     */
    public void ojbAdd(Object anObject)
    {
        DSetEntry entry = prepareEntry(anObject);
        entry.setPosition(elements.size());
        elements.add(entry);
    }

    /**
     * adds a Collection to this collection. Used in reading Extents from the Database.
     * Thus it is save to cast otherCollection to this.getClass().
     */
    public void ojbAddAll(ManageableCollection otherCollection)
    {
        // don't use this to avoid locking
        // this.addAll((DListImpl) otherCollection);
        Iterator it = otherCollection.ojbIterator();
        while (it.hasNext())
        {
            ojbAdd(it.next());
        }
    }

    public void afterStore(PersistenceBroker broker) throws PersistenceBrokerException
    {
    }

    /**
     * returns an Iterator over all elements in the collection. Used during store and delete Operations.
     * If the implementor does not return an iterator over ALL elements, OJB cannot store and delete all elements properly.
     */
    public Iterator ojbIterator()
    {
        return this.iterator();
    }

    //***************************************************************
    // PersistenceBrokerAware interface
    //***************************************************************

    /**
     * prepare itself for persistence. Each DList entry generates an
     * {@link org.apache.ojb.broker.Identity} for the wrapped persistent
     * object.
     */
    public void beforeInsert(PersistenceBroker broker) throws PersistenceBrokerException
    {
//        Iterator it = elements.iterator();
//        DSetEntry entry;
//        while (it.hasNext())
//        {
//            entry = (DSetEntry) it.next();
//            entry.prepareForPersistency(broker);
//        }
    }

    /**
     * noop
     */
    public void beforeUpdate(PersistenceBroker broker) throws PersistenceBrokerException
    {
    }

    /**
     * noop
     */
    public void beforeDelete(PersistenceBroker broker) throws PersistenceBrokerException
    {
    }

    /**
     * noop
     */
    public void afterUpdate(PersistenceBroker broker) throws PersistenceBrokerException
    {
    }

    /**
     * noop
     */
    public void afterInsert(PersistenceBroker broker) throws PersistenceBrokerException
    {
    }

    /**
     * noop
     */
    public void afterDelete(PersistenceBroker broker) throws PersistenceBrokerException
    {
    }

    /**
     * noop
     */
    public void afterLookup(PersistenceBroker broker) throws PersistenceBrokerException
    {
    }
}


text:
A CMSEmbeddedComponent is a component which renderes the main content specified by the Object to be viewed, edited or assigned.

Instance Variables
	caption:		<String>
	rootComponent:		<CMSRootElement>

caption
	- is the caption displayed in the header of the site

rootComponent
	- holds the root component


text:
<?php

namespace Payum\Paypal\Ipn;

use Http\Message\MessageFactory;
use Payum\Core\Exception\Http\HttpException;
use Payum\Core\Exception\InvalidArgumentException;
use Payum\Core\HttpClientInterface;

/**
 * @link https://www.x.com/developers/paypal/documentation-tools/ipn/integration-guide/IPNIntro
 */
class Api
{
    /**
     * It sends back if the message originated with PayPal.
     */
    public const NOTIFY_VERIFIED = 'VERIFIED';

    /**
     * if there is any discrepancy with what was originally sent
     */
    public const NOTIFY_INVALID = 'INVALID';

    public const CMD_NOTIFY_VALIDATE = '_notify-validate';

    /**
     * @var HttpClientInterface
     */
    protected $client;

    /**
     * @var MessageFactory
     */
    protected $messageFactory;

    /**
     * @var array
     */
    protected $options;

    public function __construct(array $options, HttpClientInterface $client, MessageFactory $messageFactory)
    {
        $this->client = $client;
        $this->messageFactory = $messageFactory;

        $this->options = $options;

        if (false == (isset($this->options['sandbox']) && is_bool($this->options['sandbox']))) {
            throw new InvalidArgumentException('The boolean sandbox option must be set.');
        }
    }

    /**
     * @return string
     */
    public function notifyValidate(array $fields)
    {
        $fields['cmd'] = self::CMD_NOTIFY_VALIDATE;

        $headers = [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ];

        $request = $this->messageFactory->createRequest('POST', $this->getIpnEndpoint(), $headers, http_build_query($fields));

        $response = $this->client->send($request);

        if (false == ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300)) {
            throw HttpException::factory($request, $response);
        }

        $result = $response->getBody()->getContents();

        return self::NOTIFY_VERIFIED === $result ? self::NOTIFY_VERIFIED : self::NOTIFY_INVALID;
    }

    /**
     * @return string
     */
    public function getIpnEndpoint()
    {
        return $this->options['sandbox'] ?
            'https://www.sandbox.paypal.com/cgi-bin/webscr' :
            'https://www.paypal.com/cgi-bin/webscr'
        ;
    }
}


text:
<?php
namespace Application\Controller;

use Application\Form\Login;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AuthController extends AbstractActionController
{
    protected $sm;

    public function __construct($sm)
    {
        $this->sm = $sm;
    }

    public function loginAction()
    {
        $this->layout('layout/teste');
        $form = new Login();
        $request = $this->getRequest();

        if ($request->isPost()) {
            $data = $request->getPost();
            $this->getServiceLocator()->get('AuthService')->authenticate($data);

            return $this->redirect()->toUrl('/application/index/index');
        }

        return new ViewModel(array(
            'form' => $form
        ));

    }

    public function logoutAction()
    {
        $this->getServiceLocator()->get('AuthService')->logout();

        return $this->redirect()->toUrl('/application/auth/login');
    }

    public function noauthorizeAction()
    {
        // $session = $this->sm->get('Session');

        // var_dump($session->offsetGet('user'));exit;

        // $session = new SessionContainer('Session');

        // if (!$session->user) {

        //     $this->flashMessenger()->addErrorMessage('Usuário não autenticado');
        //     return $this->redirect()->toUrl(BASE_URL.'/auth/index');
        // }

        // if(!$session->offsetGet('programas')){
        //     $this->flashMessenger()->addErrorMessage('Você não tem permissão para acessar este recurso');
        //     return $this->redirect()->toUrl(BASE_URL.'/auth/selecionar-perfil/index');
        // }

        $this->flashMessenger()->addErrorMessage('Você não tem permissão para acessar este recurso');
        return $this->redirect()->toUrl('/application/index/index');

        return new ViewModel(array());
    }

}


text:
[![Build Status](https://img.shields.io/travis/whitfin/dot-notes-js.svg)](https://travis-ci.org/whitfin/dot-notes-js) [![npm](https://img.shields.io/npm/v/dot-notes.svg)](https://www.npmjs.com/package/dot-notes)

This module provides a simple way of constructing/parsing dot/bracket notation in JavaScript/Node.js. It was born from a need to flatten Objects in a customized way, making `dot-notes` useful in many scenarios.

- [Getting Started](#setup)
- [Quick Examples](#quick-examples)
- [Migrating from 2.x to 3.x](#migrating-from-2x-to-3x)
- [Contributing](#contributing)
- [Testing](#testing)

### Getting Started

`dot-notes` lives on [npm](https://www.npmjs.com/package/dot-notes), so just install it via the command line and you're good to go. There are no dependencies either, so it should be pretty fast to download in your production environment (there *are* dev dependencies).

```bash
$ npm install --save dot-notes
```

In the interest of short READMEs, please visit the wiki for [documentation](https://github.com/zackehh/dot-notes/wiki) on how to use this module, including example usage.

### Quick Examples

```javascript
var dots = require('dot-notes');

dots.create({}, 'test.test', 'example');
  => { "test": { "test": "example" } }
dots.get({ "test": { "test": "example" } }, 'test.test');
  => "example"
dots.keys('this["is"].my[1].example');
  => [ 'this', 'is', 'my', 1, 'example' ]
dots.join([ 'this', 'is', 'my', 1, 'example' ]);
  => 'this.is.my[1].example'
dots.recurse({ "test": { "test": "example" } }, console.log);
  => [ 'test', 'example', 'test.test' ]

```

### Migrating from 2.x to 3.x

The argument syntax for any functions taking an Object target and a String have been flipped, to follow the `(haystack, needle)` format. This means that the arguments for a target are now required where they weren't previously - *however*, if you pass undefined you will get the same behaviour as previously.

This is the only non-backwards compatible change in 3.x (and is the change which forced the jump to 3.0.0).

### Contributing

If you wish to contribute (awesome!), please file an issue before filing a PR in order to avoid wasting time on a PR which may not be required. All PRs should pass `grunt lint` and maintain 100% test coverage. If something isn't covered by `lint`, please just use the existing code as an example of the style which should be used.

### Testing

Tests are run using `grunt` or `npm`, and written using [Mocha](https://mochajs.org/). I aim to maintain 100% coverage where possible (both line and branch).

Tests can be run as follows:

```bash
$ npm test
$ grunt test
$ grunt # runs the default Travis loop
```


text:
package net.logicsquad.pal;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PushbackReader;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;

/**
 * The PAL abstract machine simulator.
 *
 * @author Philip Roberts <philip.roberts@gmail.com>
 * @author Paul Hoadley <paulh@logicsquad.net>
 */
public class PAL {
	/** The filename containing the program. */
	private static String filename = "CODE";

	/** A constant for code memory limit. */
	private final int CODESIZE = 1000;

	/** A constant for data stack size limit. */
	private final int DATASIZE = 500;

	/** Memory for the instructions. */
	private ArrayList codeMem;

	/** Stack for data. */
	private DataStack dataStack;

	/** The program counter. */
	private int pc;

	/** Input reader. */
	private BufferedReader inputReader;

	/**
	 * Wrapper to enable pushback of bytes into the input stream, for OPR 19.
	 */
	private PushbackReader pushBack;

	/** The number of the present exception. */
	private int currentException;

	/** Constants representing the predefined exception types. */
	private static final int reraise = 0;
	private static final int programAbort = 1;
	private static final int typeMismatch = 3;
	private static final int reachedEOF = 4;

	/**
	 * Main method for command line operation.
	 *
	 * @param args
	 *            Command line options are limited to a single filename.
	 */
	public static void main(String[] args) {
		if (args.length > 1) {
			usage();
			System.exit(1);
		} else if (args.length == 1) {
			filename = args[0];
		}

		// Make a machine and load the code.
		PAL machine = new PAL();

		// Execute.
		try {
			machine.execute();
		} catch (OutOfMemoryError e) {
			System.err.println(e.getMessage());
			System.exit(1);
		} catch (IndexOutOfBoundsException e) {
			System.err.println(e.getMessage());
			System.exit(1);
		}

		return;
	}

	/**
	 * Constructor. Reads all of the statements in {@link PAL#filename
	 * filename} into {@link Code Code} objects, and
	 * stores these objects in {@link PAL#codeMem codeMem}. The
	 * lexical analysis of the source file is quite rigid. Any deviation from
	 * the prescribed format for source files causes the machine to stop.
	 */
	public PAL() {
		// Create the code memory.
		codeMem = new ArrayList(CODESIZE);
		dataStack = new DataStack(DATASIZE);

		try {
			BufferedReader br = new BufferedReader(new FileReader(filename));
			int lineno = 1;
			String line = br.readLine();
			String mnemonic = "";
			int first = 0;
			Object second = null;
			StringTokenizer st;

			while (line != null) {
				if (lineno > CODESIZE) {
					System.err.println("Exceeded code storage limit at line "
							+ lineno);
					die(1);
				}
				st = new StringTokenizer(line);

				// It seems reasonable to allow blank lines in the
				// source.
				if (!(st.hasMoreTokens())) {
					line = br.readLine();
					lineno++;
					continue;
				}

				// May not come in groups of three, in which case,
				// catch the error.
				try {
					mnemonic = st.nextToken();
					first = Integer.parseInt(st.nextToken());
					String s = st.nextToken();
					if (s.startsWith("'")) {
						int start = line.indexOf('\'');
						int end = line.indexOf('\'', start + 1);
						second = line.substring(start, end + 1);
					} else {
						second = makeObject(s);
						if (second instanceof String) {
							System.err.println("Unrecognised second operand"
									+ " on line " + lineno);
							die(1);
						}
					}
				} catch (NoSuchElementException e) {
					System.err.println("Not enough tokens on line " + lineno);
					die(1);
				} catch (NumberFormatException e) {
					System.err.println("First operand non-integer on line "
							+ lineno);
					die(1);
				}
				codeMem.add(new Code(mnemonic, first, second, lineno));
				line = br.readLine();
				lineno++;
			}

			// Set up the input reader.
			pushBack = new PushbackReader(new InputStreamReader(System.in));
			// Note: the internal buffer of the BufferedReader is set
			// to 1 (the smallest possible) so that it won't buffer up
			// to EOF, thereby confusing OPR 19.
			inputReader = new BufferedReader(pushBack, 1);
		} catch (FileNotFoundException e) {
			usage();
			System.exit(1);
		} catch (IOException e) {
			System.err.println(e);
			System.exit(1);
		}

		currentException = 0;

		return;
	}

	/**
	 * Execute the instructions in the machine's code memory. The instructions
	 * are implemented in accordance with the specification found here: The
	 * PAL Machine.
	 */
	private void execute() {
		// Initialise program counter.
		pc = 0;

		Code currInst;

		while (pc < codeMem.size()) {
			currInst = codeMem.get(pc);

			// Bump the program counter.
			pc++;

			// Object to pull out of currInst.second.
			Object o = currInst.getSecond();

			Data tos, ntos, returnPoint, loadedVal;

			switch (Mnemonic.mnemonicToInt(currInst.getMnemonic())) {
			case Mnemonic.CAL:
				// Procedure/function call.

				// Set return point field in stack mark.
				returnPoint = dataStack.get(dataStack.getTop()
						- currInst.getFirst() - 2);
				returnPoint.setType(Data.INT);
				returnPoint.setValue(new Integer(pc));

				// Set new frame base.
				dataStack.setBase(dataStack.getTop() - currInst.getFirst());

				// Jump to procedure/function code. Note that while
				// the PAL instructions start from 1, our code store
				// is indexed from 0.
				pc = ((Integer) currInst.getSecond()).intValue() - 1;

				break;
			case Mnemonic.INC:
				// Push space onto the stack.

				if (!(o instanceof Integer)) {
					error(currInst, "Argument to INC must be an integer.");
					die(1);
				} else {
					dataStack.incTop(((Integer) o).intValue());
				}
				break;
			case Mnemonic.JIF:
				// Jump if false.

				if (!(o instanceof Integer)) {
					error(currInst, "Argument to JIF must be an integer.");
					die(1);
				}

				tos = dataStack.pop();

				if (tos.getType() != Data.BOOL) {
					dataStack.push(tos);
					error(currInst, "JIF - top of stack not a boolean.");
					die(1);
				}

				if (!((Boolean) tos.getValue()).booleanValue()) {
					int destination = ((Integer) o).intValue();

					if (destination < 1 || destination > codeMem.size()) {
						dataStack.push(tos);
						error(currInst, "JIF - attempt to jump outside code.");
						die(1);
					}

					// Our code store uses zero-based indexing. For
					// compatibility reasons, addresses start at 1.
					pc = destination - 1;
				}

				break;
			case Mnemonic.JMP:
				// Unconditional jump.

				if (!(o instanceof Integer)) {
					error(currInst, "Argument to JMP must be an integer.");
					die(1);
				}

				int destination = ((Integer) o).intValue();

				if (destination == 0) {
					// "JMP 0 0" signifies program termination.
					die(0);
				}

				if (destination < 1 || destination > codeMem.size()) {
					error(currInst, "JMP - attempt to jump outside code.");
					die(1);
				}

				// Our code store uses zero-based indexing. For
				// compatibility reasons, addresses start at 1.
				pc = destination - 1;

				break;
			case Mnemonic.LCI:
				// Load an integer constant onto the stack.

				if (!(o instanceof Integer)) {
					error(currInst, "Argument to LCI must be an integer.");
					die(1);
				} else {
					dataStack.push(new Data(Data.INT, o));
				}
				break;
			case Mnemonic.LCR:
				// Load a real constant onto the stack.

				if (o instanceof Integer) {
					o = new Float(((Integer) o).floatValue());
				}

				if (!(o instanceof Float)) {
					error(currInst, "Argument to LCR must be a real.");
					die(1);
				} else {
					dataStack.push(new Data(Data.REAL, o));
				}
				break;
			case Mnemonic.LCS:
				// Load a string constant onto the stack.

				if (!(o instanceof String)) {
					error(currInst, "Argument to LCS must be a string.");
					die(1);
				} else {
					if (!(((String) o).startsWith("'") && (((String) o)
							.endsWith("'")))) {
						error(currInst,
								"String must be delimited by single-quotes.");
						die(1);
					} else {
						String oS = (String) o;
						oS = oS.substring(1, oS.length() - 1);
						dataStack.push(new Data(Data.STRING, oS));
					}
				}
				break;
			case Mnemonic.LDA:
				// Load the address of a stack location onto the top
				// of the stack.

				if (!(o instanceof Integer)) {
					error(currInst, "Argument to LDA must be an integer.");
					die(1);
				}

				int address = dataStack.getAddress(currInst.getFirst(),
						((Integer) o).intValue());

				dataStack.push(new Data(Data.INT, new Integer(address)));

				break;
			case Mnemonic.LDI:
				// Load the value addressed by the top of stack.

				tos = dataStack.pop();

				if (tos.getType() != Data.INT) {
					dataStack.push(tos);
					error(currInst, "LDI - top of stack must be an integer.");
					die(1);
				}

				address = ((Integer) tos.getValue()).intValue();

				loadedVal = dataStack.get(address);

				dataStack.push((Data) loadedVal.clone());

				break;
			case Mnemonic.LDV:
				// Load a value from elsewhere in the stack onto the
				// top.

				if (!(o instanceof Integer)) {
					error(currInst, "Argument to LDV must be an integer");
					die(1);
				}

				loadedVal = dataStack.get(currInst.getFirst(),
						((Integer) o).intValue());

				dataStack.push((Data) loadedVal.clone());

				break;
			case Mnemonic.LDU:
				// Load an uninitialised value onto the top of the
				// stack.

				dataStack.push(new Data(Data.UNDEF, null));

				break;
			case Mnemonic.MST:
				// Mark the stack in preparation for a
				// procedure/function call.

				int staticLink = dataStack.getAddress(currInst.getFirst(), 0);
				int dynamicLink = dataStack.getAddress(0, 0);

				dataStack.markStack(staticLink, dynamicLink);

				break;
			case Mnemonic.OPR:
				doOperation(currInst);
				break;
			case Mnemonic.RDI:
				// Read an integer from stdin.

				String intLine = "";
				try {
					intLine = inputReader.readLine();
					if (intLine == null) {
						// EOF reached.
						currentException = reachedEOF;
						raiseException(currInst);
						break;
					}
					int intVal = Integer.parseInt(intLine);
					// Put the val in the stack.
					loadedVal = dataStack.get(currInst.getFirst(),
							((Integer) o).intValue());
					loadedVal.setType(Data.INT);
					loadedVal.setValue(new Integer(intVal));
				} catch (IOException e1) {
					System.err.println(e1);
				} catch (NumberFormatException e2) {
					currentException = typeMismatch;
					raiseException(currInst);
				}
				break;
			case Mnemonic.RDR:
				// Read a real from stdin.

				String realLine = "";
				try {
					realLine = inputReader.readLine();
					if (realLine == null) {
						// EOF reached.
						currentException = reachedEOF;
						raiseException(currInst);
						break;
					}
					float realVal = Float.parseFloat(realLine);
					// Put the val in the stack.
					loadedVal = dataStack.get(currInst.getFirst(),
							((Integer) o).intValue());
					loadedVal.setType(Data.REAL);
					loadedVal.setValue(new Float(realVal));
				} catch (IOException e1) {
					System.err.println(e1);
				} catch (NumberFormatException e2) {
					currentException = typeMismatch;
					raiseException(currInst);
				}
				break;
			case Mnemonic.REH:
				// Register an exception handler with the current
				// stack mark.

				if (!(o instanceof Integer)) {
					error(currInst, "Argument to REH must be an integer.");
					die(1);
				}

				// Get the location of the exception handler pointer
				// in the highest stack mark.
				loadedVal = dataStack.get(0, -1);

				loadedVal.setType(Data.INT);
				loadedVal.setValue(o);

				break;
			case Mnemonic.SIG:
				// If the argument is 0 (the predefined "re-raise"
				// code), re-raise the current exception. Otherwise,
				// raise the exception specified by the argument.

				if (!(o instanceof Integer)) {
					error(currInst, "Argument to SIG must be an integer.");
					die(1);
				}

				int excType = ((Integer) o).intValue();
				if (excType != reraise) {
					currentException = excType;
				} else {
					// Re-raise the current exception. SIG 0 0 is
					// typically called by an exception handler when
					// it can't handle the current exception type. We
					// don't want to run that same handler again! A
					// simple way to achieve this is to nullify the
					// current exception handler pointer.
					Data handlerLocation = dataStack.get(0, -1);
					handlerLocation.setValue(new Integer(0));
				}

				// Raise the exception...
				raiseException(currInst);

				break;
			case Mnemonic.STI:
				// Store the value in the top-of-stack - 1 in the
				// address specified by the number in top-of-stack.

				tos = dataStack.pop();

				if (tos.getType() != Data.INT) {
					dataStack.push(tos);
					error(currInst, "STI - top of stack must be an integer.");
					die(1);
				}

				ntos = dataStack.pop();
				int loadAddress = ((Integer) tos.getValue()).intValue();
				loadedVal = dataStack.get(loadAddress);

				loadedVal.setType(ntos.getType());
				loadedVal.setValue(ntos.getValue());

				break;
			case Mnemonic.STO:
				// Store the value on top of the stack in the location
				// indicated.

				if (!(o instanceof Integer)) {
					error(currInst, "Argument to STO must be an integer.");
					die(1);
				}

				tos = dataStack.pop();
				loadedVal = dataStack.get(currInst.getFirst(),
						((Integer) o).intValue());

				loadedVal.setType(tos.getType());
				loadedVal.setValue(tos.getValue());

				break;
			default:
				System.out.println(currInst.getMnemonic()
						+ ": not implemented.");
			}
		}

		System.err.println("Program failed to execute a termination"
				+ " instruction (JMP 0 0).");
		die(1);
	}

	/**
	 * Perform the operation referenced by an OPR instruction. This
	 * method is provided separately to {@link PAL#execute execute}
	 * to avoid placing the rather lengthy switch statement in that
	 * method.
	 *
	 * @param currInst
	 *            The current Code object to be executed. If it
	 *            reaches here, that object contains an OPR
	 *            mnemonic.
	 */
	public void doOperation(Code currInst) {
		Object o = currInst.getSecond();
		int opr;
		if (!(o instanceof Integer)) {
			error(currInst, "Argument to OPR must be an integer.");
			die(1);
		}
		opr = ((Integer) o).intValue();
		if (opr < 0 || opr > 31) {
			error(currInst, "Argument to OPR must be in range 0-31.");
			die(1);
		}

		Data returnPoint, tos, ntos, dynamicLink;

		switch (opr) {
		case 0:
			// Procedure return.

			// Set program counter.
			returnPoint = dataStack.get(0, -2);
			pc = ((Integer) returnPoint.getValue()).intValue();

			// Remember the dynamic link.
			dynamicLink = dataStack.get(0, -3);

			// Pop data from the stack back down to the last frame.
			int popCount = dataStack.getTop() - dataStack.getAddress(0, -4);

			for (int i = 0; i < popCount; i++) {
				dataStack.pop();
			}

			// Set the new frame base using the remembered dynamic
			// link.
			dataStack.setBase(((Integer) dynamicLink.getValue()).intValue());

			break;
		case 1:
			// Function return.

			tos = dataStack.pop();

			// Set program counter.
			returnPoint = dataStack.get(0, -2);
			pc = ((Integer) returnPoint.getValue()).intValue();

			// Remember the dynamic link.
			dynamicLink = dataStack.get(0, -3);

			// Pop data from the stack back down to the last frame.
			popCount = dataStack.getTop() - dataStack.getAddress(0, -4);

			for (int i = 0; i < popCount; i++) {
				dataStack.pop();
			}

			// Set the new frame base using the remembered dynamic
			// link.
			dataStack.setBase(((Integer) dynamicLink.getValue()).intValue());

			// Leave the return value on top of the stack.
			dataStack.push(tos);

			break;
		case 2:
			// Negate the value on TOS if it is an integer or real.

			tos = dataStack.peek();
			if (tos.getType() == Data.INT) {
				int oldValue = ((Integer) tos.getValue()).intValue();
				tos.setValue(new Integer(-oldValue));
			} else if (tos.getType() == Data.REAL) {
				float oldValue = ((Float) tos.getValue()).floatValue();
				tos.setValue(new Float(-oldValue));
			} else {
				error(currInst, "Cannot negate boolean, string or UNDEF value.");
				die(1);
			}
			break;
		case 3:
		case 4:
		case 5:
		case 6:
			// Pop values at TOS and TOS-1,
			// add/subtract/multiply/divide them (depending on the
			// opcode) and push result onto TOS.

			tos = dataStack.pop();
			ntos = dataStack.pop();
			if (ntos.getType() != tos.getType()) {
				dataStack.push(ntos);
				dataStack.push(tos);
				error(currInst, "Values for arithmetic operations must be"
						+ " of same type.");
				die(1);
			} else {
				int type = tos.getType();
				if (type != Data.INT && type != Data.REAL) {
					dataStack.push(ntos);
					dataStack.push(tos);
					error(currInst, "Values for arithmetic operations must be"
							+ " of type integer or real.");
					die(1);
				}
				if (type == Data.INT) {
					int int1 = ((Integer) ntos.getValue()).intValue();
					int int2 = ((Integer) tos.getValue()).intValue();
					switch (opr) {
					case 3:
						dataStack.push(new Data(Data.INT, new Integer(int1
								+ int2)));
						break;
					case 4:
						dataStack.push(new Data(Data.INT, new Integer(int1
								- int2)));
						break;
					case 5:
						dataStack.push(new Data(Data.INT, new Integer(int1
								* int2)));
						break;
					case 6:
						if (int2 == 0) {
							dataStack.push(ntos);
							dataStack.push(tos);
							error(currInst, "Attempt to divide by zero.");
							die(1);
						}

						dataStack.push(new Data(Data.INT, new Integer(int1
								/ int2)));
						break;
					default:
					}
				} else {
					float flt1 = ((Float) ntos.getValue()).floatValue();
					float flt2 = ((Float) tos.getValue()).floatValue();
					switch (opr) {
					case 3:
						dataStack.push(new Data(Data.REAL, new Float(flt1
								+ flt2)));
						break;
					case 4:
						dataStack.push(new Data(Data.REAL, new Float(flt1
								- flt2)));
						break;
					case 5:
						dataStack.push(new Data(Data.REAL, new Float(flt1
								* flt2)));
						break;
					case 6:
						if (flt2 == 0) {
							dataStack.push(ntos);
							dataStack.push(tos);
							error(currInst, "Attempt to divide by zero.");
							die(1);
						}

						dataStack.push(new Data(Data.REAL, new Float(flt1
								/ flt2)));
						break;
					default:
					}
				}
			}
			break;
		case 7:
			// Raise the value at TOS-1 to the power of the value at
			// TOS, pop both and push the result.

			if (dataStack.peek().getType() != Data.INT) {
				error(currInst, "Exponent must be of type integer.");
				die(1);
			}
			tos = dataStack.pop();
			int exponent = ((Integer) tos.getValue()).intValue();

			int baseType = dataStack.peek().getType();
			if (baseType != Data.INT && baseType != Data.REAL) {
				error(currInst, "Base must be of type integer or real.");
				die(1);
			}
			ntos = dataStack.pop();
			if (baseType == Data.INT) {
				int base = ((Integer) ntos.getValue()).intValue();
				int intAnswer = (int) Math.pow(base, exponent);
				dataStack.push(new Data(Data.INT, new Integer(intAnswer)));
			} else {
				float base = ((Float) ntos.getValue()).floatValue();
				float floatAnswer = (float) Math.pow(base, exponent);
				dataStack.push(new Data(Data.REAL, new Float(floatAnswer)));
			}
			break;
		case 8:
			// String concatenation.

			tos = dataStack.pop();
			ntos = dataStack.pop();
			if (tos.getType() != Data.STRING || ntos.getType() != Data.STRING) {
				dataStack.push(ntos);
				dataStack.push(tos);
				error(currInst,
						"Both arguments to OPR 8 must be of type string.");
				die(1);
			}
			String sResult = (String) ntos.getValue();
			sResult += (String) tos.getValue();
			dataStack.push(new Data(Data.STRING, sResult));
			break;
		case 9:
			// Test if TOS is an odd integer.

			if (dataStack.peek().getType() != Data.INT) {
				error(currInst, "Argument to OPR 9 must be of type integer.");
				die(1);
			} else {
				tos = dataStack.pop();
				// NB the % operator will give a negative for a
				// negative number.
				if (Math.abs(((Integer) tos.getValue()).intValue() % 2) == 1) {
					dataStack.push(new Data(Data.BOOL, new Boolean(true)));
				} else {
					dataStack.push(new Data(Data.BOOL, new Boolean(false)));
				}
			}
			break;
		case 10:
		case 11:
		case 12:
		case 13:
		case 14:
		case 15:
			// Pop values at TOS and TOS-1, compare them (depending on
			// the opcode) and push result onto TOS.

			tos = dataStack.pop();
			ntos = dataStack.pop();

			if (ntos.getType() != tos.getType()) {
				dataStack.push(ntos);
				dataStack.push(tos);
				error(currInst, "Values for arithmetic operations must be"
						+ " of same type.");
				die(1);
			} else {
				int type = tos.getType();
				if (type != Data.INT && type != Data.REAL) {
					dataStack.push(ntos);
					dataStack.push(tos);
					error(currInst, "Values for arithmetic operations must be"
							+ " of type integer or real.");
					die(1);
				}
				if (type == Data.INT) {
					int int1 = ((Integer) ntos.getValue()).intValue();
					int int2 = ((Integer) tos.getValue()).intValue();
					switch (opr) {
					case 10:
						dataStack.push(new Data(Data.BOOL, new Boolean(
								int1 == int2)));
						break;
					case 11:
						dataStack.push(new Data(Data.BOOL, new Boolean(
								int1 != int2)));
						break;
					case 12:
						dataStack.push(new Data(Data.BOOL, new Boolean(
								int1 < int2)));
						break;
					case 13:
						dataStack.push(new Data(Data.BOOL, new Boolean(
								int1 >= int2)));
						break;
					case 14:
						dataStack.push(new Data(Data.BOOL, new Boolean(
								int1 > int2)));
						break;
					case 15:
						dataStack.push(new Data(Data.BOOL, new Boolean(
								int1 <= int2)));
						break;
					default:
					}
				} else {
					float flt1 = ((Float) ntos.getValue()).floatValue();
					float flt2 = ((Float) tos.getValue()).floatValue();
					switch (opr) {
					case 10:
						dataStack.push(new Data(Data.BOOL, new Boolean(
								flt1 == flt2)));
						break;
					case 11:
						dataStack.push(new Data(Data.BOOL, new Boolean(
								flt1 != flt2)));
						break;
					case 12:
						dataStack.push(new Data(Data.BOOL, new Boolean(
								flt1 < flt2)));
						break;
					case 13:
						dataStack.push(new Data(Data.BOOL, new Boolean(
								flt1 >= flt2)));
						break;
					case 14:
						dataStack.push(new Data(Data.BOOL, new Boolean(
								flt1 > flt2)));
						break;
					case 15:
						dataStack.push(new Data(Data.BOOL, new Boolean(
								flt1 <= flt2)));
						break;
					default:
					}
				}
			}
			break;
		case 16:
			// Logical complement the top element of the stack.

			tos = dataStack.pop();

			if (tos.getType() != Data.BOOL) {
				dataStack.push(tos);
				error(currInst, "Top of stack must be a boolean.");
				die(1);
			}

			boolean bResult = !((Boolean) tos.getValue()).booleanValue();
			dataStack.push(new Data(Data.BOOL, new Boolean(bResult)));
			break;
		case 17:
			// Push boolean true on TOS.

			dataStack.push(new Data(Data.BOOL, new Boolean(true)));
			break;
		case 18:
			// Push boolean false on TOS

			dataStack.push(new Data(Data.BOOL, new Boolean(false)));
			break;
		case 19:
			// Test for EOF.

			try {
				int nextByte = pushBack.read();
				if (nextByte == -1) {
					dataStack.push(new Data(Data.BOOL, new Boolean(true)));
				} else {
					dataStack.push(new Data(Data.BOOL, new Boolean(false)));
					pushBack.unread(nextByte);
				}
			} catch (IOException e) {
				System.err.println(e);
			}
			break;
		case 20:
			// Pop value on TOS and print it.

			if (dataStack.peek().getType() == Data.BOOL
					|| dataStack.peek().getType() == Data.UNDEF) {
				error(currInst, "OPR 20 can only print values"
						+ " of type integer, real or string.");
				die(1);
			} else {
				tos = dataStack.pop();
				System.out.print(tos);
			}
			break;
		case 21:
			// Print a newline.

			System.out.println();
			break;
		case 22:
			// Swap the top two elements on the stack.

			tos = dataStack.pop();
			ntos = dataStack.pop();
			dataStack.push(tos);
			dataStack.push(ntos);
			break;
		case 23:
			// Duplicate the element at the top of the stack.

			tos = dataStack.peek();
			dataStack.push((Data) tos.clone());
			break;
		case 24:
			// Discard the element at the top of the stack.

			dataStack.pop();
			break;
		case 25:
			// Convert the integer at TOS to a real.

			if (dataStack.peek().getType() != Data.INT) {
				error(currInst, "Integer to real conversion can only be"
						+ " performed on a value of type integer.");
				die(1);
			}
			float fAns = ((Integer) dataStack.pop().getValue()).floatValue();
			dataStack.push(new Data(Data.REAL, new Float(fAns)));
			break;
		case 26:
			// Convert the real at TOS to an integer.

			if (dataStack.peek().getType() != Data.REAL) {
				error(currInst, "Real to integer conversion can only be"
						+ " performed on a value of type real.");
				die(1);
			}
			int iResult = ((Float) dataStack.pop().getValue()).intValue();
			dataStack.push(new Data(Data.INT, new Integer(iResult)));
			break;
		case 27:
			// Convert the integer at TOS to a string.

			if (dataStack.peek().getType() != Data.INT) {
				error(currInst, "Integer to string conversion can only be"
						+ " performed on a value of type integer.");
				die(1);
			}
			dataStack.push(new Data(Data.STRING, dataStack.pop().getValue()
					.toString()));
			break;
		case 28:
			// Convert the real at TOS to a string.

			if (dataStack.peek().getType() != Data.REAL) {
				error(currInst, "Real to string conversion can only be"
						+ " performed on value of type real.");
				die(1);
			}
			dataStack.push(new Data(Data.STRING, dataStack.pop().getValue()
					.toString()));
			break;
		case 29:
			// Logical and of two booleans.

			tos = dataStack.pop();
			ntos = dataStack.pop();
			if (tos.getType() != Data.BOOL || ntos.getType() != Data.BOOL) {
				dataStack.push(ntos);
				dataStack.push(tos);
				error(currInst, "Logical and can only be"
						+ " performed on values of type boolean.");
				die(1);
			}
			boolean bool1 = ((Boolean) tos.getValue()).booleanValue();
			boolean bool2 = ((Boolean) ntos.getValue()).booleanValue();
			dataStack.push(new Data(Data.BOOL, new Boolean(bool1 && bool2)));
			break;
		case 30:
			// Logical or of two booleans.

			tos = dataStack.pop();
			ntos = dataStack.pop();
			if (tos.getType() != Data.BOOL || ntos.getType() != Data.BOOL) {
				dataStack.push(ntos);
				dataStack.push(tos);
				error(currInst, "Logical or can only be"
						+ " performed on values of type boolean.");
				die(1);
			}
			bool1 = ((Boolean) tos.getValue()).booleanValue();
			bool2 = ((Boolean) ntos.getValue()).booleanValue();
			dataStack.push(new Data(Data.BOOL, new Boolean(bool1 || bool2)));
			break;
		case 31:
			// Test whether the current exception code is the same as
			// the integer on TOS.

			tos = dataStack.pop();
			if (tos.getType() != Data.INT) {
				dataStack.push(tos);
				error(currInst, "OPR 0 31 expects an integer value"
						+ "on top of the stack.");
				die(1);
			}

			int testValue = ((Integer) tos.getValue()).intValue();
			boolean pushValue = testValue == currentException;

			dataStack.push(new Data(Data.BOOL, new Boolean(pushValue)));
			break;
		default:
			System.out.println("OPR " + opr + ": not implemented.");
		}
		return;
	}

	/**
	 * Make an Object from a String. Because the type
	 * of the third field in a single instruction is not pre-defined, we need to
	 * be able to expect an int, a float or a
	 * String. To simplify the storage, we handle each of them as
	 * an Object anyway, so ints and
	 * floats are wrapped by Integer and
	 * Float respectively.
	 *
	 * @param input
	 *            A String.
	 * @return An Object which is either a String,
	 *         Integer or Float.
	 */
	private Object makeObject(String input) {
		// We are expecting an integer, real or string.
		Object output;
		try {
			output = new Integer(input);
			return output;
		} catch (NumberFormatException e1) {
			try {
				output = new Float(input);
				return output;
			} catch (NumberFormatException e2) {
				return input;
			}
		}
	}

	/**
	 * Raise an exception - look down through stack frames for an exception
	 * handler.
	 *
	 * This method uses the {@link PAL#currentException
	 * currentException} variable to determine which exception to
	 * raise. Exception 1 (Program Abort) cannot be caught, so the program just
	 * terminates. All other exceptions are treated equally.
	 *
	 * @param currInst
	 *            The Code object which caused the exception. Used
	 *            to add information to error messages.
	 */
	private void raiseException(Code currInst) {
		// The Program Abort signal cannot be caught.
		if (currentException == programAbort) {
			error(currInst, "A Program Abort signal was raised.");
			die(1);
		}

		Data handlerLocation, dynamicLink;
		int handlerAddress;

		boolean moreFrames = true;

		while (true) {
			handlerLocation = dataStack.get(0, -1);

			if (handlerLocation.getType() != Data.INT) {
				error(currInst, "Exception handler address must be an integer.");
				die(1);
			}

			handlerAddress = ((Integer) handlerLocation.getValue()).intValue();

			if (handlerAddress < 0 || handlerAddress > codeMem.size()) {
				error(currInst, "Exception handler address out of code range.");
				die(1);
			}

			if (handlerAddress == 0) {
				// An address of 0 means no handler - throw away this
				// frame and keep searching.

				// First, check if this is the lowest frame - the
				// lowest frame's stack mark begins at address 0.
				if (dataStack.getAddress(0, -4) == 0) {
					moreFrames = false;
					break;
				}

				// Remember the dynamic link.
				dynamicLink = dataStack.get(0, -3);

				// Pop data from the stack back down to the previous
				// frame.
				int pops = dataStack.getTop() - dataStack.getAddress(0, -4);

				for (int i = 0; i < pops; i++) {
					dataStack.pop();
				}

				// Set the new frame base using the remembered dynamic
				// link.
				int baseAddr = ((Integer) dynamicLink.getValue()).intValue();
				dataStack.setBase(baseAddr);
			} else {
				// There is an exception handler.
				pc = handlerAddress - 1;

				// Stop throwing out frames.
				break;
			}
		}

		if (!moreFrames) {
			// No handler was found.
			error(currInst, "Exception #" + currentException
					+ " never handled!");
			die(1);
		}
	}

	/**
	 * Print an error. Errors are almost invariably unrecoverable, so this
	 * method announces the error, prints the offending instruction and dumps
	 * the stack.
	 *
	 * @param currInst
	 *            The offending Code object.
	 * @param s
	 *            A context-dependent error message to be printed.
	 */
	private void error(Code currInst, String s) {
		// Ensure the error is always started on a new line.
		System.err.println();
		System.err.println("Runtime Error:");
		System.err.println(filename + ":" + currInst.getLineNo() + ":" + s);
		System.err.println(currInst);
		System.err.println("\nStack dump:");
		System.err.println("----------");
		System.err.print(dataStack);
		return;
	}

	/**
	 * Die due to an error.
	 *
	 * @param err
	 *            An arbitrary error code. This integer is returned to the
	 *            operating system via the System.exit method.
	 */
	private void die(int err) {
		System.exit(err);
	}

	/**
	 * Simple usage information.
	 */
	private static void usage() {
		System.out.println("usage: java -jar PAL.jar [filename]");
		return;
	}
}


text:
'use strict';
const request = require('request-promise');

const apiBaseEndpoint = 'https://api.spotify.com';
const endpoints = {
  track: '/v1/tracks/'
};

function parseUri(uri) {
  // x-sonos-spotify:spotify%3atrack%3a3WKg25vrbjJlkhsgl2W4p3?sid=9&flags=8224&sn=9
  let id;

  const matches = /spotify%3atrack%3a([\w\d]+)/i.exec(uri);

  if (matches) {
    id = matches[1];
  }

  return {
    id
  };

}

function tryGetHighResArt(uri) {
  let trackInfo = parseUri(uri);

  let apiUrl = [apiBaseEndpoint, endpoints.track, trackInfo.id].join('');

  return request({
    url: apiUrl,
    json: true
  })
    .then((response) => {
      return response.album.images.length ? response.album.images[0].url : null;
    });
}

module.exports = function (services) {
  services[9] = {
    tryGetHighResArt
  };
};


text:
<?php
/**
 * Created by PhpStorm.
 * User: Pavel
 * Date: 2014-05-31
 * Time: 21:58
 */

namespace NemesisPlatform\Core\Account\Form\Type;

use NemesisPlatform\Core\Account\Entity\Phone;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class PhoneType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'phonenumber',
            'text',
            [
                'pattern' => '\d{10}',
                'label'   => 'Номер телефона',
            ]
        );
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            ['data_class' => Phone::class]
        );
    }

    /**
     * Returns the name of this type.
     *
     * @return string The name of this type
     */
    public function getName()
    {
        return 'phone_type';
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="GENERATOR" content="VSdocman - documentation generator; https://www.helixoft.com" />
	<link rel="icon" href="favicon.ico">
	<title>JobVacancyDetailDto Class</title>

	<link rel="stylesheet" type="text/css" href="msdn2019/toc.css" />

	<link rel="stylesheet" type="text/css" href="msdn2019/msdn2019.css"></link>

	<link href="SyntaxHighlighter/styles/shCore.css" rel="stylesheet" type="text/css" />
	<link href="SyntaxHighlighter/styles/shThemeMsdnLW.css" rel="stylesheet" type="text/css" />

 <link rel="stylesheet" type="text/css" href="vsdocman_overrides.css"></link>

logo

SOLUTION-WIDE PROPERTIES Reference

     <form id="search-bar" action="search--.html">
      <input id="HeaderSearchInput" type="search" name="search" placeholder="Search" >
      <button id="btn-search" class="c-glyph" title="Search">
      Search
     </button>
     </form>
     <button id="cancel-search" class="cancel-search" title="Cancel">
     Cancel
    </button>

JobVacancyDetailDto Class

        Namespace:
Tlece.Recruitment.Models.RecruitmentPlanning

Assembly: Tlece.Recruitment (in Tlece.Recruitment.dll)

					VB

					C#

					F#

					C++

					JScript

					Copy

Public Class JobVacancyDetailDto
    Inherits TleceBaseResponseModel

This language is not supported or no code example is available.

					VB

					C#

					F#

					C++

					JScript

					Copy

public class JobVacancyDetailDto : TleceBaseResponseModel

This language is not supported or no code example is available.

					VB

					C#

					F#

					C++

					JScript

					Copy

public ref class JobVacancyDetailDto : public TleceBaseResponseModel^

This language is not supported or no code example is available.

					VB

					C#

					F#

					C++

					JScript

					Copy

public class JobVacancyDetailDto
   extends TleceBaseResponseModel

This language is not supported or no code example is available.

		Properties

        Name

        Description

	ApplyPostVacancyId

	CompanyAddress

	CompanyCvVideo

	CompanyLogo

	CompanyName

	EndDate

	Interview

	IsInterviewScheduled

	JobCoverPhoto

	JobDescription

	JobTitle

	JobVacancy

	JobVacancyId

	JobVideos

	LocationName

	Notes

	ResponseCode

(inherited from TleceBaseResponseModel).

	ResponseMessage

(inherited from TleceBaseResponseModel).

	RoomId

	Salary

	Slots

	StageId

	StartDate

	WorkArea

    Top

		Methods

        Name

        Description

	Equals(Object)

Determines whether the specified object is equal to the current object.
(inherited from Object).

	Finalize

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
(inherited from Object).

	GetHashCode

Serves as the default hash function.
(inherited from Object).

	GetType

Gets the Type of the current instance.
(inherited from Object).

	MemberwiseClone

Creates a shallow copy of the current Object.
(inherited from Object).

	ToString

Returns a string that represents the current object.
(inherited from Object).

    Top

		Extension Methods

        Name

        Description

	SetError(this TleceBaseResponseModel, string)

(Defined by TleceBaseResponseModelExtension).

	SetOk(this TleceBaseResponseModel, string)

(Defined by TleceBaseResponseModelExtension).

    Top

		Inheritance Hierarchy

System.Object

Tlece.Common.Models.TleceBaseResponseModel

Tlece.Recruitment.Models.RecruitmentPlanning.JobVacancyDetailDto

		Applies to

.NET Framework
Supported in: 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1

		See Also

	Tlece.Recruitment.Models.RecruitmentPlanning Namespace

In this article

					Definition

Generated with unregistered version of VSdocman
Your own footer text will only be shown in registered version.


text:
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.235
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace PrecompiledMvcLibrary.Views.Home
{

    [System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "1.0.0.0")]
    [System.Web.WebPages.PageVirtualPathAttribute("~/Views/Home/About.cshtml")]
    public class About : System.Web.Mvc.WebViewPage<dynamic>
    {
        public About()
        {
        }
        public override void Execute()
        {

#line 1 "D:\forks\razorsinglefilegenerator\samples\PrecompiledMvcLibrary\Views\Home\About.cshtml"

            ViewBag.Title = "About Us";

#line default
#line hidden
            WriteLiteral("\r\n
About
\r\n
\r\n     Put content here.\r\n
\r\n");

        }
    }
}
#pragma warning restore 1591


text:
import {Component} from '@angular/core';
import {TranslateService} from "@ngx-translate/core";

@Component({
    selector: 'app-header',
    templateUrl: './header.component.html'
})
export class HeaderComponent
{
    constructor(
        public translate: TranslateService
    ) {}
}


text:
'Copyright 2013 Esri
'Licensed under the Apache License, Version 2.0 (the "License");
'You may not use this file except in compliance with the License.
'You may obtain a copy of the License at
'http://www.apache.org/licenses/LICENSE-2.0
'Unless required by applicable law or agreed to in writing, software
'distributed under the License is distributed on an "AS IS" BASIS,
'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'See the License for the specific language governing permissions and
'limitations under the License.
Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports System.ComponentModel
Imports ESRI.ArcGIS.Client
Imports ESRI.ArcGIS.Client.Geometry
Imports ESRI.ArcGIS.Client.Toolkit
Imports ESRI.ArcGIS.Client.Tasks
Imports Toolkit.Icons
Imports System.Windows.Controls.Primitives
Imports System.Windows.Data

Namespace FrostedTabsVB
  Partial Public Class MainPage
    Inherits UserControl
    Private _panFactor As Double = 0.5
    Private layerResolutions() As Double

    Private zoomSetUp As Boolean = False
    Private settingZoomLevel As Boolean = False
    Private currentLevel As Integer = 0
    Private startPoint As Point
    Private rotationAngle As Double = 0
    Private startRotationAngle As Double = 0

    Private levelGreaterThanBrush As SolidColorBrush
    Private levelLessThanBrush As SolidColorBrush
    Private levelEqualsBrush As SolidColorBrush
    Private ribbonElementBackground As LinearGradientBrush
    Private ribbonElementBackgroundHighlight As LinearGradientBrush

    Private _drawSurface As Draw
    Private _queryTask As QueryTask

    Public Sub New()
      InitializeComponent()
      Dim rd As ResourceDictionary = Application.Current.Resources
      levelGreaterThanBrush = TryCast(rd("levelGreaterThanBrush"), SolidColorBrush)
      levelLessThanBrush = TryCast(rd("levelLessThanBrush"), SolidColorBrush)
      levelEqualsBrush = TryCast(rd("levelEqualsBrush"), SolidColorBrush)
      ribbonElementBackground = TryCast(rd("RibbonElementBackground"), LinearGradientBrush)
      ribbonElementBackgroundHighlight = TryCast(rd("RibbonElementBackgroundHighlight"), LinearGradientBrush)

      _drawSurface = New Draw(Map) With {.LineSymbol = DefaultLineSymbol, .FillSymbol = DefaultFillSymbol}
      AddHandler _drawSurface.DrawComplete, AddressOf MyDrawSurface_DrawComplete

      _queryTask = New QueryTask("http://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer/2")
      AddHandler _queryTask.ExecuteCompleted, AddressOf QueryTask_ExecuteCompleted
      AddHandler _queryTask.Failed, AddressOf QueryTask_Failed
    End Sub

#Region "Startup Event Handlers"

    Private Sub ArcGISTiledMapServiceLayer_Initialized(ByVal sender As Object, ByVal e As EventArgs)
      If Not zoomSetUp Then
        SetUpZoom()
      End If
    End Sub

    Private Sub Map_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
      AddHandler Map.ExtentChanged, AddressOf Map_ExtentChanged
    End Sub

#End Region

#Region "Event Handlers"

    Private Sub Map_ExtentChanged(ByVal sender As Object, ByVal args As ExtentEventArgs)
      If Not zoomSetUp Then
        SetUpZoom()
      End If
      If ZoomLevelStack IsNot Nothing Then
        currentLevel = Convert.ToInt32(Math.Round(getValueFromMap(Map.Extent)))
        Dim zs As StackPanel = ZoomLevelStack
        Dim level As Integer = currentLevel
        For i As Integer = 0 To zs.Children.Count - 1
          Dim border As Border = TryCast(zs.Children(i), Border)
          Dim brush As SolidColorBrush = setLevelBrush(i)
          border.Background = brush
        Next i
      End If

    End Sub

    Private Sub PanButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      If Map Is Nothing OrElse sender Is Nothing Then
        Return
      End If

      Dim env As Envelope = Map.Extent
      If env Is Nothing Then
        Return
      End If
      Dim x As Double = 0, y As Double = 0
      Dim oldCenter As MapPoint = env.GetCenter()
      Dim newCenter As MapPoint = Nothing
      Dim height = env.Height * _panFactor
      Dim width = env.Width * _panFactor
      ' if units are degrees (the default), limit or alter panning to the lat/lon limits
      If sender Is PanUp Then ' North
        y = oldCenter.Y + height
        newCenter = New MapPoint(oldCenter.X, y)
      ElseIf sender Is PanRight Then ' East
        x = oldCenter.X + width
        newCenter = New MapPoint(x, oldCenter.Y)
      ElseIf sender Is PanLeft Then ' West
        x = oldCenter.X - width
        newCenter = New MapPoint(x, oldCenter.Y)
      ElseIf sender Is PanDown Then ' South
        y = oldCenter.Y - height
        newCenter = New MapPoint(oldCenter.X, y)
      End If

      If newCenter IsNot Nothing Then
        Map.PanTo(newCenter)
      End If

    End Sub

    Private Sub ZoomFullExtentButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      If Map IsNot Nothing Then
        Map.ZoomTo(Map.Layers.GetFullExtent())
      End If
    End Sub

    Private Sub LayoutRoot_SizeChanged(ByVal sender As Object, ByVal e As SizeChangedEventArgs)
      MapRotationGrid.Width = MapDisplayGrid.ActualWidth
      MapRotationGrid.Height = MapDisplayGrid.ActualHeight
    End Sub

    Private Sub TabItem_MouseEnter(ByVal sender As Object, ByVal e As MouseEventArgs)
      'TabItem item = sender as TabItem;
      'Int32 index = Convert.ToInt32(item.Tag);
      'tabRibbon.SelectedIndex = index;
    End Sub

    Private Sub Border_MouseEnter(ByVal sender As Object, ByVal e As MouseEventArgs)
      Dim border As Border = TryCast(sender, Border)
      border.Background = ribbonElementBackgroundHighlight

    End Sub

    Private Sub Border_MouseLeave(ByVal sender As Object, ByVal e As MouseEventArgs)
      Dim border As Border = TryCast(sender, Border)
      border.Background = ribbonElementBackground
    End Sub

    Private Sub ZoomStackGrid_MouseEnter(ByVal sender As Object, ByVal e As MouseEventArgs)
      'ZoomStackHighlight.Opacity = 1;
    End Sub

    Private Sub ZoomStackGrid_MouseLeave(ByVal sender As Object, ByVal e As MouseEventArgs)
      'ZoomStackHighlight.Opacity = 0;
    End Sub

#End Region

#Region "Zoom Level"

    Private Sub SetUpZoom()
      If ZoomLevelStack IsNot Nothing Then
        Dim resolutions As New List(Of Double)()
        For Each layer As Layer In Map.Layers
          If TypeOf layer Is TiledMapServiceLayer Then
            Dim tlayer As TiledMapServiceLayer = TryCast(layer, TiledMapServiceLayer)
            If tlayer.TileInfo Is Nothing OrElse tlayer.TileInfo.Lods Is Nothing Then
              Continue For
            End If
            Dim res = From t In tlayer.TileInfo.Lods
                      Select t.Resolution
            resolutions.AddRange(res)
          End If
        Next layer
        If resolutions.Count < 1 Then
          Return
        End If
        resolutions.Sort()
        layerResolutions = resolutions.Distinct().Reverse().ToArray()
        Dim sp As StackPanel = ZoomLevelStack
        Dim min As Integer = 0
        Dim max As Integer = layerResolutions.Length - 1
        Dim numLevels As Integer = max + 1 - min
        Dim levelHeight As Double = (100 \ numLevels)
        For i As Integer = min To max
          Dim brush As SolidColorBrush = setLevelBrush(i)
          Dim levelBorder As New Border() With {.BorderThickness = New Thickness(1), .CornerRadius = New CornerRadius(1), .Height = levelHeight, .Width = 18, .BorderBrush = New SolidColorBrush(Color.FromArgb(255, 0, 0, 0)), .Background = brush, .Tag = i}
          AddHandler levelBorder.MouseLeftButtonDown, AddressOf levelBorder_MouseLeftButtonDown
          AddHandler levelBorder.MouseMove, AddressOf levelBorder_MouseMove
          AddHandler levelBorder.MouseLeftButtonUp, AddressOf levelBorder_MouseLeftButtonUp
          sp.Children.Add(levelBorder)
        Next i
        AddHandler sp.MouseLeave, AddressOf sp_MouseLeave
        zoomSetUp = True
      End If
    End Sub

    Private Sub sp_MouseLeave(ByVal sender As Object, ByVal e As MouseEventArgs)
      If settingZoomLevel Then
        FinishSettingLevel()
      End If
    End Sub

    Private Sub levelBorder_MouseLeftButtonUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
      FinishSettingLevel()
    End Sub

    Private Sub FinishSettingLevel()
      settingZoomLevel = False
      Map.ZoomToResolution(layerResolutions(currentLevel))

    End Sub

    Private Sub levelBorder_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs)
      If settingZoomLevel Then
        Dim levelBorder As Border = TryCast(sender, Border)
        Dim level As Integer = Convert.ToInt32(levelBorder.Tag)
        Dim zs As StackPanel = ZoomLevelStack
        For i As Integer = 0 To zs.Children.Count - 1
          Dim border As Border = TryCast(zs.Children(i), Border)
          Dim brush As SolidColorBrush = setLevelBrush(i)
          border.Background = brush

        Next i
        currentLevel = level
      End If
    End Sub

    Private Sub levelBorder_MouseLeftButtonDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
      Dim levelBorder As Border = TryCast(sender, Border)
      currentLevel = Convert.ToInt32(levelBorder.Tag)
      settingZoomLevel = True
    End Sub

    Private Function getValueFromMap(ByVal extent As ESRI.ArcGIS.Client.Geometry.Envelope) As Double
      If layerResolutions Is Nothing OrElse layerResolutions.Length = 0 OrElse Map Is Nothing OrElse extent Is Nothing Then
        Return -1
      End If
      Dim mapRes As Double = extent.Width / Map.ActualWidth
      For i As Integer = 0 To layerResolutions.Length - 2
        Dim thisRes As Double = layerResolutions(i)
        Dim nextRes As Double = layerResolutions(i + 1)
        If mapRes >= thisRes Then
          Return i
        End If
        If mapRes < thisRes AndAlso mapRes > nextRes Then
          Return i + (thisRes - mapRes) / (thisRes - nextRes)
        End If
      Next i
      Return Convert.ToDouble(layerResolutions.Length - 1)
    End Function

    Private Function setLevelBrush(ByVal level As Integer) As SolidColorBrush
      Dim brush As SolidColorBrush
      If level < currentLevel Then
        brush = levelGreaterThanBrush
      ElseIf currentLevel = level Then
        brush = levelEqualsBrush
      Else
        brush = levelLessThanBrush
      End If
      Return brush
    End Function

    Private Sub ZoomOutButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)

      Map.Zoom(0.5)
    End Sub

    Private Sub ZoomInButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      Map.Zoom(2.0)
    End Sub

#End Region

#Region "Map Rotation"

    Private Sub MapRotationGrid_MouseLeftButtonDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)

      Dim mapRotator As FrameworkElement = TryCast(sender, FrameworkElement)
      startPoint = e.GetPosition(MapRotationCanvas)
      startRotationAngle = Math.Atan2(startPoint.Y, startPoint.X) / Math.PI * 180
      AddHandler mapRotator.MouseMove, AddressOf mapRotator_MouseMove
      AddHandler mapRotator.MouseLeftButtonUp, AddressOf mapRotator_MouseLeftButtonUp
      AddHandler mapRotator.MouseLeave, AddressOf mapRotator_MouseLeave

    End Sub

    Private Sub mapRotator_MouseLeave(ByVal sender As Object, ByVal e As MouseEventArgs)
      Dim mapRotator As FrameworkElement = TryCast(sender, FrameworkElement)
      finishRotation(mapRotator)
    End Sub

    Private Sub mapRotator_MouseLeftButtonUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
      Dim mapRotator As FrameworkElement = TryCast(sender, FrameworkElement)
      finishRotation(mapRotator)
    End Sub

    Private Sub mapRotator_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs)
      Dim pt As Point = e.GetPosition(MapRotationCanvas)
      Dim newAngle As Double = Math.Atan2(pt.Y, pt.X) / Math.PI * 180
      Dim diff As Double = newAngle - startRotationAngle
      Dim angle As Double = rotationAngle + diff
      Map.Rotation = angle
      RotationAngleText.Text = String.Format("{0}°", Math.Round(angle, 1))
      Dim rotate As New RotateTransform()
      rotate.Angle = angle
      RotationGlobeGrid.RenderTransform = rotate

    End Sub

    Private Sub finishRotation(ByVal mapRotator As FrameworkElement)
      RemoveHandler mapRotator.MouseMove, AddressOf mapRotator_MouseMove
      RemoveHandler mapRotator.MouseLeftButtonUp, AddressOf mapRotator_MouseLeftButtonUp
      RemoveHandler mapRotator.MouseLeave, AddressOf mapRotator_MouseLeave
      rotationAngle = Map.Rotation
    End Sub

    Private Sub ResetRotation_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      ResetMapRotation.Begin()
    End Sub

    Private Sub ResetMapRotation_Completed(ByVal sender As Object, ByVal e As EventArgs)
      ResetMapRotation.Stop()
      Map.Rotation = 0
      MapRotationTransform.Angle = 0
      RotationAngleText.Text = "0°"
      rotationAngle = 0
      RotationGlobeGrid.RenderTransform = MapRotationTransform
    End Sub

#End Region

#Region "Spatial Query"

    Private Sub SelectionTool_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      Dim button As Button = TryCast(sender, Button)
      Dim tagstring As String = CStr(button.Tag)
      Select Case tagstring
        Case "0" ' Point
          _drawSurface.DrawMode = DrawMode.Point
        Case "1" ' Polyline
          _drawSurface.DrawMode = DrawMode.Polyline
        Case "2" ' Polygon
          _drawSurface.DrawMode = DrawMode.Polygon
        Case "3" ' Rectangle
          _drawSurface.DrawMode = DrawMode.Rectangle
        Case Else ' Clear
          _drawSurface.DrawMode = DrawMode.None
          Dim selectionGraphicslayer As GraphicsLayer = TryCast(Map.Layers("MySelectionGraphicsLayer"), GraphicsLayer)
          selectionGraphicslayer.ClearGraphics()
          QueryDetailsDataGrid.ItemsSource = Nothing
          ResultsDisplay.IsExpanded = False
      End Select
      _drawSurface.IsEnabled = (_drawSurface.DrawMode <> DrawMode.None)
    End Sub

    Private Sub MyDrawSurface_DrawComplete(ByVal sender As Object, ByVal args As ESRI.ArcGIS.Client.DrawEventArgs)
      Dim selectionGraphicslayer As GraphicsLayer = TryCast(Map.Layers("MySelectionGraphicsLayer"), GraphicsLayer)
      selectionGraphicslayer.ClearGraphics()

      ' Bind data grid to query results
      Dim resultFeaturesBinding As New Binding("LastResult.Features")
      resultFeaturesBinding.Source = _queryTask
      QueryDetailsDataGrid.SetBinding(DataGrid.ItemsSourceProperty, resultFeaturesBinding)

      Dim query As Query = New ESRI.ArcGIS.Client.Tasks.Query()
      query.OutFields.AddRange(New String() {"state_name", "pop2000", "sub_region"})
      query.OutSpatialReference = Map.SpatialReference
      query.Geometry = args.Geometry
      query.SpatialRelationship = SpatialRelationship.esriSpatialRelIntersects
      query.ReturnGeometry = True

      _queryTask.ExecuteAsync(query)
    End Sub
    Private Sub QueryTask_ExecuteCompleted(ByVal sender As Object, ByVal args As ESRI.ArcGIS.Client.Tasks.QueryEventArgs)
      Dim featureSet As FeatureSet = args.FeatureSet

      If featureSet Is Nothing OrElse featureSet.Features.Count < 1 Then
        MessageBox.Show("No features retured from query")
        Return
      End If

      Dim graphicsLayer As GraphicsLayer = TryCast(Map.Layers("MySelectionGraphicsLayer"), GraphicsLayer)

      If featureSet IsNot Nothing AndAlso featureSet.Features.Count > 0 Then
        For Each feature As Graphic In featureSet.Features
          feature.Symbol = ResultsFillSymbol
          graphicsLayer.Graphics.Insert(0, feature)
        Next feature
      End If

      'ResultsDisplay.Visibility = Visibility.Visible;
      ResultsDisplay.IsExpanded = True

      _drawSurface.IsEnabled = False
    End Sub

    Private Sub QueryTask_Failed(ByVal sender As Object, ByVal args As TaskFailedEventArgs)
      MessageBox.Show("Query failed: " & args.Error.ToString())
    End Sub

    Private Sub QueryDetailsDataGrid_SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
      For Each g As Graphic In e.AddedItems
        g.Select()
      Next g

      For Each g As Graphic In e.RemovedItems
        g.UnSelect()
      Next g
    End Sub

    Private Sub QueryDetailsDataGrid_LoadingRow(ByVal sender As Object, ByVal e As DataGridRowEventArgs)
      AddHandler e.Row.MouseEnter, AddressOf Row_MouseEnter
      AddHandler e.Row.MouseLeave, AddressOf Row_MouseLeave
    End Sub

    Private Sub Row_MouseEnter(ByVal sender As Object, ByVal e As MouseEventArgs)
      TryCast((CType(sender, System.Windows.FrameworkElement)).DataContext, Graphic).Select()
    End Sub

    Private Sub Row_MouseLeave(ByVal sender As Object, ByVal e As MouseEventArgs)
      Dim row As DataGridRow = TryCast(sender, DataGridRow)
      Dim g As Graphic = TryCast((CType(sender, System.Windows.FrameworkElement)).DataContext, Graphic)

      If Not QueryDetailsDataGrid.SelectedItems.Contains(g) Then
        g.UnSelect()
      End If
    End Sub

    Private Sub GraphicsLayer_MouseEnter(ByVal sender As Object, ByVal args As GraphicMouseEventArgs)
      QueryDetailsDataGrid.Focus()
      QueryDetailsDataGrid.SelectedItem = args.Graphic
      QueryDetailsDataGrid.CurrentColumn = QueryDetailsDataGrid.Columns(0)
      QueryDetailsDataGrid.ScrollIntoView(QueryDetailsDataGrid.SelectedItem, QueryDetailsDataGrid.Columns(0))
    End Sub

    Private Sub GraphicsLayer_MouseLeave(ByVal sender As Object, ByVal args As GraphicMouseEventArgs)
      QueryDetailsDataGrid.Focus()
      QueryDetailsDataGrid.SelectedItem = Nothing
    End Sub

#End Region

#Region "HeaderGrid Button events"

    Private Sub PanHeaderGrid_MouseLeftButtonUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
      If PanArrowsGrid.ActualHeight > 0 Then
        HidePanArrows.Begin()
      Else
        ShowPanArrows.Begin()
      End If
    End Sub

    Private Sub MapScaleHeaderGrid_MouseLeftButtonUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
      If MapScaleGrid.ActualHeight > 0 Then
        HideMapScale.Begin()
      Else
        ShowMapScale.Begin()
      End If

    End Sub

    Private Sub MapZoomHeaderGrid_MouseLeftButtonUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
      If MapZoomGrid.ActualHeight > 0 Then
        HideMapZoom.Begin()
      Else
        ShowMapZoom.Begin()
      End If
    End Sub

    Private Sub WorldGlobe_MouseLeftButtonDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
      If Map IsNot Nothing Then
        Map.ZoomTo(Map.Layers.GetFullExtent())
      End If
    End Sub

    Private Sub OverviewHeaderGrid_MouseLeftButtonUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
      If OverviewGrid.ActualHeight > 0 Then
        HideOverview.Begin()
      Else
        ShowOverview.Begin()
      End If
    End Sub

    Private Sub HeaderTitleHeaderGrid_MouseLeftButtonUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
      If HeaderTitleGrid.ActualHeight > 0 Then
        HideHeaderTitle.Begin()
      Else
        ShowHeaderTitle.Begin()
      End If
    End Sub

    Private Sub ViewOptionsHeaderGrid_MouseLeftButtonUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
      If ViewOptionsGrid.ActualHeight > 0 Then
        HideViewOptions.Begin()
      Else
        ShowViewOptions.Begin()
      End If

    End Sub

    Private Sub SpatialQueryHeaderGrid_MouseLeftButtonUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
      If SpatialQueryGrid.ActualHeight > 0 Then
        HideSpatialQuery.Begin()
      Else
        ShowSpatialQuery.Begin()
      End If
    End Sub

#End Region

  End Class
End Namespace


text:
package com.sefford.beauthentic.activities;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.sefford.beauthentic.R;
import com.sefford.beauthentic.auth.AuthenticAuthenticator;
import com.sefford.beauthentic.callbacks.TextWatcherAdapter;
import com.sefford.beauthentic.callbacks.ValueEventListenerAdapter;
import com.sefford.beauthentic.providers.MessageProvider;
import com.sefford.beauthentic.services.LoginGCMNotificationService;
import com.sefford.beauthentic.services.NotifySyncService;
import com.sefford.beauthentic.utils.Constants;
import com.sefford.beauthentic.utils.GoogleApiAdapter;
import com.sefford.beauthentic.utils.Hasher;
import com.sefford.beauthentic.utils.Sessions;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Seconday activity of the app, most of the show happens here.
 *
 * @author Saúl Díaz González <sefford@gmail.com>
 */
public class LoggedActivity extends AppCompatActivity implements Handler.Callback {

    public static final String ACTION_REFRESH = "com.sefford.beauthentic.REFRESH";
    public static final String EXTRA_MESSAGE = "extra_message";

    static final int MSG_SYNC = 0x100;

    @Bind(R.id.tv_status)
    TextView tvStatus;
    @Bind(R.id.et_syncable)
    EditText etSyncable;

    Handler handler;

    AccountManager am;
    GoogleApiAdapter googleApi = GoogleApiAdapter.getInstance();
    TextWatcherAdapter watcher = new TextWatcherAdapter() {
        @Override
        public void afterTextChanged(Editable s) {
            if (handler != null) {
                handler.removeMessages(MSG_SYNC);
                handler.sendEmptyMessageDelayed(MSG_SYNC, 600);
            }
        }
    };

    BroadcastReceiver updateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (etSyncable != null) {
                etSyncable.removeTextChangedListener(watcher);
                etSyncable.setText(intent.getStringExtra(EXTRA_MESSAGE));
                etSyncable.addTextChangedListener(watcher);
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen_logged);
        am = AccountManager.get(getApplicationContext());
        ButterKnife.bind(this);
        googleApi.connect(googleApi);
        handler = new Handler(this);
        etSyncable.addTextChangedListener(watcher);
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_REFRESH);
        registerReceiver(updateReceiver, intentFilter);
        ContentResolver.requestSync(Sessions.getAccount(am), MessageProvider.AUTHORITY, Bundle.EMPTY);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!Sessions.isLogged(am)) {
            onLoggingOut();
        } else {
            getSupportActionBar().setTitle(Sessions.getAccount(am).name);
        }
    }

    private void logout() {
        finish();
        final Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(updateReceiver);
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.bt_invalidate)
    public void onAuthTokenInvalidated() {
        if (!TextUtils.isEmpty(am.peekAuthToken(Sessions.getAccount(am), AuthenticAuthenticator.AUTHTOKEN_TYPE))) {
            am.invalidateAuthToken(AuthenticAuthenticator.ACCOUNT_TYPE, am.peekAuthToken(Sessions.getAccount(am), AuthenticAuthenticator.AUTHTOKEN_TYPE));
            tvStatus.setText(R.string.status_invalidated);
        }
    }

    @OnClick(R.id.bt_delete_pass)
    public void onDeletePassword() {
        am.clearPassword(Sessions.getAccount(am));
        tvStatus.setText(R.string.status_forgot);
    }

    @OnClick(R.id.bt_refresh)
    public void onGettingAuthToken() {
        if (Sessions.isLogged(am)) {
            final Bundle data = new Bundle();
            data.putInt(AuthenticAuthenticator.EXTRA_TYPE, Integer.valueOf(am.getUserData(Sessions.getAccount(am), AuthenticAuthenticator.EXTRA_TYPE)));
            am.getAuthToken(Sessions.getAccount(am), AuthenticAuthenticator.AUTHTOKEN_TYPE, data, true, new AccountManagerCallback<Bundle>() {
                @Override
                public void run(AccountManagerFuture<Bundle> future) {
                    try {
                        final Bundle result = future.getResult();
                        if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)) {
                            tvStatus.setText(R.string.status_logged);
                        } else {
                            // We would be returning a intent here to open Login Activity, so we do not care, actually
                            onLoggingOut();
                        }
                    } catch (OperationCanceledException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (AuthenticatorException e) {
                        e.printStackTrace();
                    }
                }
            }, null);
        } else {
            onLoggingOut();
        }
    }

    @OnClick(R.id.bt_logout)
    public void onLoggingOut() {
        am.removeAccount(Sessions.getAccount(am), new AccountManagerCallback<Boolean>() {
            @Override
            public void run(AccountManagerFuture<Boolean> future) {
                logout();
            }
        }, null);
    }

    @Override
    public boolean handleMessage(Message msg) {
        final Account primaryAccount = Sessions.getPrimaryPhoneAccount(AccountManager.get(getApplicationContext()));
        if (primaryAccount != null) {
            final Firebase firebase = new Firebase(Constants.FIREBASE_USER_URL + Hasher.hash(primaryAccount.name));
            final Firebase message = firebase.child("message");
            message.setValue(etSyncable.getText().toString());
            orderSync();
        }
        return false;
    }

    void orderSync() {
        final Account primaryAccount = Sessions.getPrimaryPhoneAccount(AccountManager.get(getApplicationContext()));
        if (primaryAccount == null) {
            return;
        }
        final Firebase firebase = new Firebase(Constants.FIREBASE_USER_URL + Hasher.hash(primaryAccount.name));
        final Firebase devices = firebase.child("devices");
        if (primaryAccount != null) {
            devices.addListenerForSingleValueEvent(new ValueEventListenerAdapter() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    if (snapshot.exists()) {
                        Intent intent = new Intent(LoggedActivity.this, NotifySyncService.class);
                        intent.putStringArrayListExtra(LoginGCMNotificationService.EXTRA_DEVICES, (ArrayList<String>) snapshot.getValue());
                        startService(intent);
                    }
                }
            });
        }
    }
}


text:
#ifndef __SECURITY_TLSCALLBACKS_H__
#define __SECURITY_TLSCALLBACKS_H__ 1

#include <tls_handshake.h>

extern tls_handshake_callbacks_t tls_handshake_callbacks;

#endif