text:
{-# LANGUAGE OverloadedStrings #-}

module Main where

import Common
import Web.Twitter.Enumerator

import Network.HTTP.Enumerator
import Data.Enumerator hiding (map)
import qualified Data.Enumerator.List as EL
import qualified Data.ByteString.Lazy.Char8 as LB
import qualified Data.ByteString.Char8 as B
import Control.Monad.IO.Class
import Control.Applicative
import qualified Data.Text.Encoding as T
import Control.Monad
import System.IO
import System.Process (rawSystem)
import System.FilePath
import System.Directory
import System.Environment

main :: IO ()
main = withCF $ do
  (ln:_) <- liftIO getArgs
  curious <- fetchListAll ln
  let cid = map userId curious
  run_ $ userstream (EL.mapM (\x -> showTL x >> return x) =$ EL.filter (filterUsers cid) =$ iterNotify)
  where fetchListAll str = run_ $ listsMembers (ListNameParam str) $$ EL.consume
        filterUsers ulist (SStatus s) = (`elem` ulist) . userId . statusUser $ s
        filterUsers _ _ = False

iconPath :: IO FilePath
iconPath = (</> "icons") <$> confdir >>= ensureDirectoryExist

fetchIcon :: String -> String -> IO String
fetchIcon scName url = do
  ipath <- iconPath
  let fname = ipath </> scName ++ "__" ++ takeFileName url
  exists <- doesFileExist fname
  unless exists $ do
    h <- openBinaryFile fname WriteMode
    simpleHttp url >>= LB.hPut h
    hClose h
  return fname

notifySend :: String -> String -> Maybe FilePath -> IO ()
notifySend header content icon = do
  let ic = maybe [] (\i -> ["-i", i]) icon
  _ <- rawSystem "notify-send" $ [header, content] ++ ic
  return ()

iterNotify :: Iteratee StreamingAPI IO ()
iterNotify = do
  st <- EL.head
  case st of
    Just (SStatus s) -> do
      let user = statusUser s
          sn = userScreenName user
          cnt = B.unpack . T.encodeUtf8 $ statusText s
      icon <- case userProfileImageURL user of
        Nothing -> return Nothing
        Just url -> liftIO $ Just <$> fetchIcon sn url
      liftIO $ notifySend sn cnt icon
      iterNotify
    Just _ -> iterNotify
    Nothing -> return ()

showTL :: StreamingAPI -> IO ()
showTL (SStatus s) = do
  let user = statusUser s
      sn = B.pack $ userScreenName user
      cnt = T.encodeUtf8 $ statusText s
  B.putStrLn $ B.concat [sn, ": ", cnt]
showTL (SRetweetedStatus rs) =
  B.putStrLn $ B.concat ["Retweeted (by ", rtuser, "): ", user, ": ", T.encodeUtf8 text]
    where rtuser = B.pack . userScreenName . rsUser $ rs
          status = rsRetweetedStatus rs
          user = B.pack . userScreenName . statusUser $ status
          text = statusText status
showTL (SEvent ev) = do
  putStrLn $ "Event: " ++ evEvent ev
  putStr "> "
  showEventTarget $ evTarget ev
  putStr "> "
  showEventTarget $ evSource ev
  maybe (return ()) (\e -> putStr "> " >> showEventTarget e) $ evTargetObject ev
showTL _ = return ()

showEventTarget :: EventTarget -> IO ()
showEventTarget (ETUser u) =
  B.putStrLn $ B.concat ["@", screenName, " (followers:", fol, ", description:", des, ")"]
    where screenName = B.pack . userScreenName $ u
          des = maybe "" T.encodeUtf8 $ userDescription u
          fol = B.pack . maybe "" show $ userFollowers u
showEventTarget (ETStatus s) =
  B.putStrLn $ B.concat [user, ": ", T.encodeUtf8 text]
    where user = B.pack . userScreenName . statusUser $ s
          text = statusText s
showEventTarget (ETList l) =
  B.putStrLn $ B.concat ["List: ", fullname, ": ", memberCount]
    where fullname = B.pack . listFullName $ l
          memberCount = B.pack . show . listMemberCount $ l
showEventTarget o = putStrLn $ "unknown object: " ++ show o


text:
<?php

/**
 * Class BridgeTest
 */
final class BridgeTest extends PHPUnit\Framework\TestCase {
    /**
     * @return array
     */
    final public function vehicle_provider(): array {
        return array(
            array(new \DesignPatterns\Structural\Bridge\CarVehicle(
                new \DesignPatterns\Structural\Bridge\Workshop\Car\CarWorkshopProduce(),
                new \DesignPatterns\Structural\Bridge\Workshop\Car\CarWorkshopAssemble(),
                new \DesignPatterns\Structural\Bridge\Workshop\Car\CarWorkshopDetect()
            )),
            array(new \DesignPatterns\Structural\Bridge\MotorcycleVehicle(
                new \DesignPatterns\Structural\Bridge\Workshop\Motorcycle\MotorcycleWorkshopProduce(),
                new \DesignPatterns\Structural\Bridge\Workshop\Motorcycle\MotorcycleWorkshopAssemble()
            ))
        );
    }

    /**
     * @param \DesignPatterns\Structural\Bridge\Vehicle\VehicleInterface $vehicle
     * @dataProvider vehicle_provider
     */
    final public function testVehicle(\DesignPatterns\Structural\Bridge\Vehicle\VehicleInterface $vehicle): void {
        $this->assertTrue($vehicle->manufacture());
    }
}

redpajama_set_name: RedPajamaGithub


text:
//==================================================================================
// BSD 2-Clause License
//
// Copyright (c) 2014-2022, NJIT, Duality Technologies Inc. and other contributors
//
// All rights reserved.
//
// Author TPOC: contact@openfhe.org
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//==================================================================================

/*
  Provides the utility for sampling trapdoor lattices as described in https://eprint.iacr.org/2017/844.pdf
  https://eprint.iacr.org/2018/946, and "Implementing Token-Based Obfuscation under (Ring) LWE" as described in
  https://eprint.iacr.org/2018/1222.pdf.
 */

#ifndef LBCRYPTO_LATTICE_TRAPDOOR_H
#define LBCRYPTO_LATTICE_TRAPDOOR_H

#include <memory>
#include <utility>

#include "math/matrix.h"

#include "lattice/dgsampling.h"

namespace lbcrypto {

/**
 * @brief Class to store a lattice trapdoor pair generated using construction 1
 * in section 3.2 of https://eprint.iacr.org/2013/297.pdf This construction is
 * based on the hardness of Ring-LWE problem
 */
template <class Element>
class RLWETrapdoorPair {
public:
    // matrix of noise polynomials
    Matrix<Element> m_r;
    // matrix
    Matrix<Element> m_e;
    // CTOR with empty trapdoor pair for deserialization
    RLWETrapdoorPair()
        : m_r(Matrix<Element>([]() { return Element(); }, 0, 0)),
          m_e(Matrix<Element>([]() { return Element(); }, 0, 0)) {}

    RLWETrapdoorPair(const Matrix<Element>& r, const Matrix<Element>& e) : m_r(r), m_e(e) {}

    template <class Archive>
    void save(Archive& ar, std::uint32_t const version) const {
        ar(CEREAL_NVP(m_r));
        ar(CEREAL_NVP(m_e));
    }

    template <class Archive>
    void load(Archive& ar, std::uint32_t const version) {
        ar(CEREAL_NVP(m_r));
        ar(CEREAL_NVP(m_e));
    }
};

/**
 * @brief Static class implementing lattice trapdoor construction in Algorithm 1
 * of https://eprint.iacr.org/2017/844.pdf
 */
template <class Element>
class RLWETrapdoorUtility {
    using ParmType = typename Element::Params;
    using DggType  = typename Element::DggType;
    using IntType  = typename Element::Integer;

public:
    /**
   * Trapdoor generation method as described in Algorithm 1 of
   * https://eprint.iacr.org/2017/844.pdf
   *
   * @param params ring element parameters
   * @param sttdev distribution parameter used in sampling noise polynomials
   * of the trapdoor
   * @param base base of gadget matrix
   * @param bal flag for balanced (true) versus not-balanced (false) digit
   * representation
   * @return the trapdoor pair including the public key (matrix of rings)
   * and trapdoor itself
   */
    static std::pair<Matrix<Element>, RLWETrapdoorPair<Element>> TrapdoorGen(std::shared_ptr<ParmType> params,
                                                                             double stddev, int64_t base = 2,
                                                                             bool bal = false);

    /**
   * Generalized trapdoor generation method (described in "Implementing
   * Token-Based Obfuscation under (Ring) LWE")
   *
   * @param params ring element parameters
   * @param sttdev distribution parameter used in sampling noise polynomials of
   * the trapdoor
   * @param dimension of square matrix
   * @param base base of gadget matrix
   * @param bal flag for balanced (true) versus not-balanced (false) digit
   * representation
   * @return the trapdoor pair including the public key (matrix of rings) and
   * trapdoor itself
   */
    static std::pair<Matrix<Element>, RLWETrapdoorPair<Element>> TrapdoorGenSquareMat(std::shared_ptr<ParmType> params,
                                                                                double stddev, size_t dimension,
                                                                                int64_t base = 2,
                                                                                bool bal     = false);

    /**
   * Gaussian sampling as described in Alogorithm 2 of
   * https://eprint.iacr.org/2017/844.pdf
   *
   * @param n ring dimension
   * @param k matrix sample dimension; k = log2(q)/log2(base) + 2
   * @param &A public key of the trapdoor pair
   * @param &T trapdoor itself
   * @param &u syndrome vector where gaussian that Gaussian sampling is centered
   * around
   * @param &dgg discrete Gaussian generator for integers
   * @param &dggLargeSigma discrete Gaussian generator for perturbation vector
   * sampling (only used in Peikert's method)
   * @param base base of gadget matrix
   * @return the sampled vector (matrix)
   */
    static Matrix<Element> GaussSamp(size_t n, size_t k, const Matrix<Element>& A, const RLWETrapdoorPair<Element>& T,
                                     const Element& u, DggType& dgg, DggType& dggLargeSigma, int64_t base = 2);

    /**
   * Gaussian sampling (described in "Implementing Token-Based Obfuscation under
   * (Ring) LWE")
   *
   * @param n ring dimension
   * @param k matrix sample dimension; k = log2(q)/log2(base) + 2
   * @param &A public key of the trapdoor pair
   * @param &T trapdoor itself
   * @param &U syndrome matrix that Gaussian sampling is centered around
   * @param &dgg discrete Gaussian generator for integers
   * @param &dggLargeSigma discrete Gaussian generator for perturbation vector
   * sampling (only used in Peikert's method)
   * @param base base of gadget matrix
   * @return the sampled vector (matrix)
   */
    static Matrix<Element> GaussSampSquareMat(size_t n, size_t k, const Matrix<Element>& A,
                                              const RLWETrapdoorPair<Element>& T, const Matrix<Element>& U,
                                              DggType& dgg, DggType& dggLargeSigma, int64_t base = 2);

    /**
   * On-line stage of pre-image sampling (includes only G-sampling)
   *
   * @param n ring dimension
   * @param k matrix sample dimension; k = log2(q)/log2(base) + 2
   * @param &A public key of the trapdoor pair
   * @param &T trapdoor itself
   * @param &u syndrome vector where gaussian that Gaussian sampling is centered
   * around
   * @param &dgg discrete Gaussian generator for integers
   * @param &perturbationVector perturbation vector generated during the offline
   * stage
   * @param &base base for G-lattice
   * @return the sampled vector (matrix)
   */
    static Matrix<Element> GaussSampOnline(size_t n, size_t k, const Matrix<Element>& A,
                                           const RLWETrapdoorPair<Element>& T, const Element& u, DggType& dgg,
                                           const std::shared_ptr<Matrix<Element>> perturbationVector, int64_t base = 2);

    /**
   * Offline stage of pre-image sampling (perturbation sampling)
   *
   * @param n ring dimension
   * @param k matrix sample dimension; k = logq + 2
   * @param &T trapdoor itself
   * @param &dgg discrete Gaussian generator for integers
   * @param &dggLargeSigma discrete Gaussian generator for perturbation vector
   * sampling
   * @param &base base for G-lattice
   * @return the sampled vector (matrix)
   */
    static std::shared_ptr<Matrix<Element>> GaussSampOffline(size_t n, size_t k, const RLWETrapdoorPair<Element>& T,
                                                             DggType& dgg, DggType& dggLargeSigma, int64_t base = 2);

    /**
   * Method for perturbation generation as described in Algorithm 4 of
   *https://eprint.iacr.org/2017/844.pdf
   *
   *@param n ring dimension
   *@param s parameter Gaussian distribution
   *@param sigma standard deviation
   *@param &Tprime compact trapdoor matrix
   *@param &dgg discrete Gaussian generator for error sampling
   *@param &dggLargeSigma discrete Gaussian generator for perturbation vector
   *sampling
   *@param *perturbationVector perturbation vector;output of the function
   */
    static void ZSampleSigmaP(size_t n, double s, double sigma, const RLWETrapdoorPair<Element>& Tprime,
                              const DggType& dgg, const DggType& dggLargeSigma,
                              std::shared_ptr<Matrix<Element>> perturbationVector) {
        OPENFHE_DEBUG_FLAG(false);
        TimeVar t1, t1_tot;

        TIC(t1);
        TIC(t1_tot);
        Matrix<Element> Tprime0 = Tprime.m_e;
        Matrix<Element> Tprime1 = Tprime.m_r;

        // k is the bit length
        size_t k = Tprime0.GetCols();

        const std::shared_ptr<ParmType> params = Tprime0(0, 0).GetParams();
        OPENFHE_DEBUG("z1a: " << TOC(t1));  // 0
        TIC(t1);
        // all three Polynomials are initialized with "0" coefficients
        Element va(params, Format::EVALUATION, 1);
        Element vb(params, Format::EVALUATION, 1);
        Element vd(params, Format::EVALUATION, 1);

        for (size_t i = 0; i < k; i++) {
            va += Tprime0(0, i) * Tprime0(0, i).Transpose();
            vb += Tprime1(0, i) * Tprime0(0, i).Transpose();
            vd += Tprime1(0, i) * Tprime1(0, i).Transpose();
        }
        OPENFHE_DEBUG("z1b: " << TOC(t1));  // 9
        TIC(t1);

        // Switch the ring elements (Polynomials) to coefficient representation
        va.SetFormat(Format::COEFFICIENT);
        vb.SetFormat(Format::COEFFICIENT);
        vd.SetFormat(Format::COEFFICIENT);

        OPENFHE_DEBUG("z1c: " << TOC(t1));  // 5
        TIC(t1);

        // Create field elements from ring elements
        Field2n a(va), b(vb), d(vd);

        double scalarFactor = -s * s * sigma * sigma / (s * s - sigma * sigma);

        a = a.ScalarMult(scalarFactor);
        b = b.ScalarMult(scalarFactor);
        d = d.ScalarMult(scalarFactor);

        a = a + s * s;
        d = d + s * s;
        OPENFHE_DEBUG("z1d: " << TOC(t1));  // 0
        TIC(t1);

        // converts the field elements to DFT representation
        a.SetFormat(Format::EVALUATION);
        b.SetFormat(Format::EVALUATION);
        d.SetFormat(Format::EVALUATION);
        OPENFHE_DEBUG("z1e: " << TOC(t1));  // 0
        TIC(t1);

        Matrix<int64_t> p2ZVector([]() { return 0; }, n * k, 1);

        double sigmaLarge = sqrt(s * s - sigma * sigma);

        // for distribution parameters up to 3e5 (experimentally found threshold)
        // use the Peikert's inversion method otherwise, use Karney's method

        if (sigmaLarge > KARNEY_THRESHOLD) {
            // Karney rejection sampling method
            for (size_t i = 0; i < n * k; i++) {
                p2ZVector(i, 0) = dgg.GenerateIntegerKarney(0, sigmaLarge);
            }
        }
        else {
            // Peikert's inversion sampling method
            std::shared_ptr<int64_t> dggVector = dggLargeSigma.GenerateIntVector(n * k);
            for (size_t i = 0; i < n * k; i++) {
                p2ZVector(i, 0) = (dggVector.get())[i];
            }
        }
        OPENFHE_DEBUG("z1f1: " << TOC(t1));
        TIC(t1);

        // create k ring elements in coefficient representation
        Matrix<Element> p2 = SplitInt64IntoElements<Element>(p2ZVector, n, va.GetParams());
        OPENFHE_DEBUG("z1f2: " << TOC(t1));
        TIC(t1);

        // now converting to Format::EVALUATION representation before multiplication
        p2.SetFormat(Format::EVALUATION);

        OPENFHE_DEBUG("z1g: " << TOC(t1));  // 17

        TIC(t1);

        // the dimension is 2x1 - a vector of 2 ring elements
        auto zero_alloc = Element::Allocator(params, Format::EVALUATION);
        Matrix<Element> Tp2(zero_alloc, 2, 1);
        Tp2(0, 0) = (Tprime0 * p2)(0, 0);
        Tp2(1, 0) = (Tprime1 * p2)(0, 0);

        OPENFHE_DEBUG("z1h2: " << TOC(t1));
        TIC(t1);
        // change to coefficient representation before converting to field elements
        Tp2.SetFormat(Format::COEFFICIENT);
        OPENFHE_DEBUG("z1h3: " << TOC(t1));
        TIC(t1);

        Matrix<Field2n> c([]() { return Field2n(); }, 2, 1);

        c(0, 0) = Field2n(Tp2(0, 0)).ScalarMult(-sigma * sigma / (s * s - sigma * sigma));
        c(1, 0) = Field2n(Tp2(1, 0)).ScalarMult(-sigma * sigma / (s * s - sigma * sigma));

        auto p1ZVector = std::make_shared<Matrix<int64_t>>([]() { return 0; }, n * 2, 1);
        OPENFHE_DEBUG("z1i: " << TOC(t1));
        TIC(t1);
        LatticeGaussSampUtility<Element>::ZSampleSigma2x2(a, b, d, c, dgg, p1ZVector);
        OPENFHE_DEBUG("z1j1: " << TOC(t1));  // 14
        TIC(t1);

        // create 2 ring elements in coefficient representation
        Matrix<Element> p1 = SplitInt64IntoElements<Element>(*p1ZVector, n, va.GetParams());
        OPENFHE_DEBUG("z1j2: " << TOC(t1));
        TIC(t1);

        p1.SetFormat(Format::EVALUATION);
        OPENFHE_DEBUG("z1j3: " << TOC(t1));
        TIC(t1);

        *perturbationVector = p1.VStack(p2);
        OPENFHE_DEBUG("z1j4: " << TOC(t1));
        TIC(t1);
        OPENFHE_DEBUG("z1tot: " << TOC(t1_tot));
    }

    /**
   * Method for perturbation generation as described in "Implementing
   *Token-Based Obfuscation under (Ring) LWE"
   *
   *@param n ring dimension
   *@param s spectral norm
   *@param sigma standard deviation
   *@param &Tprime compact trapdoor matrix
   *@param &dgg discrete Gaussian generator for error sampling
   *@param &dggLargeSigma discrete Gaussian generator for perturbation vector
   *sampling
   *@param *perturbationVector perturbation vector;output of the function
   */
    static void SamplePertSquareMat(size_t n, double s, double sigma, const RLWETrapdoorPair<Element>& Tprime,
                                    const DggType& dgg, const DggType& dggLargeSigma,
                                    std::shared_ptr<Matrix<Element>> perturbationVector) {
        Matrix<Element> R = Tprime.m_r;
        Matrix<Element> E = Tprime.m_e;

        const std::shared_ptr<ParmType> params = R(0, 0).GetParams();

        // k is the bit length
        size_t k = R.GetCols();
        size_t d = R.GetRows();

        Matrix<int64_t> p2ZVector([]() { return 0; }, n * k, d);

        double sigmaLarge = sqrt(s * s - sigma * sigma);

        // for distribution parameters up to the experimentally found threshold, use
        // the Peikert's inversion method otherwise, use Karney's method
        if (sigmaLarge > KARNEY_THRESHOLD) {
            // Karney rejection sampling method
            for (size_t i = 0; i < n * k; i++) {
                for (size_t j = 0; j < d; j++) {
                    p2ZVector(i, j) = dgg.GenerateIntegerKarney(0, sigmaLarge);
                }
            }
        }
        else {
            // Peikert's inversion sampling method
            std::shared_ptr<int64_t> dggVector = dggLargeSigma.GenerateIntVector(n * k * d);

            for (size_t i = 0; i < n * k; i++) {
                for (size_t j = 0; j < d; j++) {
                    p2ZVector(i, j) = (dggVector.get())[i * d + j];
                }
            }
        }

        // create a matrix of d*k x d ring elements in coefficient representation
        Matrix<Element> p2 = SplitInt64IntoElements<Element>(p2ZVector.ExtractCol(0), n, params);
        for (size_t i = 1; i < d; i++) {
            p2.HStack(SplitInt64IntoElements<Element>(p2ZVector.ExtractCol(i), n, params));
        }

        // now converting to Format::EVALUATION representation before multiplication
        p2.SetFormat(Format::EVALUATION);

        auto zero_alloc = Element::Allocator(params, Format::EVALUATION);

        Matrix<Element> A = R * (R.Transpose());  // d x d
        Matrix<Element> B = R * (E.Transpose());  // d x d
        Matrix<Element> D = E * (E.Transpose());  // d x d

        // Switch the ring elements (Polynomials) to coefficient representation
        A.SetFormat(Format::COEFFICIENT);
        B.SetFormat(Format::COEFFICIENT);
        D.SetFormat(Format::COEFFICIENT);

        Matrix<Field2n> AF([&]() { return Field2n(n, Format::EVALUATION, true); }, d, d);
        Matrix<Field2n> BF([&]() { return Field2n(n, Format::EVALUATION, true); }, d, d);
        Matrix<Field2n> DF([&]() { return Field2n(n, Format::EVALUATION, true); }, d, d);

        double scalarFactor = -sigma * sigma;

        for (size_t i = 0; i < d; i++) {
            for (size_t j = 0; j < d; j++) {
                AF(i, j) = Field2n(A(i, j));
                AF(i, j) = AF(i, j).ScalarMult(scalarFactor);
                BF(i, j) = Field2n(B(i, j));
                BF(i, j) = BF(i, j).ScalarMult(scalarFactor);
                DF(i, j) = Field2n(D(i, j));
                DF(i, j) = DF(i, j).ScalarMult(scalarFactor);
                if (i == j) {
                    AF(i, j) = AF(i, j) + s * s;
                    DF(i, j) = DF(i, j) + s * s;
                }
            }
        }

        // converts the field elements to DFT representation
        AF.SetFormat(Format::EVALUATION);
        BF.SetFormat(Format::EVALUATION);
        DF.SetFormat(Format::EVALUATION);

        // the dimension is 2d x d
        Matrix<Element> Tp2 = (R.VStack(E)) * p2;

        // change to coefficient representation before converting to field elements
        Tp2.SetFormat(Format::COEFFICIENT);

        Matrix<Element> p1(zero_alloc, 1, 1);

        for (size_t j = 0; j < d; j++) {
            Matrix<Field2n> c([&]() { return Field2n(n, Format::COEFFICIENT); }, 2 * d, 1);

            for (size_t i = 0; i < d; i++) {
                c(i, 0)     = Field2n(Tp2(i, j)).ScalarMult(-sigma * sigma / (s * s - sigma * sigma));
                c(i + d, 0) = Field2n(Tp2(i + d, j)).ScalarMult(-sigma * sigma / (s * s - sigma * sigma));
            }

            auto p1ZVector = std::make_shared<Matrix<int64_t>>([]() { return 0; }, n * 2 * d, 1);

            LatticeGaussSampUtility<Element>::SampleMat(AF, BF, DF, c, dgg, p1ZVector);

            if (j == 0)
                p1 = SplitInt64IntoElements<Element>(*p1ZVector, n, params);
            else
                p1.HStack(SplitInt64IntoElements<Element>(*p1ZVector, n, params));
        }

        p1.SetFormat(Format::EVALUATION);

        *perturbationVector = p1.VStack(p2);

        p1.SetFormat(Format::COEFFICIENT);
    }
};

}  // namespace lbcrypto

#endif


text:
import re
import string
import iso8601
from prettytoml import tokens
from prettytoml.tokens import TYPE_BOOLEAN, TYPE_INTEGER, TYPE_FLOAT, TYPE_DATE, \
    TYPE_MULTILINE_STRING, TYPE_BARE_STRING, TYPE_MULTILINE_LITERAL_STRING, TYPE_LITERAL_STRING, \
    TYPE_STRING
import codecs
import six
from prettytoml.tokens.errors import MalformedDateError
from .errors import BadEscapeCharacter
import functools
import operator

def deserialize(token):
    """
    Deserializes the value of a single tokens.Token instance based on its type.

    Raises DeserializationError when appropriate.
    """

    if token.type == TYPE_BOOLEAN:
        return _to_boolean(token)
    elif token.type == TYPE_INTEGER:
        return _to_int(token)
    elif token.type == TYPE_FLOAT:
        return _to_float(token)
    elif token.type == TYPE_DATE:
        return _to_date(token)
    elif token.type in (TYPE_STRING, TYPE_MULTILINE_STRING, TYPE_BARE_STRING,
                        TYPE_LITERAL_STRING, TYPE_MULTILINE_LITERAL_STRING):
        return _to_string(token)
    else:
        raise Exception('This should never happen!')

def _unescape_str(text):
    """
    Unescapes a string according the TOML spec. Raises BadEscapeCharacter when appropriate.
    """

    # Detect bad escape jobs
    bad_escape_regexp = re.compile(r'([^\\]|^)\\[^btnfr"\\uU]')
    if bad_escape_regexp.findall(text):
        raise BadEscapeCharacter

    # Do the unescaping
    if six.PY2:
        return _unicode_escaped_string(text).decode('string-escape').decode('unicode-escape')
    else:
        return codecs.decode(_unicode_escaped_string(text), 'unicode-escape')

def _unicode_escaped_string(text):
    """
    Escapes all unicode characters in the given string
    """

    if six.PY2:
        text = unicode(text)

    def is_unicode(c):
        return c.lower() not in string.ascii_letters + string.whitespace + string.punctuation + string.digits

    def escape_unicode_char(x):
        if six.PY2:
            return x.encode('unicode-escape')
        else:
            return codecs.encode(x, 'unicode-escape')

    if any(is_unicode(c) for c in text):
        homogeneous_chars = tuple(escape_unicode_char(c) if is_unicode(c) else c.encode() for c in text)
        homogeneous_bytes = functools.reduce(operator.add, homogeneous_chars)
        return homogeneous_bytes.decode()
    else:
        return text

def _to_string(token):
    if token.type == tokens.TYPE_BARE_STRING:
        return token.source_substring

    elif token.type == tokens.TYPE_STRING:
        escaped = token.source_substring[1:-1]
        return _unescape_str(escaped)

    elif token.type == tokens.TYPE_MULTILINE_STRING:
        escaped = token.source_substring[3:-3]

        # Drop the first newline if existed
        if escaped and escaped[0] == '\n':
            escaped = escaped[1:]

        # Remove all occurrences of a slash-newline-zero-or-more-whitespace patterns
        escaped = re.sub(r'\\\n\s*', repl='', string=escaped, flags=re.DOTALL)
        return _unescape_str(escaped)

    elif token.type == tokens.TYPE_LITERAL_STRING:
        return token.source_substring[1:-1]

    elif token.type == tokens.TYPE_MULTILINE_LITERAL_STRING:
        text = token.source_substring[3:-3]
        if text[0] == '\n':
            text = text[1:]
        return text

    raise RuntimeError('Control should never reach here.')

def _to_int(token):
    return int(token.source_substring.replace('_', ''))

def _to_float(token):
    assert token.type == tokens.TYPE_FLOAT
    string = token.source_substring.replace('_', '')
    return float(string)

def _to_boolean(token):
    return token.source_substring == 'true'

_correct_date_format = re.compile(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|(\+|-)\d{2}:\d{2})')

def _to_date(token):
    if not _correct_date_format.match(token.source_substring):
        raise MalformedDateError
    return iso8601.parse_date(token.source_substring)


text: Calculator that provides simple operators


text:
.class final Landroid/support/v4/view/h;
.super Landroid/view/View$AccessibilityDelegate;

# instance fields
.field final synthetic a:Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;

# direct methods
.method constructor <init>(Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;)V
    .locals 0

    iput-object p1, p0, Landroid/support/v4/view/h;->a:Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;

    invoke-direct {p0}, Landroid/view/View$AccessibilityDelegate;-><init>()V

    return-void
.end method

# virtual methods
.method public dispatchPopulateAccessibilityEvent(Landroid/view/View;Landroid/view/accessibility/AccessibilityEvent;)Z
    .locals 1

    iget-object v0, p0, Landroid/support/v4/view/h;->a:Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;

    invoke-interface {v0, p1, p2}, Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;->dispatchPopulateAccessibilityEvent(Landroid/view/View;Landroid/view/accessibility/AccessibilityEvent;)Z

    move-result v0

    return v0
.end method

.method public getAccessibilityNodeProvider(Landroid/view/View;)Landroid/view/accessibility/AccessibilityNodeProvider;
    .locals 1

    iget-object v0, p0, Landroid/support/v4/view/h;->a:Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;

    invoke-interface {v0, p1}, Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;->getAccessibilityNodeProvider(Landroid/view/View;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/accessibility/AccessibilityNodeProvider;

    return-object v0
.end method

.method public onInitializeAccessibilityEvent(Landroid/view/View;Landroid/view/accessibility/AccessibilityEvent;)V
    .locals 1

    iget-object v0, p0, Landroid/support/v4/view/h;->a:Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;

    invoke-interface {v0, p1, p2}, Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;->onInitializeAccessibilityEvent(Landroid/view/View;Landroid/view/accessibility/AccessibilityEvent;)V

    return-void
.end method

.method public onInitializeAccessibilityNodeInfo(Landroid/view/View;Landroid/view/accessibility/AccessibilityNodeInfo;)V
    .locals 1

    iget-object v0, p0, Landroid/support/v4/view/h;->a:Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;

    invoke-interface {v0, p1, p2}, Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;->onInitializeAccessibilityNodeInfo(Landroid/view/View;Ljava/lang/Object;)V

    return-void
.end method

.method public onPopulateAccessibilityEvent(Landroid/view/View;Landroid/view/accessibility/AccessibilityEvent;)V
    .locals 1

    iget-object v0, p0, Landroid/support/v4/view/h;->a:Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;

    invoke-interface {v0, p1, p2}, Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;->onPopulateAccessibilityEvent(Landroid/view/View;Landroid/view/accessibility/AccessibilityEvent;)V

    return-void
.end method

.method public onRequestSendAccessibilityEvent(Landroid/view/ViewGroup;Landroid/view/View;Landroid/view/accessibility/AccessibilityEvent;)Z
    .locals 1

    iget-object v0, p0, Landroid/support/v4/view/h;->a:Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;

    invoke-interface {v0, p1, p2, p3}, Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;->onRequestSendAccessibilityEvent(Landroid/view/ViewGroup;Landroid/view/View;Landroid/view/accessibility/AccessibilityEvent;)Z

    move-result v0

    return v0
.end method

.method public performAccessibilityAction(Landroid/view/View;ILandroid/os/Bundle;)Z
    .locals 1

    iget-object v0, p0, Landroid/support/v4/view/h;->a:Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;

    invoke-interface {v0, p1, p2, p3}, Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;->performAccessibilityAction(Landroid/view/View;ILandroid/os/Bundle;)Z

    move-result v0

    return v0
.end method

.method public sendAccessibilityEvent(Landroid/view/View;I)V
    .locals 1

    iget-object v0, p0, Landroid/support/v4/view/h;->a:Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;

    invoke-interface {v0, p1, p2}, Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;->sendAccessibilityEvent(Landroid/view/View;I)V

    return-void
.end method

.method public sendAccessibilityEventUnchecked(Landroid/view/View;Landroid/view/accessibility/AccessibilityEvent;)V
    .locals 1

    iget-object v0, p0, Landroid/support/v4/view/h;->a:Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;

    invoke-interface {v0, p1, p2}, Landroid/support/v4/view/AccessibilityDelegateCompatJellyBean$AccessibilityDelegateBridgeJellyBean;->sendAccessibilityEventUnchecked(Landroid/view/View;Landroid/view/accessibility/AccessibilityEvent;)V

    return-void
.end method


text:
from django.test import TestCase
from django.core import mail
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User

from model_mommy import mommy

from .models import Location

class DetailTest(TestCase):
    def setUp(self):
        user = User.objects.create_user('test', 'no@no.no', 'password')
        mommy.make_recipe('locations.san_francisco')

    def test_location_detail(self):
        response = self.client.get(
            reverse('locations:detail', args=("san-francisco",))
            )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "San Francisco")

    def test_location_detail_related(self):
        mommy.make('projects.team', user=User.objects.get(username='test'))
        self.client.login(username='test', password='password')
        self.client.get(reverse('registration:base') + 'san-francisco/')
        response = self.client.get(
            reverse('locations:detail', args=("san-francisco",))
            )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Visit Project")

    def test_location_detail_sponsor(self):
        mommy.make(
            'locations.sponsor',
            location = Location.objects.get(name='San Francisco'),
            name = 'John Glenn'
            )
        response = self.client.get(
            reverse('locations:detail', args=("san-francisco",))
            )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "John Glenn")

    def test_location_detail_lead(self):
        mommy.make(
            'locations.lead',
            location = Location.objects.get(name='San Francisco'),
            lead = User.objects.get(username='test'),
            )
        response = self.client.get(
            reverse('locations:detail', args=("san-francisco",))
            )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Email")

    def test_location_detail_resource(self):
        mommy.make(
            'locations.resource',
            location = Location.objects.get(name='San Francisco'),
            name = 'John Glenn'
            )
        response = self.client.get(
            reverse('locations:detail', args=("san-francisco",))
            )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "John Glenn")

class ListTest(TestCase):
    def setUp(self):
        mommy.make_recipe('locations.san_francisco')

    def test_list_locations(self):
        response = self.client.get(
            reverse('locations:list')
            )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "San Francisco")

class EditTest(TestCase):
    def setUp(self):
        User.objects.create_user('test', 'no@no.no', 'password')
        User.objects.create_superuser('super', 'no@no.no', 'password')
        mommy.make_recipe('locations.san_francisco')

    def test_can_edit_location_unauthenticated(self):
        response = self.client.get(
            reverse('locations:edit', args=('san-francisco',))
            )
        self.assertNotEqual(response.status_code, 200)

    def test_can_edit_location_unprivileged(self):
        self.client.login(username='test', password='password')
        response = self.client.get(
            reverse('locations:edit', args=('san-francisco',))
            )
        self.assertEqual(response.status_code, 403)

    def test_can_edit_location_as_lead(self):
        mommy.make(
            'locations.lead',
            location = Location.objects.get(name='San Francisco'),
            lead = User.objects.get(username='test'),
            )
        self.client.login(username='test', password='password')
        response = self.client.get(
            reverse('locations:edit', args=('san-francisco',))
            )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "San Francisco")

    def test_can_edit_location_as_super(self):
        self.client.login(username='super', password='password')
        response = self.client.get(
            reverse('locations:edit', args=('san-francisco',))
            )
        self.assertEqual(response.status_code, 200)

    def test_edit_location(self):
        self.client.login(username='super', password='password')
        response = self.client.post(
            reverse('locations:edit', args=('san-francisco',)), {
                'name': 'San Francisco',
                'slug': 'san-francisco',
                'description': 'Description',
                'timezone': '-8.0',
                'city': 'San Francisco',
                'country': 'US',
                'continent': 'NA',
                'lat': '0',
                'lon': '0',
                'capacity': '100',
                'sponsor-TOTAL_FORMS': '0',
                'sponsor-INITIAL_FORMS': '0',
                'lead-TOTAL_FORMS': '0',
                'lead-INITIAL_FORMS': '0',
                'localaward-TOTAL_FORMS': '0',
                'localaward-INITIAL_FORMS': '0',
                'nomination-TOTAL_FORMS': '0',
                'nomination-INITIAL_FORMS': '0',
                'resource-TOTAL_FORMS': '0',
                'resource-INITIAL_FORMS': '0',
            }),

        self.assertTrue(Location.objects.get(description='Description'))

class AttendeesTest(TestCase):
    def setUp(self):
        User.objects.create_user('test', 'no@no.no', 'password')
        User.objects.create_superuser('super', 'no@no.no', 'password')
        mommy.make_recipe('locations.san_francisco')

    def test_view_attendees_unauthenticated(self):
        response = self.client.get(
            reverse('locations:attendees', args=('san-francisco',))
            )
        self.assertNotEqual(response.status_code, 200)

    def test_view_attendees_unprivilged(self):
        self.client.login(username='test', password='password')
        response = self.client.get(
            reverse('locations:attendees', args=('san-francisco',))
            )
        self.assertNotEqual(response.status_code, 200)

    def test_view_attendees_as_lead(self):
        mommy.make(
            'locations.lead',
            location = Location.objects.get(name='San Francisco'),
            lead = User.objects.get(username='test'),
            )
        self.client.login(username='test', password='password')
        self.client.get(reverse('registration:base') + 'san-francisco/')
        response = self.client.get(
            reverse('locations:attendees', args=('san-francisco',))
            )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "no@no.no")

    def test_view_attendees_as_super(self):
        self.client.login(username='super', password='password')
        self.client.get(reverse('registration:base') + 'san-francisco/')
        response = self.client.get(
            reverse('locations:attendees', args=('san-francisco',))
            )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "no@no.no")

class CSVTest(TestCase):
    def setUp(self):
        User.objects.create_user('test', 'no@no.no', 'password')
        User.objects.create_superuser('super', 'no@no.no', 'password')
        mommy.make_recipe('locations.san_francisco')
        self.client.login(username='test', password='password')
        self.client.get(reverse('registration:base') + 'san-francisco/')

    def test_export_attendees_unauthenticated(self):
        response = self.client.get(
            reverse('locations:export', args=('san-francisco',))
            )
        self.assertNotEqual(response.status_code, 200)

    def test_export_attendees_unprivilged(self):
        self.client.login(username='test', password='password')
        response = self.client.get(
            reverse('locations:export', args=('san-francisco',))
            )
        self.assertNotEqual(response.status_code, 200)

    def test_export_attendees_as_lead(self):
        mommy.make(
            'locations.lead',
            location = Location.objects.get(name='San Francisco'),
            lead = User.objects.get(username='test'),
            )
        self.client.login(username='test', password='password')
        response = self.client.get(
            reverse('locations:export', args=('san-francisco',))
            )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "no@no.no")

    def test_export_attendees_as_super(self):
        self.client.login(username='super', password='password')
        self.client.get(reverse('registration:base') + 'san-francisco/')
        response = self.client.get(
            reverse('locations:export', args=('san-francisco',))
            )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "no@no.no")

class RelatedTest(TestCase):
    def setUp(self):
        User.objects.create_user('test', 'no@no.no', 'password')
        mommy.make_recipe('locations.san_francisco')
        self.client.login(username='test', password='password')
        self.client.get(
            reverse('registration:register', args=('san-francisco',))
            )
        mommy.make('projects.team', user=User.objects.get(username='test'))

    def test_related_projects(self):
        response = self.client.get(
            reverse('locations:related', args=('san-francisco',))
            )
        print response
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "project")


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JWPlayer AMP Example</title>
    <link rel="canonical" href="amps.html" >
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    <meta property="og:title" content="title_tag" />
    <link href='https://fonts.googleapis.com/css?family=Georgia%7COpen+Sans%7CRoboto' rel='stylesheet' type='text/css'>

JWPlayer AMP Examples

Responsive

    <amp-jwplayer
      data-media-id="BZ6tc0gy"
      data-player-id="uoIbMPm3"
      layout="responsive"
      width="16"
      height="9"
    >
    </amp-jwplayer>

Non-responsive, with a playlist

    <amp-jwplayer
      data-playlist-id="482jsTAr"
      data-player-id="uoIbMPm3"
      width="480"
      height="270"
    >
    </amp-jwplayer>

Docking

    <amp-jwplayer
      data-media-id="CtaIzmFs"
      data-player-id="BjcwyK37"
      dock
      width="480"
      height="270"
    >
    </amp-jwplayer>

Responsive contextual

    <amp-jwplayer
      data-player-id="BjcwyK37"
      data-media-id="CtaIzmFs"
      data-content-search="__CONTEXTUAL__"
      data-content-backfill="true"
      data-content-recency="9D"
      layout="responsive"
      width="16"
      height="9"
    >
    </amp-jwplayer>

Non-Responsive, with a VAST Ad

    <amp-jwplayer
      data-media-id="NsdRZqng"
      data-player-id="WmASC9FK"
      width="480"
      height="270"
    >
    </amp-jwplayer>

Non-Responsive, with an IMA Ad

    <amp-jwplayer
      data-media-id="3h8NHAIV"
      data-player-id="n6vw37Z7"
      width="480"
      height="270"
    >
    </amp-jwplayer>

External Controls

    <amp-jwplayer
      id="myVideo"
      data-media-id="CtaIzmFs"
      data-player-id="BjcwyK37"
      width="480"
      height="270"
    >
    </amp-jwplayer>

      <button on="tap:myVideo.play">Play</button>
      <button on="tap:myVideo.pause">Pause</button>
      <button on="tap:myVideo.mute">Mute</button>
      <button on="tap:myVideo.unmute">Unmute</button>
      <button on="tap:myVideo.fullscreen">FS</button>


text:
require 'sidekiq/web'

module Sidetiq
  module Grouping
    module Web
      VIEWS = File.expand_path('views', File.dirname(__FILE__))

      def self.registered(app)
        app.get "/grouping" do
          @batches = Sidekiq::Grouping::Batch.all
          erb File.read(File.join(VIEWS, 'index.erb')), locals: {view_path: VIEWS}
        end

        app.post "/grouping/:name/delete" do
          worker_class, queue = Sidekiq::Grouping::Batch.extract_worker_klass_and_queue(params['name'])
          batch = Sidekiq::Grouping::Batch.new(worker_class, queue)
          batch.delete
          redirect "#{root_path}/grouping"
        end
      end

    end
  end
end

Sidekiq::Web.register(Sidetiq::Grouping::Web)
Sidekiq::Web.tabs["Grouping"] = "grouping"


text:
NSString * const RACKeyValueChangeCausedByDeallocationKey = @"RACKeyValueChangeCausedByDeallocationKey";
NSString * const RACKeyValueChangeAffectedOnlyLastComponentKey = @"RACKeyValueChangeAffectedOnlyLastComponentKey";

@implementation NSObject (RACKVOWrapper)

- (RACDisposable *)rac_observeKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options observer:(NSObject *)observer block:(void (^)(id, NSDictionary *))block {
	NSCParameterAssert(block != nil);
	NSCParameterAssert(keyPath.rac_keyPathComponents.count > 0);

	keyPath = [keyPath copy];

	@unsafeify(observer);

	NSArray *keyPathComponents = keyPath.rac_keyPathComponents;
	BOOL keyPathHasOneComponent = (keyPathComponents.count == 1);
	NSString *keyPathHead = keyPathComponents[0];
	NSString *keyPathTail = keyPath.rac_keyPathByDeletingFirstKeyPathComponent;

	RACCompoundDisposable *disposable = [RACCompoundDisposable compoundDisposable];

	// The disposable that groups all disposal necessary to clean up the callbacks
	// added to the value of the first key path component.
	RACSerialDisposable *firstComponentSerialDisposable = [RACSerialDisposable serialDisposableWithDisposable:[RACCompoundDisposable compoundDisposable]];
	RACCompoundDisposable * (^firstComponentDisposable)(void) = ^{
		return (RACCompoundDisposable *)firstComponentSerialDisposable.disposable;
	};

	[disposable addDisposable:firstComponentSerialDisposable];

	// Adds the callback block to the value's deallocation. Also adds the logic to
	// clean up the callback to the firstComponentDisposable.
	void (^addDeallocObserverToPropertyValue)(NSObject *, NSString *, NSObject *) = ^(NSObject *parent, NSString *propertyKey, NSObject *value) {
		// If a key path value is the observer, commonly when a key path begins
		// with "self", we prevent deallocation triggered callbacks for any such key
		// path components. Thus, the observer's deallocation is not considered a
		// change to the key path.
		@strongify(observer);
		if (value == observer) return;

		objc_property_t property = class_getProperty(object_getClass(parent), propertyKey.UTF8String);
		if (property == NULL) {
			// If we can't find an Objective-C property for this key, we assume
			// that we don't need to observe its deallocation (thus matching
			// vanilla KVO behavior).
			//
			// Even if we wanted to, there's not enough type information on
			// ivars to figure out its memory management.
			return;
		}

		rac_propertyAttributes *attributes = rac_copyPropertyAttributes(property);
		if (attributes == NULL) return;

		@onExit {
			free(attributes);
		};

		if (attributes->objectClass == nil && strcmp(attributes->type, @encode(id)) != 0) {
			// If this property isn't actually an object (or is a Class object),
			// no point in observing the deallocation of the wrapper returned by
			// KVC.
			return;
		}

		if (!attributes->weak) {
			// If this property is an object, but not declared `weak`, we
			// don't need to watch for it spontaneously being set to nil.
			//
			// Attempting to observe non-weak properties will result in
			// broken behavior for dynamic getters, so don't even try.
			return;
		}

		NSDictionary *change = @{
			NSKeyValueChangeKindKey: @(NSKeyValueChangeSetting),
			NSKeyValueChangeNewKey: NSNull.null,
			RACKeyValueChangeCausedByDeallocationKey: @YES,
			RACKeyValueChangeAffectedOnlyLastComponentKey: @(keyPathHasOneComponent)
		};

		RACCompoundDisposable *valueDisposable = value.rac_deallocDisposable;
		RACDisposable *deallocDisposable = [RACDisposable disposableWithBlock:^{
			block(nil, change);
		}];

		[valueDisposable addDisposable:deallocDisposable];
		[firstComponentDisposable() addDisposable:[RACDisposable disposableWithBlock:^{
			[valueDisposable removeDisposable:deallocDisposable];
		}]];
	};

	// Adds the callback block to the remaining path components on the value. Also
	// adds the logic to clean up the callbacks to the firstComponentDisposable.
	void (^addObserverToValue)(NSObject *) = ^(NSObject *value) {
		@strongify(observer);
		RACDisposable *observerDisposable = [value rac_observeKeyPath:keyPathTail options:(options & ~NSKeyValueObservingOptionInitial) observer:observer block:block];
		[firstComponentDisposable() addDisposable:observerDisposable];
	};

	// Observe only the first key path component, when the value changes clean up
	// the callbacks on the old value, add callbacks to the new value and call the
	// callback block as needed.
	//
	// Note this does not use NSKeyValueObservingOptionInitial so this only
	// handles changes to the value, callbacks to the initial value must be added
	// separately.
	NSKeyValueObservingOptions trampolineOptions = (options | NSKeyValueObservingOptionPrior) & ~NSKeyValueObservingOptionInitial;
	RACKVOTrampoline *trampoline = [[RACKVOTrampoline alloc] initWithTarget:self observer:observer keyPath:keyPathHead options:trampolineOptions block:^(id trampolineTarget, id trampolineObserver, NSDictionary *change) {
		// Prepare the change dictionary by adding the RAC specific keys
		{
			NSMutableDictionary *newChange = [change mutableCopy];
			newChange[RACKeyValueChangeCausedByDeallocationKey] = @NO;
			newChange[RACKeyValueChangeAffectedOnlyLastComponentKey] = @(keyPathHasOneComponent);
			change = newChange.copy;
		}

		// If this is a prior notification, clean up all the callbacks added to the
		// previous value and call the callback block. Everything else is deferred
		// until after we get the notification after the change.
		if ([change[NSKeyValueChangeNotificationIsPriorKey] boolValue]) {
			[firstComponentDisposable() dispose];

			if ((options & NSKeyValueObservingOptionPrior) != 0) {
				block([trampolineTarget valueForKeyPath:keyPath], change);
			}

			return;
		}

		// From here the notification is not prior.
		NSObject *value = [trampolineTarget valueForKey:keyPathHead];

		// If the value has changed but is nil, there is no need to add callbacks to
		// it, just call the callback block.
		if (value == nil) {
			block(nil, change);
			return;
		}

		// From here the notification is not prior and the value is not nil.

		// Create a new firstComponentDisposable while getting rid of the old one at
		// the same time, in case this is being called concurrently.
		RACDisposable *oldFirstComponentDisposable = [firstComponentSerialDisposable swapInDisposable:[RACCompoundDisposable compoundDisposable]];
		[oldFirstComponentDisposable dispose];

		addDeallocObserverToPropertyValue(trampolineTarget, keyPathHead, value);

		// If there are no further key path components, there is no need to add the
		// other callbacks, just call the callback block with the value itself.
		if (keyPathHasOneComponent) {
			block(value, change);
			return;
		}

		// The value has changed, is not nil, and there are more key path components
		// to consider. Add the callbacks to the value for the remaining key path
		// components and call the callback block with the current value of the full
		// key path.
		addObserverToValue(value);
		block([value valueForKeyPath:keyPathTail], change);
	}];

	// Stop the KVO observation when this one is disposed of.
	[disposable addDisposable:trampoline];

	// Add the callbacks to the initial value if needed.
	NSObject *value = [self valueForKey:keyPathHead];
	if (value != nil) {
		addDeallocObserverToPropertyValue(self, keyPathHead, value);

		if (!keyPathHasOneComponent) {
			addObserverToValue(value);
		}
	}

	// Call the block with the initial value if needed.
	if ((options & NSKeyValueObservingOptionInitial) != 0) {
		id initialValue = [self valueForKeyPath:keyPath];
		NSDictionary *initialChange = @{
			NSKeyValueChangeKindKey: @(NSKeyValueChangeSetting),
			NSKeyValueChangeNewKey: initialValue ?: NSNull.null,
			RACKeyValueChangeCausedByDeallocationKey: @NO,
			RACKeyValueChangeAffectedOnlyLastComponentKey: @(keyPathHasOneComponent)
		};
		block(initialValue, initialChange);
	}

	RACCompoundDisposable *observerDisposable = observer.rac_deallocDisposable;
	RACCompoundDisposable *selfDisposable = self.rac_deallocDisposable;
	// Dispose of this observation if the receiver or the observer deallocate.
	[observerDisposable addDisposable:disposable];
	[selfDisposable addDisposable:disposable];

	return [RACDisposable disposableWithBlock:^{
		[disposable dispose];
		[observerDisposable removeDisposable:disposable];
		[selfDisposable removeDisposable:disposable];
	}];
}

@end

@implementation NSObject (RACKVOWrapperDeprecated)

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"

- (RACKVOTrampoline *)rac_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options block:(RACKVOBlock)block {
	return [[RACKVOTrampoline alloc] initWithTarget:self observer:observer keyPath:keyPath options:options block:block];
}

#pragma clang diagnostic pop

@end


text:
from marvin.cloudstackAPI import *
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.cloudstackException import CloudstackAPIException
from marvin.lib.base import Account
from marvin.lib.utils import cleanup_resources
from marvin.sshClient import SshClient
from nose.plugins.attrib import attr

import inspect
import logging
import os
import re

class TestStaticRoles(cloudstackTestCase):
    """Tests static role api-checker
    """

    def setUp(self):
        self.apiclient = self.testClient.getApiClient()
        self.dbclient = self.testClient.getDbConnection()
        self.mgtSvrDetails = self.config.__dict__["mgtSvr"][0].__dict__
        self.cleanup = []
        self.testdata = {
            "account": {
                "email": "mtu@test.cloud",
                "firstname": "Marvin",
                "lastname": "TestUser",
                "username": "staticrole_acctest-",
                "password": "password",
            }
        }

        feature_enabled = self.apiclient.listCapabilities(listCapabilities.listCapabilitiesCmd()).dynamicrolesenabled
        if feature_enabled:
            self.skipTest("Dynamic role-based API checker is enabled, skipping tests for static role-base API checker")

        commandsProperties = []
        try:
            sshClient = SshClient(
                self.mgtSvrDetails["mgtSvrIp"],
                22,
                self.mgtSvrDetails["user"],
                self.mgtSvrDetails["passwd"],
                retries=1,
                log_lvl=logging.INFO
            )
            result = sshClient.runCommand("cat /etc/cloudstack/management/commands.properties")
            if 'status' in result and result['status'] == 'SUCCESS' and 'stdout' in result and len(result['stdout']) > 0:
                commandsProperties = result['stdout']
        except Exception:
            self.debug("Failed to ssh into mgmt server host and grab commands.properties file")
            testDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
            localFileName = os.path.abspath(testDir + "/../../../client/conf/commands.properties.in")
            if os.path.isfile(localFileName):
                self.info("Detected that we're running in developer mode with maven, using file at:" + localFileName)
                with open(localFileName) as f:
                    commandsProperties = f.readlines()

        if len(commandsProperties) < 1:
            self.skipTest("Unable to find commands.properties, skipping this test")

        apiMap = {}
        for line in commandsProperties:
            if not line or line == '' or line == '\n' or line.startswith('#'):
                continue
            name, value = line.split('=')
            apiMap[name.strip()] = value.strip()

        self.roleApiMap = {} # role to list of apis allowed
        octetKey = {'Admin':1, 'DomainAdmin':4, 'User':8}
        for role in octetKey.keys():
            for api in sorted(apiMap.keys()):
                if (octetKey[role] & int(apiMap[api])) > 0:
                    if role not in self.roleApiMap:
                        self.roleApiMap[role] = []
                    self.roleApiMap[role].append(api)

    def tearDown(self):
        try:
           cleanup_resources(self.apiclient, self.cleanup)
        except Exception as e:
            self.debug("Warning! Exception in tearDown: %s" % e)

    def translateRoleToAccountType(self, role_type):
        if role_type == 'User':
            return 0
        elif role_type == 'Admin':
            return 1
        elif role_type == 'DomainAdmin':
            return 2
        return -1

    @attr(tags=['advanced', 'simulator', 'basic', 'sg'], required_hardware=False)
    def test_static_role_account_acls(self):
        """
            Tests allowed APIs for common account types
        """
        for role in ['Admin', 'DomainAdmin', 'User']:
            accountType = self.translateRoleToAccountType(role)
            account = Account.create(
                self.apiclient,
                self.testdata['account'],
                admin=accountType
            )
            self.cleanup.append(account)
            userApiClient = self.testClient.getUserApiClient(UserName=account.name, DomainName=account.domain, type=accountType)
            allowedApis = map(lambda x: x.name, userApiClient.listApis(listApis.listApisCmd()))
            allApis = map(lambda x: x.name, self.apiclient.listApis(listApis.listApisCmd()))
            for api in self.roleApiMap[role]:
                if api not in allApis:
                    continue
                if api not in allowedApis:
                    self.fail("API configured in commands.properties not returned by listApis: " + api + " for role: " + role)


text:
package com.google.gdata.data.gtt;

import com.google.gdata.data.AbstractExtension;
import com.google.gdata.data.AttributeGenerator;
import com.google.gdata.data.AttributeHelper;
import com.google.gdata.data.ExtensionDescription;
import com.google.gdata.util.ParseException;

/**
 * Describes a percent complete.
 *
 *
 */
@ExtensionDescription.Default(
    nsAlias = GttNamespace.GTT_ALIAS,
    nsUri = GttNamespace.GTT,
    localName = PercentComplete.XML_NAME)
public class PercentComplete extends AbstractExtension {

  /** XML element name */
  static final String XML_NAME = "percentComplete";

  /** Value */
  private Integer value = null;

  /**
   * Default mutable constructor.
   */
  public PercentComplete() {
    super();
  }

  /**
   * Immutable constructor.
   *
   * @param value value.
   */
  public PercentComplete(Integer value) {
    super();
    setValue(value);
    setImmutable(true);
  }

  /**
   * Returns the value.
   *
   * @return value
   */
  public Integer getValue() {
    return value;
  }

  /**
   * Sets the value.
   *
   * @param value value or null to reset
   */
  public void setValue(Integer value) {
    throwExceptionIfImmutable();
    this.value = value;
  }

  /**
   * Returns whether it has the value.
   *
   * @return whether it has the value
   */
  public boolean hasValue() {
    return getValue() != null;
  }

  @Override
  protected void validate() {
    if (value == null) {
      throw new IllegalStateException("Missing text content");
    }
  }

  /**
   * Returns the extension description, specifying whether it is required, and
   * whether it is repeatable.
   *
   * @param required   whether it is required
   * @param repeatable whether it is repeatable
   * @return extension description
   */
  public static ExtensionDescription getDefaultDescription(boolean required,
      boolean repeatable) {
    ExtensionDescription desc =
        ExtensionDescription.getDefaultDescription(PercentComplete.class);
    desc.setRequired(required);
    desc.setRepeatable(repeatable);
    return desc;
  }

  @Override
  protected void putAttributes(AttributeGenerator generator) {
    generator.setContent(value.toString());
  }

  @Override
  protected void consumeAttributes(AttributeHelper helper) throws ParseException
      {
    value = helper.consumeInteger(null, true);
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (!sameClassAs(obj)) {
      return false;
    }
    PercentComplete other = (PercentComplete) obj;
    return eq(value, other.value);
  }

  @Override
  public int hashCode() {
    int result = getClass().hashCode();
    if (value != null) {
      result = 37 * result + value.hashCode();
    }
    return result;
  }

  @Override
  public String toString() {
    return "{PercentComplete value=" + value + "}";
  }

}


text:
<ViewAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/viewAnimator"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_menu"
    android:inAnimation="@android:anim/slide_in_left"
    android:keepScreenOn="true"
    android:outAnimation="@android:anim/slide_out_right"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <include layout="@layout/pause_view" />
    <include layout="@layout/ingame_view" />

</ViewAnimator>


text:
package color

import "fmt"

// Foreground colors.
const (
	Black Color = iota + 30
	Red
	Green
	Yellow
	Blue
	Magenta
	Cyan
	White
)

// Color represents a text color.
type Color uint8

// Add adds the coloring to the given string.
func (c Color) Add(s string) string {
	return fmt.Sprintf("\x1b[%dm%s\x1b[0m", uint8(c), s)
}