text:
"""Tools for connecting to a MongoDB replica set.

.. warning::
   **DEPRECATED:** Please use :mod:`~pymongo.mongo_replica_set_client` instead.

.. seealso:: :doc:`/examples/high_availability` for more examples of
   how to connect to a replica set.

To get a :class:`~pymongo.database.Database` instance from a
:class:`ReplicaSetConnection` use either dictionary-style or
attribute-style access:

.. doctest::

  >>> from pymongo import ReplicaSetConnection
  >>> c = ReplicaSetConnection('localhost:27017', replicaSet='repl0')
  >>> c.test_database
  Database(ReplicaSetConnection([u'...', u'...']), u'test_database')
  >>> c['test_database']
  Database(ReplicaSetConnection([u'...', u'...']), u'test_database')
"""
from pymongo.mongo_replica_set_client import MongoReplicaSetClient
from pymongo.errors import ConfigurationError

class ReplicaSetConnection(MongoReplicaSetClient):
    """Connection to a MongoDB replica set.
    """

    def __init__(self, hosts_or_uri=None, max_pool_size=10,
                 document_class=dict, tz_aware=False, **kwargs):
        """Create a new connection to a MongoDB replica set.

        .. warning::
           **DEPRECATED:** :class:`ReplicaSetConnection` is deprecated. Please
           use :class:`~pymongo.mongo_replica_set_client.MongoReplicaSetClient`
           instead

        The resultant connection object has connection-pooling built
        in. It also performs auto-reconnection when necessary. If an
        operation fails because of a connection error,
        :class:`~pymongo.errors.ConnectionFailure` is raised. If
        auto-reconnection will be performed,
        :class:`~pymongo.errors.AutoReconnect` will be
        raised. Application code should handle this exception
        (recognizing that the operation failed) and then continue to
        execute.

        Raises :class:`~pymongo.errors.ConnectionFailure` if
        the connection cannot be made.

        The `hosts_or_uri` parameter can be a full `mongodb URI
        <http://dochub.mongodb.org/core/connections>`_, in addition to
        a string of `host:port` pairs (e.g. 'host1:port1,host2:port2').
        If `hosts_or_uri` is None 'localhost:27017' will be used.

        .. note:: Instances of :class:`~ReplicaSetConnection` start a
           background task to monitor the state of the replica set. This allows
           it to quickly respond to changes in replica set configuration.
           Before discarding an instance of :class:`~ReplicaSetConnection` make
           sure you call :meth:`~close` to ensure that the monitor task is
           cleanly shut down.

        :Parameters:
          - `hosts_or_uri` (optional): A MongoDB URI or string of `host:port`
            pairs. If a host is an IPv6 literal it must be enclosed in '[' and
            ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for
            localhost)
          - `max_pool_size` (optional): The maximum size limit for
            each connection pool.
          - `document_class` (optional): default class to use for
            documents returned from queries on this connection
          - `tz_aware` (optional): if ``True``,
            :class:`~datetime.datetime` instances returned as values
            in a document by this :class:`ReplicaSetConnection` will be timezone
            aware (otherwise they will be naive)
          - `replicaSet`: (required) The name of the replica set to connect to.
            The driver will verify that each host it connects to is a member of
            this replica set. Can be passed as a keyword argument or as a
            MongoDB URI option.

          | **Other optional parameters can be passed as keyword arguments:**

          - `host`: For compatibility with connection.Connection. If both
            `host` and `hosts_or_uri` are specified `host` takes precedence.
          - `port`: For compatibility with connection.Connection. The default
            port number to use for hosts.
          - `network_timeout`: For compatibility with connection.Connection.
            The timeout (in seconds) to use for socket operations - default
            is no timeout. If both `network_timeout` and `socketTimeoutMS` are
            specified `network_timeout` takes precedence, matching
            connection.Connection.
          - `socketTimeoutMS`: (integer) How long (in milliseconds) a send or
            receive on a socket can take before timing out.
          - `connectTimeoutMS`: (integer) How long (in milliseconds) a
            connection can take to be opened before timing out.
          - `auto_start_request`: If ``True`` (the default), each thread that
            accesses this :class:`ReplicaSetConnection` has a socket allocated
            to it for the thread's lifetime, for each member of the set. For
            :class:`~pymongo.read_preferences.ReadPreference` PRIMARY,
            auto_start_request=True ensures consistent reads, even if you read
            after an unsafe write. For read preferences other than PRIMARY,
            there are no consistency guarantees.
          - `use_greenlets`: if ``True``, use a background Greenlet instead of
            a background thread to monitor state of replica set. Additionally,
            :meth:`start_request()` will ensure that the current greenlet uses
            the same socket for all operations until :meth:`end_request()`.
            `use_greenlets` with ReplicaSetConnection requires `Gevent
            <http://gevent.org/>`_ to be installed.

          | **Write Concern options:**

          - `safe`: :class:`ReplicaSetConnection` **disables** acknowledgement
            of write operations. Use ``safe=True`` to enable write
            acknowledgement.
          - `w`: (integer or string) Write operations will block until they have
            been replicated to the specified number or tagged set of servers.
            `w=<int>` always includes the replica set primary (e.g. w=3 means
            write to the primary and wait until replicated to **two**
            secondaries). Implies safe=True.
          - `wtimeout`: (integer) Used in conjunction with `w`. Specify a value
            in milliseconds to control how long to wait for write propagation
            to complete. If replication does not complete in the given
            timeframe, a timeout exception is raised. Implies safe=True.
          - `j`: If ``True`` block until write operations have been committed
            to the journal. Ignored if the server is running without journaling.
            Implies safe=True.
          - `fsync`: If ``True`` force the database to fsync all files before
            returning. When used with `j` the server awaits the next group
            commit before returning. Implies safe=True.

          | **Read preference options:**

          - `slave_okay` or `slaveOk` (deprecated): Use `read_preference`
            instead.
          - `read_preference`: The read preference for this connection.
            See :class:`~pymongo.read_preferences.ReadPreference` for available
          - `tag_sets`: Read from replica-set members with these tags.
            To specify a priority-order for tag sets, provide a list of
            tag sets: ``[{'dc': 'ny'}, {'dc': 'la'}, {}]``. A final, empty tag
            set, ``{}``, means "read from any member that matches the mode,
            ignoring tags." :class:`MongoReplicaSetClient` tries each set of
            tags in turn until it finds a set of tags with at least one matching
            member.
          - `secondary_acceptable_latency_ms`: (integer) Any replica-set member
            whose ping time is within secondary_acceptable_latency_ms of the
            nearest member may accept reads. Default 15 milliseconds.
            **Ignored by mongos** and must be configured on the command line.
            See the localThreshold_ option for more information.

          | **SSL configuration:**

          - `ssl`: If ``True``, create the connection to the servers using SSL.
          - `ssl_keyfile`: The private keyfile used to identify the local
            connection against mongod.  If included with the ``certfile` then
            only the ``ssl_certfile`` is needed.  Implies ``ssl=True``.
          - `ssl_certfile`: The certificate file used to identify the local
            connection against mongod. Implies ``ssl=True``.
          - `ssl_cert_reqs`: Specifies whether a certificate is required from
            the other side of the connection, and whether it will be validated
            if provided. It must be one of the three values ``ssl.CERT_NONE``
            (certificates ignored), ``ssl.CERT_OPTIONAL``
            (not required, but validated if provided), or ``ssl.CERT_REQUIRED``
            (required and validated). If the value of this parameter is not
            ``ssl.CERT_NONE``, then the ``ssl_ca_certs`` parameter must point
            to a file of CA certificates. Implies ``ssl=True``.
          - `ssl_ca_certs`: The ca_certs file contains a set of concatenated
            "certification authority" certificates, which are used to validate
            certificates passed from the other end of the connection.
            Implies ``ssl=True``.

        .. versionchanged:: 2.5
           Added additional ssl options
        .. versionchanged:: 2.3
           Added `tag_sets` and `secondary_acceptable_latency_ms` options.
        .. versionchanged:: 2.2
           Added `auto_start_request` and `use_greenlets` options.
           Added support for `host`, `port`, and `network_timeout` keyword
           arguments for compatibility with connection.Connection.
        .. versionadded:: 2.1

        .. _localThreshold: http://docs.mongodb.org/manual/reference/mongos/#cmdoption-mongos--localThreshold
        """
        network_timeout = kwargs.pop('network_timeout', None)
        if network_timeout is not None:
            if (not isinstance(network_timeout, (int, float)) or
                network_timeout <= 0):
                raise ConfigurationError("network_timeout must "
                                         "be a positive integer")
            kwargs['socketTimeoutMS'] = network_timeout * 1000

        kwargs['auto_start_request'] = kwargs.get('auto_start_request', True)
        kwargs['safe'] = kwargs.get('safe', False)

        super(ReplicaSetConnection, self).__init__(
            hosts_or_uri, max_pool_size, document_class, tz_aware, **kwargs)

    def __repr__(self):
        return "ReplicaSetConnection(%r)" % (["%s:%d" % n
                                              for n in self.hosts],)


text:
package com.amazonaws.services.simplesystemsmanagement.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeInstanceAssociationsStatusRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The managed node IDs for which you want association status information.
     *

     */
    private String instanceId;
    /**
     *

     * The maximum number of items to return for this call. The call also returns a token that you can specify in a
     * subsequent call to get the next set of results.
     *

     */
    private Integer maxResults;
    /**
     *

     * The token for the next set of items to return. (You received this token from a previous call.)
     *

     */
    private String nextToken;

    /**
     *

     * The managed node IDs for which you want association status information.
     *

     *
     * @param instanceId
     *        The managed node IDs for which you want association status information.
     */

    public void setInstanceId(String instanceId) {
        this.instanceId = instanceId;
    }

    /**
     *

     * The managed node IDs for which you want association status information.
     *

     *
     * @return The managed node IDs for which you want association status information.
     */

    public String getInstanceId() {
        return this.instanceId;
    }

    /**
     *

     * The managed node IDs for which you want association status information.
     *

     *
     * @param instanceId
     *        The managed node IDs for which you want association status information.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeInstanceAssociationsStatusRequest withInstanceId(String instanceId) {
        setInstanceId(instanceId);
        return this;
    }

    /**
     *

     * The maximum number of items to return for this call. The call also returns a token that you can specify in a
     * subsequent call to get the next set of results.
     *

     *
     * @param maxResults
     *        The maximum number of items to return for this call. The call also returns a token that you can specify in
     *        a subsequent call to get the next set of results.
     */

    public void setMaxResults(Integer maxResults) {
        this.maxResults = maxResults;
    }

    /**
     *

     * The maximum number of items to return for this call. The call also returns a token that you can specify in a
     * subsequent call to get the next set of results.
     *

     *
     * @return The maximum number of items to return for this call. The call also returns a token that you can specify
     *         in a subsequent call to get the next set of results.
     */

    public Integer getMaxResults() {
        return this.maxResults;
    }

    /**
     *

     * The maximum number of items to return for this call. The call also returns a token that you can specify in a
     * subsequent call to get the next set of results.
     *

     *
     * @param maxResults
     *        The maximum number of items to return for this call. The call also returns a token that you can specify in
     *        a subsequent call to get the next set of results.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeInstanceAssociationsStatusRequest withMaxResults(Integer maxResults) {
        setMaxResults(maxResults);
        return this;
    }

    /**
     *

     * The token for the next set of items to return. (You received this token from a previous call.)
     *

     *
     * @param nextToken
     *        The token for the next set of items to return. (You received this token from a previous call.)
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * The token for the next set of items to return. (You received this token from a previous call.)
     *

     *
     * @return The token for the next set of items to return. (You received this token from a previous call.)
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * The token for the next set of items to return. (You received this token from a previous call.)
     *

     *
     * @param nextToken
     *        The token for the next set of items to return. (You received this token from a previous call.)
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeInstanceAssociationsStatusRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getInstanceId() != null)
            sb.append("InstanceId: ").append(getInstanceId()).append(",");
        if (getMaxResults() != null)
            sb.append("MaxResults: ").append(getMaxResults()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeInstanceAssociationsStatusRequest == false)
            return false;
        DescribeInstanceAssociationsStatusRequest other = (DescribeInstanceAssociationsStatusRequest) obj;
        if (other.getInstanceId() == null ^ this.getInstanceId() == null)
            return false;
        if (other.getInstanceId() != null && other.getInstanceId().equals(this.getInstanceId()) == false)
            return false;
        if (other.getMaxResults() == null ^ this.getMaxResults() == null)
            return false;
        if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getInstanceId() == null) ? 0 : getInstanceId().hashCode());
        hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public DescribeInstanceAssociationsStatusRequest clone() {
        return (DescribeInstanceAssociationsStatusRequest) super.clone();
    }

}

redpajama_set_name: RedPajamaGithub


text:
/*!
 * @file SBFirstVCCustomSegueViewController
 *
 * @author SMRT
 *
 * @section Description
 * Launch View Controller
 *
 * @section Version 1.0
 *
 */
/*************************************************************************************/
#pragma mark - Imported Class
/*************************************************************************************/
#import "SBFirstVCCustomSegueViewController.h"
#import "SBCustomSegue.h"

/*************************************************************************************/
#pragma mark - Interface
/*************************************************************************************/
@interface SBFirstVCCustomSegueViewController ()

@end

/*************************************************************************************/
#pragma mark - Implementation
/*************************************************************************************/
@implementation SBFirstVCCustomSegueViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*************************************************************************************/
#pragma mark - Storyboard
/*************************************************************************************/
/* Only if we implement this method will we be able to get the option in "Storyboard" to connect. */
- (IBAction)unwindToFirst:(UIStoryboardSegue *)unwindSegue
{
}

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue isKindOfClass:[SBCustomSegue class]]) {
        // Set the start point for the animation to center of the button for the animation
        ((SBCustomSegue *)segue).originatingPoint = ((UIButton *)sender).center;
    }
}

// We need to over-ride this method from UIViewController to provide a custom segue for unwinding
- (UIStoryboardSegue *)segueForUnwindingToViewController:(UIViewController *)toViewController fromViewController:(UIViewController *)fromViewController identifier:(NSString *)identifier {
    // Instantiate a new CustomUnwindSegue
    //SBCustomUnwindingSegue *segue = [[SBCustomUnwindingSegue alloc] initWithIdentifier:identifier source:fromViewController destination:toViewController];
    // Set the target point for the animation to the center of the button in this VC
    //segue.targetPoint = self.view.center;
    //return segue;

    return nil;
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/tipbutton2" android:state_pressed="false"/>
    <item android:drawable="@drawable/tipbutton1" android:state_pressed="true"/>

</selector>


text:
#include "Endpoint.h"

using namespace de::njsm::netsi;

/**
 * @brief Construct a new Endpoint with given values
 *
 * @param a_name The name to set
 * @param a_port The port to set
 */
de::njsm::netsi::Endpoint::Endpoint(Device_Type a_name, std::uint16_t a_port) noexcept :
    m_name(std::move(a_name)),
    m_port(a_port)
{

}

/**
 * @brief Tests for equality
 *
 * @param a_other The point to compare to
 * @return True iff all members are equal
 */
bool
de::njsm::netsi::Endpoint::operator==(const Endpoint& a_other) const noexcept {
    return m_name == a_other.m_name &&
           m_port == a_other.m_port;
}

/**
 * @brief Compare two points
 *
 * The points are compared in lexicographical order by the following
 * priority:
 * - name
 * - port
 *
 * @param a_other The point to compare to
 * @return True iff this is smaller than a_other
 */
bool
de::njsm::netsi::Endpoint::operator<(const Endpoint& a_other) const noexcept {
    bool l_return_value;
    bool l_name_equal;

    l_return_value = (m_name < a_other.m_name) ||
                     ((l_name_equal = m_name == a_other.m_name) && m_port < a_other.m_port);

    return l_return_value;
}


text:
{-# LANGUAGE FlexibleInstances, DeriveGeneric, DeriveAnyClass #-}

{- ===========================================================================
Contains basic types - you'll have to extend several of the definitions below
=========================================================================== -}

module FP_TypesEtc where

import GHC.Generics
import FPPrac.Trees

-- ===================================================================
-- Example Alphabet
-- - Extend, adapt, change the non-terminals to your own needs
-- - Do NOT change the first two groups of constructors (Symbol ... Rep1)

data Alphabet = Terminal String               -- Terminal symbol: WILL be included in parseTree
              | Symbol   String               -- Terminal symbol: will NOT be included in parseTree
              | SyntCat  Alphabet             -- Checks whether a string belongs to a syntactic category

              | Alt   [Alphabet] [Alphabet]   -- Try both
              | Opt   [Alphabet]              -- Optional
              | Rep0  [Alphabet]              -- Zero or more repetitions
              | Rep1  [Alphabet]              -- One or more repetitions

              | Expr                          -- Expression
              | Nmbr                          -- Number
              | Var                           -- Variable (self-defined)
              | Op                            -- Operation symbol
              | Space                         -- Spaces
              | Bracket                       -- Brackets
              | Brace                         -- Braces
              | Rsvd                          -- Reserved word (self-defined)

              | Program                       -- Program (self-defined)
              | Stat                          -- Statements (self-defined)
              | Block                         -- Block statement (self-defined)
              | Asm                           -- Assignment (self-defined)
              | Rep                           -- Repeat (self-defined)
              | If                            -- If (self-defined)
              | Then                          -- Then (self-defined)
              | Else                          -- Else (self-defined)
              deriving (Eq,Ord,Show,Generic,ToRoseTree)

-- ===================================================================
-- Symbolic notation for EBNF constructors

ps <> qs = Alt  ps qs
(?:) ps  = Opt  ps
(*:) ps  = Rep0 ps
(+:) ps  = Rep1 ps

-- ===================================================================

type Grammar = Alphabet -> [[Alphabet]]

type Token   = (Alphabet,String,Int)  -- Alphabet: indicates the "syntactic category" to which
                                      --      the String belongs (to distinguish, a.o., between
                                      --      reserved words and identifiers in general),
                                      -- String: the token itself,
                                      -- Int: the position of the token in the input token-list
                                      --      (needed for error messages).

instance ToRoseTree Token where
  toRoseTree t = RoseNode (show t) []

data ParseTree  = PLeaf Token
                | PNode Alphabet [ParseTree]
                | PError ParseTree [Alphabet] Alphabet String Int
                deriving (Eq,Show,Generic,ToRoseTree)

instance Ord ParseTree where
  PError _ _ _ _ k <  PError _ _ _ _ k' = k <  k'
  _                <  _                 = error "ordering only in case of parse-errors"

  PError _ _ _ _ k <= PError _ _ _ _ k' = k <= k'
  _                <= _                 = error "ordering only in case of parse-errors"

type ParseState = ( Alphabet       -- Non-terminal indicating the present subexpression
                  , [ParseTree]    -- The already produced trees within the present subexpression
                  , [Token]        -- The remaining list of input tokens
                  )

-- ===================================================================
x ∈ xs = x `elem` xs

-- ===================================================================
-- Pretty Printing

toStrings tree = case tree of
     PLeaf t                 -> ["PLeaf " ++ show t]

     PNode nt ts             -> ("PNode " ++ show nt) : (addSpace 7 $ concat $ addEndBrack $ addListNotation $ map toStrings ts)
                             where
                               addSpace n = map ((replicate n ' ') ++)

                               addListNotation ((str:strs):strss) =   (("["++str):strs)
                                                                    : [  (","++str'):strs' | (str':strs') <- strss ]

                               addEndBrack [strs]       = [ strs ++ ["]"] ]
                               addEndBrack (strs:strss) = strs : addEndBrack strss

     PError tr rule nt str k -> [ "==========="
                                , "Parse Error"
                                , "==========="
                                , "Recognized:"
                                , "-----------"
                                ]
                                ++ toStrings tr ++
                                [ "-----------"
                                , "Still to go:   " ++ show rule
                                , "Expected:      " ++ show nt
                                , "Found:         " ++ str
                                , "At position:   " ++ show k
                                , "==========="
                                ]

prpr t  = putStr $ ('\n':) $ (++"\n") $ unlines $ toStrings t

--------------- Own stuff ----------------------

resWord :: [Token] -> [Token]
resWord = map resWord'
    where
        resWord' (Var,b,c)  | elem b res = (Rsvd,b,c)
                            | otherwise  = (Var,b,c)
            where
                res = ["while","if","then","repeat","else"]
        resWord' x          = x

data AST = ASTRoot [AST]
         | ASTStat String AST [AST] [AST]
         | ASTExpr String [AST]
         | ASTBlock [AST]
         | ASTLeaf
            deriving Show

ptreeToAst :: ParseTree -> AST
ptreeToAst (PNode Program l)
    = ASTRoot (map ptreeToAst l)
ptreeToAst (PNode Stat (st@(PLeaf (Rep,_,_)):e:bl:_))
    = ASTStat "repeat" (ptreeToAst e) [(ptreeToAst bl)] []
ptreeToAst (PNode Stat (st@(PLeaf (If,_,_)):e:(PLeaf (Then,_,_)):th:(PLeaf (Else,_,_)):el:_))
    = ASTStat "if" (ptreeToAst e) [(ptreeToAst th)] [(ptreeToAst el)]
ptreeToAst (PNode Stat (st@(PLeaf (If,_,_)):e:(PLeaf (Then,_,_)):th:_))
    = ASTStat "if" (ptreeToAst e) [(ptreeToAst th)] []
ptreeToAst (PNode Block l)
    = ASTBlock (map ptreeToAst l)
ptreeToAst (PNode Stat ((PNode Var [PLeaf (_,v,_)]):(PLeaf (Asm,_,_)):e:_) )
    = ASTStat (v ++ " := ") (ptreeToAst e) [] []
ptreeToAst (PNode Expr ((PLeaf (Bracket,_,_)):f:(PNode Op [PLeaf (_,o,_)]):s:_))
    = ASTExpr o [ptreeToAst f, ptreeToAst s]
ptreeToAst (PNode Expr [(PNode Nmbr [PLeaf (_,n,_)])])
    = ASTExpr n []
ptreeToAst (PNode Expr [(PNode Var [PLeaf (_,n,_)])])
    = ASTExpr n []
ptreeToAst e
    = ASTLeaf

{-
ptreeToAst (PNode Program l) = ASTRoot (map ptreeToAst $ tail $ init l)
ptreeToAst (PNode Stat ((PLeaf (Rep,_,_)):e:_:ss) )
    = ASTStat "repeat" (ptreeToAst e) (map ptreeToAst $ init ss) []
ptreeToAst (PNode Stat ((PLeaf (If,_,_)):e:(PLeaf (Then,_,_)):(PLeaf (Bracket,_,_)):th:(PLeaf (Bracket,_,_)):(PLeaf (Else,_,_)):(PLeaf (Bracket,_,_)):el:(PLeaf (Bracket,_,_)):_) )
    = ASTStat "if" (ptreeToAst e) (map ptreeToAst th) (map ptreeToAst el)
ptreeToAst (PNode Stat ((PLeaf (If,_,_)):e:(PLeaf (Then,_,_)):(PLeaf (Bracket,_,_)):th:(PLeaf (Bracket,_,_)):_))
    = ASTStat "if" (ptreeToAst e) (map ptreeToAst th) []
ptreeToAst (PNode Stat ((PNode Var [PLeaf (_,v,_)]):(PLeaf (Asm,_,_)):e) )
    = ASTStat (v ++ " := ") (ptreeToAst $ head e) [] []
ptreeToAst (PNode Expr ((PLeaf (Bracket,_,_)):f:(PNode Op [PLeaf (_,o,_)]):s:_))
    = ASTExpr o [ptreeToAst f, ptreeToAst s]
ptreeToAst (PNode Expr [(PNode Nmbr [PLeaf (_,n,_)])])
    = ASTExpr n []
ptreeToAst (PNode Expr [(PNode Var [PLeaf (_,n,_)])])
    = ASTExpr n []
ptreeToAst e
    = error $ show e
-}

astToRose :: AST -> RoseTree
astToRose (ASTRoot e) = RoseNode "program" (map astToRose e)
astToRose (ASTBlock e) = RoseNode "block" (map astToRose $ init $ tail e)
astToRose (ASTStat str expr stat1 stat2) = RoseNode str buildlist
    where
        buildlist   | length stat1 > 0 && (length stat2 > 0)    = [astToRose expr, RoseNode "" (map astToRose stat1), RoseNode "" (map astToRose stat2)]
                    | length stat1 > 0                          = [astToRose expr, RoseNode "" (map astToRose stat1)]
                    | length stat2 > 0                          = [astToRose expr, RoseNode "" (map astToRose stat2)]
                    | otherwise                                 = [astToRose expr]
astToRose (ASTExpr str []) = RoseNode str []
astToRose (ASTExpr str exprs) = RoseNode str (map astToRose exprs)
astToRose (ASTLeaf) = RoseNode "" []


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2018 The Android Open Source Project

     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.
-->
<resources>
  <string name="default_notification_channel_name">Зараз іграе</string>
  <string name="media3_controls_play_description">Прайграць</string>
  <string name="media3_controls_pause_description">Прыпыніць</string>
  <string name="media3_controls_seek_to_previous_description">Перайсці да папярэдняга элемента</string>
  <string name="media3_controls_seek_to_next_description">Перайсці да наступнага элемента</string>
  <string name="media3_controls_seek_back_description">Перайсці назад</string>
  <string name="media3_controls_seek_forward_description">Перайсці ўперад</string>
  <string name="authentication_required">Патрабуецца аўтэнтыфікацыя</string>
</resources>


text:
{% load staticfiles %}

Help someone's dream take flight

Join the Campaign

Read More


text:
from datetime import datetime

import requests
from mock import patch

from pygithub3.tests.utils.core import TestCase
from pygithub3.services.base import Service, MimeTypeMixin
from pygithub3.core.result import base
from pygithub3.tests.utils.base import DummyRequest, mock_response
from pygithub3.tests.utils.services import _, DummyService

@patch.object(requests.sessions.Session, 'request')
class TestServiceCalls(TestCase):

    def setUp(self):
        self.s = Service()
        self.r = DummyRequest()
        self.args = dict(arg1='arg1', arg2='arg2')

    def test_BOOL(self, request_method):
        self.s._bool(self.r, **self.args)
        request_method.assert_called_with('head', _('dummyrequest'),
                                          params=self.args)

    def test_PUT(self, request_method):
        self.s._put(self.r, **self.args)
        data = 'PLACEHOLDER'  # See _put
        request_method.assert_called_with('put', _('dummyrequest'),
                                          data=data, params=self.args)

    def test_DELETE(self, request_method):
        request_method.return_value = mock_response('delete')
        self.s._delete(self.r, **self.args)
        request_method.assert_called_with('delete', _('dummyrequest'),
                                          data=None, params=self.args)

    def test_POST(self, request_method):
        request_method.return_value = mock_response('post')
        self.s._post(self.r, **self.args)
        request_method.assert_called_with('post', _('dummyrequest'),
                                          data=None, params=self.args)

    def test_GET(self, request_method):
        request_method.return_value = mock_response()
        self.s._get(self.r, **self.args)
        request_method.assert_called_with('get', _('dummyrequest'),
                                          params=self.args)

    def test_GET_result(self, request_method):
        result = self.s._get_result(self.r, **self.args)
        self.assertFalse(request_method.called)
        self.assertIsInstance(result, base.Result)

@patch.object(requests.sessions.Session, 'request')
class TestMimeType(TestCase):

    def setUp(self):
        self.ms = DummyService()

    def test_WITHOUT_mimetype(self, request_method):
        request_method.return_value = mock_response()
        self.ms.dummy_request()
        request_method.assert_called_with('get', _('dummyrequest'), params={})

    def test_WITH_mimetype(self, request_method):
        request_method.return_value = mock_response()
        self.ms.set_html()
        self.ms.dummy_request()
        request_method.assert_called_with('get', _('dummyrequest'),
            headers={'Accept': 'application/vnd.github.%s.html+json' %
                                MimeTypeMixin.VERSION},
            params={})


text:
from datetime import datetime, timedelta
from logging import getLogger, Logger
from typing import Dict, Optional

import config

_logger = getLogger(__name__)

class StatsMonitor:
    # TODO: ensure class is thread safe
    def __init__(self):
        self.stats: Dict[str, DomainStats] = {}
        self.combined_stats: DomainStats = DomainStats(None)
        self._next_log_time = None

    def on_page_crawled(self, domain: str):
        self._get_stats_for(domain).on_page_crawled()
        self.combined_stats.on_page_crawled()

        self._maybe_log_stats()

    def _maybe_log_stats(self):
        """
        Log statistics if it's time to do so
        """
        log_interval = self._get_log_interval()
        if log_interval is None:
            # Logging is disabled
            return
        now = datetime.utcnow()
        if (self._next_log_time is None) or (now >= self._next_log_time):
            # Time to log now
            self._next_log_time = (now + log_interval)

            for k in sorted(self.stats.keys()):
                self.stats.get(k).log_stats(now, _logger)
            self.combined_stats.log_stats(now, _logger)

    def _get_stats_for(self, domain: str) -> 'DomainStats':
        if domain not in self.stats:
            self.stats[domain] = DomainStats(domain)
        return self.stats.get(domain)

    @staticmethod
    def _get_log_interval() -> Optional[timedelta]:
        """
        :return: How often statistics should be logged, or None if disabled
        """
        interval = config.STATS_INTERVAL
        return timedelta(seconds=interval) if (interval != -1) else None

class DomainStats:
    def __init__(self, domain: Optional[str]):
        """
        :param domain: The domain these stats are for, or None if it represents stats for all domains combined
        """
        label = ('Domain "%s"' % domain) if (domain is not None) else 'Combined:'
        self.fmt = label + ' crawled %d pages in %.2f seconds (avg. %.2f/sec)'
        self.pages_crawled: int = 0
        self.time_started: datetime = datetime.utcnow()

    def on_page_crawled(self):
        self.pages_crawled += 1

    def log_stats(self, now: datetime, logger: Logger):
        elapsed = (now - self.time_started).total_seconds()
        avg = self.pages_crawled / (elapsed if (elapsed != 0) else 1.0)

        logger.info(self.fmt % (self.pages_crawled, elapsed, avg))


text:
namespace Envoy {
namespace {

using BufferIntegrationTest = HttpProtocolIntegrationTest;

INSTANTIATE_TEST_SUITE_P(Protocols, BufferIntegrationTest,
                         testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParams()),
                         HttpProtocolIntegrationTest::protocolTestParamsToString);

TEST_P(BufferIntegrationTest, RouterNotFoundBodyBuffer) {
  config_helper_.prependFilter(ConfigHelper::defaultBufferFilter());
  testRouterNotFoundWithBody();
}

TEST_P(BufferIntegrationTest, RouterRequestAndResponseWithGiantBodyBuffer) {
  config_helper_.prependFilter(ConfigHelper::defaultBufferFilter());
  testRouterRequestAndResponseWithBody(4 * 1024 * 1024, 4 * 1024 * 1024, false);
}

TEST_P(BufferIntegrationTest, RouterHeaderOnlyRequestAndResponseBuffer) {
  config_helper_.prependFilter(ConfigHelper::defaultBufferFilter());
  testRouterHeaderOnlyRequestAndResponse();
}

TEST_P(BufferIntegrationTest, RouterRequestAndResponseWithBodyBuffer) {
  config_helper_.prependFilter(ConfigHelper::defaultBufferFilter());
  testRouterRequestAndResponseWithBody(1024, 512, false);
}

TEST_P(BufferIntegrationTest, RouterRequestAndResponseWithZeroByteBodyBuffer) {
  config_helper_.prependFilter(ConfigHelper::defaultBufferFilter());
  testRouterRequestAndResponseWithBody(0, 0, false);
}

TEST_P(BufferIntegrationTest, RouterRequestPopulateContentLength) {
  config_helper_.prependFilter(ConfigHelper::defaultBufferFilter());
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));
  auto encoder_decoder = codec_client_->startRequest(Http::TestRequestHeaderMapImpl{
      {":method", "POST"}, {":scheme", "http"}, {":path", "/shelf"}, {":authority", "host"}});
  request_encoder_ = &encoder_decoder.first;
  IntegrationStreamDecoderPtr response = std::move(encoder_decoder.second);
  codec_client_->sendData(*request_encoder_, "123", false);
  codec_client_->sendData(*request_encoder_, "456", false);
  codec_client_->sendData(*request_encoder_, "789", true);

  ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
  ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));
  upstream_request_->encodeHeaders(default_response_headers_, true);
  ASSERT_TRUE(upstream_request_->waitForEndStream(*dispatcher_));

  auto* content_length = upstream_request_->headers().ContentLength();
  ASSERT_NE(content_length, nullptr);
  EXPECT_EQ(content_length->value().getStringView(), "9");

  ASSERT_TRUE(response->waitForEndStream());
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("200", response->headers().getStatusValue());
}

TEST_P(BufferIntegrationTest, RouterRequestPopulateContentLengthOnTrailers) {
  config_helper_.prependFilter(ConfigHelper::defaultBufferFilter());
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));
  auto encoder_decoder = codec_client_->startRequest(Http::TestRequestHeaderMapImpl{
      {":method", "POST"}, {":scheme", "http"}, {":path", "/shelf"}, {":authority", "host"}});
  request_encoder_ = &encoder_decoder.first;
  IntegrationStreamDecoderPtr response = std::move(encoder_decoder.second);
  codec_client_->sendData(*request_encoder_, "0123", false);
  codec_client_->sendData(*request_encoder_, "456", false);
  codec_client_->sendData(*request_encoder_, "789", false);
  Http::TestRequestTrailerMapImpl request_trailers{{"request", "trailer"}};
  codec_client_->sendTrailers(*request_encoder_, request_trailers);

  ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
  ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));
  upstream_request_->encodeHeaders(default_response_headers_, true);
  ASSERT_TRUE(upstream_request_->waitForEndStream(*dispatcher_));

  auto* content_length = upstream_request_->headers().ContentLength();
  ASSERT_NE(content_length, nullptr);
  EXPECT_EQ(content_length->value().getStringView(), "10");

  ASSERT_TRUE(response->waitForEndStream());
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("200", response->headers().getStatusValue());
}

TEST_P(BufferIntegrationTest, RouterRequestBufferLimitExceeded) {
  // Make sure the connection isn't closed during request upload.
  // Without a large drain-close it's possible that the local reply will be sent
  // during request upload, and continued upload will result in TCP reset before
  // the response is read.
  config_helper_.addConfigModifier(
      [](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
             hcm) { hcm.mutable_delayed_close_timeout()->set_seconds(2000 * 1000); });
  config_helper_.prependFilter(ConfigHelper::smallBufferFilter());
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{{":method", "POST"},
                                     {":path", "/dynamo/url"},
                                     {":scheme", "http"},
                                     {":authority", "host"},
                                     {"x-forwarded-for", "10.0.0.1"},
                                     {"x-envoy-retry-on", "5xx"}},
      1024 * 65);

  ASSERT_TRUE(response->waitForEndStream());
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("413", response->headers().getStatusValue());
}

ConfigHelper::HttpModifierFunction overrideConfig(const std::string& json_config) {
  envoy::extensions::filters::http::buffer::v3::BufferPerRoute buffer_per_route;
  TestUtility::loadFromJson(json_config, buffer_per_route);

  return
      [buffer_per_route](
          envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
              cfg) {
        auto* config = cfg.mutable_route_config()
                           ->mutable_virtual_hosts()
                           ->Mutable(0)
                           ->mutable_typed_per_filter_config();

        (*config)["envoy.filters.http.buffer"].PackFrom(buffer_per_route);
      };
}

TEST_P(BufferIntegrationTest, RouteDisabled) {
  ConfigHelper::HttpModifierFunction mod = overrideConfig(R"EOF({"disabled": true})EOF");
  config_helper_.addConfigModifier(mod);
  config_helper_.prependFilter(ConfigHelper::smallBufferFilter());
  config_helper_.setBufferLimits(1024, 1024);

  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));
  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{{":method", "POST"},
                                     {":path", "/test/long/url"},
                                     {":scheme", "http"},
                                     {":authority", "host"},
                                     {"x-forwarded-for", "10.0.0.1"}},
      1024 * 65);

  waitForNextUpstreamRequest();
  upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true);

  ASSERT_TRUE(response->waitForEndStream());
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("200", response->headers().getStatusValue());
}

TEST_P(BufferIntegrationTest, RouteOverride) {
  ConfigHelper::HttpModifierFunction mod = overrideConfig(R"EOF({"buffer": {
    "max_request_bytes": 5242880
  }})EOF");
  config_helper_.addConfigModifier(mod);
  config_helper_.prependFilter(ConfigHelper::smallBufferFilter());

  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));
  auto response = codec_client_->makeRequestWithBody(
      Http::TestRequestHeaderMapImpl{{":method", "POST"},
                                     {":path", "/test/long/url"},
                                     {":scheme", "http"},
                                     {":authority", "host"},
                                     {"x-forwarded-for", "10.0.0.1"}},
      1024 * 65);

  waitForNextUpstreamRequest();
  upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true);

  ASSERT_TRUE(response->waitForEndStream());
  ASSERT_TRUE(response->complete());
  EXPECT_EQ("200", response->headers().getStatusValue());
}

} // namespace
} // namespace Envoy


text:
function createDirNode(dirName, path){
  return {name:dirName.trim(), path:formatPath(path), children:[]};
}
function createFileNode(nodeName, path){
  return {name:nodeName.trim(), path:formatPath(path)};
}

function isFileNode(nodeName){
  var parts = nodeName.split('.');
  return parts.length > 1;
}

function createNode(nodeName, path){
  if(isFileNode(nodeName)){
    return createFileNode(nodeName, path);
  }else{
    return createDirNode(nodeName, path);
  }
}

function formatPath(path){
  path = path.trim();

  if(path[0] !='/'){
    path = '/'.concat(path);
  }
  if(path[path.length-1]=='/'){
    path = path.substring(0,path.length-1);
  }
  return path;
}

function addNode(root, nodePath) {
  var nodePath = formatPath(nodePath);
  nodePath = nodePath.substring(1,nodePath.length); //drop front slash
  var parts = nodePath.split('/');
  var current = root;

  if(root.name != parts[0]){
    throw "root name is not the same: "+root.name +", "+parts[0];
    return
  }

    // loop through the parts and create a nested namespace if necessary
    for (var i = 1; i < parts.length; i++) {  //start from 1 (ignore the root)
        var partname = parts[i];
        //if last part check to see if it's directory of file
        if(i == parts.length-1){
          if(isFileNode(partname)){
            current.children.push({name:partname, path:formatPath(nodePath)});
            break;
          }
        }
        //need to check if we have that sub directory or file
        var index = containsChild(current, partname);
        if(index == -1){
          current.children.push({name:partname, path:formatPath(parts.slice(0,i+1).join('/')), children:[]});
          index = current.children.length-1;
        }
        // get a reference to the deepest element in the hierarchy so far
        current = current.children[index];
      }
}

function gotoNode(root, path){
  var path = formatPath(path);
  path = path.substring(1,path.length); //drop front slash
  var parts = path.split('/');
  var current = root;

  if (parts.length==1 && parts[0]==root.name){
    return root;
  }
  // loop through the parts & go as deep to the target
  for (var i = 1; i < parts.length; i++) {
    var partname = parts[i];

      //need to check if we have that sub directory or file
    var index = containsChild(current, partname);
    if(index == -1){
        return null;    //before final or at final if not found terminate early
      }
    if(i == parts.length-1 && index !=-1){        //only return node found if at last part
      return current.children[index];
    }
    // get a reference to the deepest element in the hierarchy so far
    current = current.children[index];
  }
}

function removeNode(root, path){
  var path = formatPath(path);
      path = path.substring(1,path.length); //drop front slash
  var parts = path.split('/');

  var targetNodeName = parts.pop();
  var parentPath = formatPath(parts.join('/'));
  var parentNode = gotoNode(root, parentPath);
  if (parentNode==null){  //no node for deletion found
    return;
  }
   var index = containsChild(parentNode, targetNodeName);

   if(index!=-1){
    parentNode.children.splice(index,1);
    // parentNode.children[index] = null;
  }
}

function containsChild(parentNode, nodeName){ //check if parentNode is a directory before use this
  if (!parentNode.children) {
    return -1;
  }
  for (i = 0; i < parentNode.children.length; i++) {
    if(parentNode.children[i].name==nodeName){
      return i;
    }
  }
    return -1;  //not found
}

function flatten(root) {
  var nodes = [], i = 0;
  // var path ='';
  function recurse(node,path) {

    if (node.children) {
      //generate node.path that has children
      node.path = path+'/'+node.name;
      // path = path+'/'+node.name;

      node.size = node.children.reduce(function(p, v) {
        return p + recurse(v,node.path);
      }, 0);
    }
    else{
      //generat node.path with no children
      node.path = path+'/'+node.name;
    }
    nodes.push(node);
    return node.size;
  }
  root.size = recurse(root,'');

  return nodes;
}


text:
.class public abstract Landroid/media/tv/ITvInputHardwareCallback$Stub;
.super Landroid/os/Binder;
.source "ITvInputHardwareCallback.java"

# interfaces
.implements Landroid/media/tv/ITvInputHardwareCallback;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/media/tv/ITvInputHardwareCallback;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x409
    name = "Stub"
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/media/tv/ITvInputHardwareCallback$Stub$Proxy;
    }
.end annotation

# static fields
.field private static final DESCRIPTOR:Ljava/lang/String; = "android.media.tv.ITvInputHardwareCallback"

.field static final TRANSACTION_onReleased:I = 0x1

.field static final TRANSACTION_onStreamConfigChanged:I = 0x2

# direct methods
.method public constructor <init>()V
    .locals 1

    .prologue
    .line 17
    invoke-direct {p0}, Landroid/os/Binder;-><init>()V

    .line 18
    const-string v0, "android.media.tv.ITvInputHardwareCallback"

    invoke-virtual {p0, p0, v0}, Landroid/media/tv/ITvInputHardwareCallback$Stub;->attachInterface(Landroid/os/IInterface;Ljava/lang/String;)V

    .line 19
    return-void
.end method

.method public static asInterface(Landroid/os/IBinder;)Landroid/media/tv/ITvInputHardwareCallback;
    .locals 2
    .param p0, "obj"    # Landroid/os/IBinder;

    .prologue
    .line 26
    if-nez p0, :cond_0

    .line 27
    const/4 v0, 0x0

    .line 33
    :goto_0
    return-object v0

    .line 29
    :cond_0
    const-string v1, "android.media.tv.ITvInputHardwareCallback"

    invoke-interface {p0, v1}, Landroid/os/IBinder;->queryLocalInterface(Ljava/lang/String;)Landroid/os/IInterface;

    move-result-object v0

    .line 30
    .local v0, "iin":Landroid/os/IInterface;
    if-eqz v0, :cond_1

    instance-of v1, v0, Landroid/media/tv/ITvInputHardwareCallback;

    if-eqz v1, :cond_1

    .line 31
    check-cast v0, Landroid/media/tv/ITvInputHardwareCallback;

    goto :goto_0

    .line 33
    :cond_1
    new-instance v0, Landroid/media/tv/ITvInputHardwareCallback$Stub$Proxy;

    .end local v0    # "iin":Landroid/os/IInterface;
    invoke-direct {v0, p0}, Landroid/media/tv/ITvInputHardwareCallback$Stub$Proxy;-><init>(Landroid/os/IBinder;)V

    goto :goto_0
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .locals 0

    .prologue
    .line 37
    return-object p0
.end method

.method public onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z
    .locals 3
    .param p1, "code"    # I
    .param p2, "data"    # Landroid/os/Parcel;
    .param p3, "reply"    # Landroid/os/Parcel;
    .param p4, "flags"    # I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    const/4 v1, 0x1

    .line 41
    sparse-switch p1, :sswitch_data_0

    .line 63
    invoke-super {p0, p1, p2, p3, p4}, Landroid/os/Binder;->onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    move-result v1

    :goto_0
    return v1

    .line 45
    :sswitch_0
    const-string v2, "android.media.tv.ITvInputHardwareCallback"

    invoke-virtual {p3, v2}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    goto :goto_0

    .line 50
    :sswitch_1
    const-string v2, "android.media.tv.ITvInputHardwareCallback"

    invoke-virtual {p2, v2}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    .line 51
    invoke-virtual {p0}, Landroid/media/tv/ITvInputHardwareCallback$Stub;->onReleased()V

    goto :goto_0

    .line 56
    :sswitch_2
    const-string v2, "android.media.tv.ITvInputHardwareCallback"

    invoke-virtual {p2, v2}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    .line 58
    sget-object v2, Landroid/media/tv/TvStreamConfig;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-virtual {p2, v2}, Landroid/os/Parcel;->createTypedArray(Landroid/os/Parcelable$Creator;)[Ljava/lang/Object;

    move-result-object v0

    check-cast v0, [Landroid/media/tv/TvStreamConfig;

    .line 59
    .local v0, "_arg0":[Landroid/media/tv/TvStreamConfig;
    invoke-virtual {p0, v0}, Landroid/media/tv/ITvInputHardwareCallback$Stub;->onStreamConfigChanged([Landroid/media/tv/TvStreamConfig;)V

    goto :goto_0

    .line 41
    nop

    :sswitch_data_0
    .sparse-switch
        0x1 -> :sswitch_1
        0x2 -> :sswitch_2
        0x5f4e5446 -> :sswitch_0
    .end sparse-switch
.end method


text:
package ro.pub.cs.systems.eim.exemplutestpractic;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ExempluTestPracticActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exemplu_test_practic);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        Button button0 = (Button)findViewById(R.id.press_button0);
        button0.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                EditText text0 = (EditText)findViewById(R.id.text0);
                int value = Integer.valueOf(text0.getText().toString());
                value++;
                text0.setText(String.valueOf(value));
            }
        });

        Button button1 = (Button)findViewById(R.id.press_button1);
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                EditText text1 = (EditText)findViewById(R.id.text1);
                int value = Integer.valueOf(text1.getText().toString());
                value++;
                text1.setText(String.valueOf(value));
            }
        });

        Button nextActivity = (Button)findViewById(R.id.nevigate_button);
        nextActivity.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent("ro.cs.pub.ro.android.intent.action.SUM");
                EditText text0 = (EditText)findViewById(R.id.text0);
                EditText text1 = (EditText)findViewById(R.id.text1);

                int sum = Integer.valueOf(text0.getText().toString()) + Integer.valueOf(text1.getText().toString());
                intent.putExtra("sum", sum);
                startActivityForResult(intent, 1);
            }
        });
    }

    protected void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        EditText text0 = (EditText)findViewById(R.id.text0);
        EditText text1 = (EditText)findViewById(R.id.text1);

        savedInstanceState.putString("text0", text0.getText().toString());
        savedInstanceState.putString("text1", text1.getText().toString());
    }

    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        EditText text0 = (EditText)findViewById(R.id.text0);
        EditText text1 = (EditText)findViewById(R.id.text1);

        text0.setText(savedInstanceState.getString("text0"));
        text1.setText(savedInstanceState.getString("text1"));
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch(requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Toast.makeText(getApplicationContext(), "Result OK", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Result Wrong", Toast.LENGTH_LONG).show();
                }
                break;

            // process other request codes
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_exemplu_test_practic, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------

using System.Diagnostics.CodeAnalysis;

namespace Microsoft.Azure.Mobile.Server.TestModels
{
    public class TestEntity : EntityData
    {
        [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "int", Justification = "Fine for this test class.")]
        public int IntValue { get; set; }

        public string StringValue { get; set; }

        public bool BooleanValue { get; set; }
    }

    [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "These classes are variants of each other.")]
    public class TestEntitySimple
    {
        public string Id { get; set; }

        [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "int", Justification = "Fine for this test class.")]
        public int IntValue { get; set; }

        public string StringValue { get; set; }

        public bool BooleanValue { get; set; }
    }
}