text:
package org.kuali.rice.kim.api.identity.phone;

import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.CoreConstants;
import org.kuali.rice.core.api.mo.AbstractDataTransferObject;
import org.kuali.rice.core.api.mo.ModelBuilder;
import org.kuali.rice.kim.api.KimApiConstants;
import org.kuali.rice.kim.api.identity.CodedAttribute;
import org.w3c.dom.Element;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.Serializable;
import java.util.Collection;

@XmlRootElement(name = EntityPhone.Constants.ROOT_ELEMENT_NAME)
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = EntityPhone.Constants.TYPE_NAME, propOrder = {
    EntityPhone.Elements.ID,
    EntityPhone.Elements.ENTITY_TYPE_CODE,
    EntityPhone.Elements.ENTITY_ID,
    EntityPhone.Elements.PHONE_TYPE,
    EntityPhone.Elements.COUNTRY_CODE,
    EntityPhone.Elements.PHONE_NUMBER,
    EntityPhone.Elements.EXTENSION_NUMBER,
    EntityPhone.Elements.FORMATTED_PHONE_NUMBER,
    EntityPhone.Elements.COUNTRY_CODE_UNMASKED,
    EntityPhone.Elements.PHONE_NUMBER_UNMASKED,
    EntityPhone.Elements.EXTENSION_NUMBER_UNMASKED,
    EntityPhone.Elements.FORMATTED_PHONE_NUMBER_UNMASKED,
    EntityPhone.Elements.SUPPRESS_PHONE,
    EntityPhone.Elements.DEFAULT_VALUE,
    EntityPhone.Elements.ACTIVE,
    CoreConstants.CommonElements.VERSION_NUMBER,
    CoreConstants.CommonElements.OBJECT_ID,
    CoreConstants.CommonElements.FUTURE_ELEMENTS
})
public final class EntityPhone extends AbstractDataTransferObject
    implements EntityPhoneContract
{

    @XmlElement(name = Elements.ID, required = false)
    private final String id;
    @XmlElement(name = Elements.ENTITY_TYPE_CODE, required = false)
    private final String entityTypeCode;
    @XmlElement(name = Elements.ENTITY_ID, required = false)
    private final String entityId;
    @XmlElement(name = Elements.PHONE_TYPE, required = false)
    private final CodedAttribute phoneType;
    @XmlElement(name = Elements.PHONE_NUMBER, required = false)
    private final String phoneNumber;
    @XmlElement(name = Elements.EXTENSION_NUMBER, required = false)
    private final String extensionNumber;
    @XmlElement(name = Elements.COUNTRY_CODE, required = false)
    private final String countryCode;
    @XmlElement(name = Elements.PHONE_NUMBER_UNMASKED, required = false)
    private final String phoneNumberUnmasked;
    @XmlElement(name = Elements.EXTENSION_NUMBER_UNMASKED, required = false)
    private final String extensionNumberUnmasked;
    @XmlElement(name = Elements.COUNTRY_CODE_UNMASKED, required = false)
    private final String countryCodeUnmasked;
    @XmlElement(name = Elements.FORMATTED_PHONE_NUMBER, required = false)
    private final String formattedPhoneNumber;
    @XmlElement(name = Elements.FORMATTED_PHONE_NUMBER_UNMASKED, required = false)
    private final String formattedPhoneNumberUnmasked;
    @XmlElement(name = Elements.SUPPRESS_PHONE, required = false)
    private final boolean suppressPhone;
    @XmlElement(name = Elements.DEFAULT_VALUE, required = false)
    private final boolean defaultValue;
    @XmlElement(name = CoreConstants.CommonElements.VERSION_NUMBER, required = false)
    private final Long versionNumber;
    @XmlElement(name = CoreConstants.CommonElements.OBJECT_ID, required = false)
    private final String objectId;
    @XmlElement(name = Elements.ACTIVE, required = false)
    private final boolean active;
    @SuppressWarnings("unused")
    @XmlAnyElement
    private final Collection<Element> _futureElements = null;

    /**
     * Private constructor used only by JAXB.
     *
     */
    private EntityPhone() {
        this.id = null;
        this.entityId = null;
        this.entityTypeCode = null;
        this.phoneType = null;
        this.phoneNumber = null;
        this.extensionNumber = null;
        this.countryCode = null;
        this.phoneNumberUnmasked = null;
        this.extensionNumberUnmasked = null;
        this.countryCodeUnmasked = null;
        this.formattedPhoneNumber = null;
        this.formattedPhoneNumberUnmasked = null;
        this.suppressPhone = false;
        this.defaultValue = false;
        this.versionNumber = null;
        this.objectId = null;
        this.active = false;
    }

    private EntityPhone(Builder builder) {
        this.id = builder.getId();
        this.entityId = builder.getEntityId();
        this.entityTypeCode = builder.getEntityTypeCode();
        this.phoneType = (builder.getPhoneType() != null) ? builder.getPhoneType().build() : null;
        this.phoneNumber = builder.getPhoneNumber();
        this.extensionNumber = builder.getExtensionNumber();
        this.countryCode = builder.getCountryCode();
        this.phoneNumberUnmasked = builder.getPhoneNumberUnmasked();
        this.extensionNumberUnmasked = builder.getExtensionNumberUnmasked();
        this.countryCodeUnmasked = builder.getCountryCodeUnmasked();
        this.formattedPhoneNumber = builder.getFormattedPhoneNumber();
        this.formattedPhoneNumberUnmasked = builder.getFormattedPhoneNumberUnmasked();
        this.suppressPhone = builder.isSuppressPhone();
        this.defaultValue = builder.isDefaultValue();
        this.versionNumber = builder.getVersionNumber();
        this.objectId = builder.getObjectId();
        this.active = builder.isActive();
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public String getEntityId() {
        return this.entityId;
    }

    @Override
    public String getEntityTypeCode() {
        return this.entityTypeCode;
    }

    @Override
    public CodedAttribute getPhoneType() {
        return this.phoneType;
    }

    @Override
    public String getPhoneNumber() {
        return this.phoneNumber;
    }

    @Override
    public String getExtensionNumber() {
        return this.extensionNumber;
    }

    @Override
    public String getCountryCode() {
        return this.countryCode;
    }

    @Override
    public String getPhoneNumberUnmasked() {
        return this.phoneNumberUnmasked;
    }

    @Override
    public String getExtensionNumberUnmasked() {
        return this.extensionNumberUnmasked;
    }

    @Override
    public String getCountryCodeUnmasked() {
        return this.countryCodeUnmasked;
    }

    @Override
    public String getFormattedPhoneNumber() {
        return this.formattedPhoneNumber;
    }

    @Override
    public String getFormattedPhoneNumberUnmasked() {
        return this.formattedPhoneNumberUnmasked;
    }

    @Override
    public boolean isSuppressPhone() {
        return this.suppressPhone;
    }

    @Override
    public boolean isDefaultValue() {
        return this.defaultValue;
    }

    @Override
    public Long getVersionNumber() {
        return this.versionNumber;
    }

    @Override
    public String getObjectId() {
        return this.objectId;
    }

    @Override
    public boolean isActive() {
        return this.active;
    }

    /**
     * A builder which can be used to construct {@link EntityPhone} instances.  Enforces the constraints of the {@link EntityPhoneContract}.
     *
     */
    public final static class Builder
        implements Serializable, ModelBuilder, EntityPhoneContract
    {

        private String id;
        private String entityId;
        private String entityTypeCode;
        private CodedAttribute.Builder phoneType;
        //private String phoneNumber;
        //private String extensionNumber;
        //private String countryCode;
        private String phoneNumberUnmasked;
        private String extensionNumberUnmasked;
        private String countryCodeUnmasked;
        //private String formattedPhoneNumber;
        //private String formattedPhoneNumberUnmasked;
        private boolean suppressPhone;
        private boolean defaultValue;
        private Long versionNumber;
        private String objectId;
        private boolean active;

        private Builder() {

        }

        public static Builder create() {
            return new Builder();
        }

        public static Builder create(EntityPhoneContract contract) {
            if (contract == null) {
                throw new IllegalArgumentException("contract was null");
            }
            Builder builder = create();
            builder.setId(contract.getId());
            builder.setEntityId(contract.getEntityId());
            builder.setEntityTypeCode(contract.getEntityTypeCode());
            builder.setSuppressPhone(contract.isSuppressPhone());
            if (contract.getPhoneType() != null) {
                builder.setPhoneType(CodedAttribute.Builder.create(contract.getPhoneType()));
            }
            builder.setPhoneNumber(contract.getPhoneNumberUnmasked());
            builder.setExtensionNumber(contract.getExtensionNumberUnmasked());
            builder.setCountryCode(contract.getCountryCodeUnmasked());
            builder.setDefaultValue(contract.isDefaultValue());
            builder.setVersionNumber(contract.getVersionNumber());
            builder.setObjectId(contract.getObjectId());
            builder.setActive(contract.isActive());
            return builder;
        }

        public EntityPhone build() {
            return new EntityPhone(this);
        }

        @Override
        public String getId() {
            return this.id;
        }

        @Override
        public String getEntityTypeCode() {
            return this.entityTypeCode;
        }

        @Override
        public String getEntityId() {
            return this.entityId;
        }

        @Override
        public CodedAttribute.Builder getPhoneType() {
            return this.phoneType;
        }

        @Override
        public String getPhoneNumber() {
            if (isSuppressPhone()) {
                return KimApiConstants.RestrictedMasks.RESTRICTED_DATA_MASK_PHONE;
            }
            return this.phoneNumberUnmasked;
        }

        @Override
        public String getExtensionNumber() {
            if (isSuppressPhone()) {
                return KimApiConstants.RestrictedMasks.RESTRICTED_DATA_MASK;
            }
            return this.extensionNumberUnmasked;
        }

        @Override
        public String getCountryCode() {
            if (isSuppressPhone()) {
                return KimApiConstants.RestrictedMasks.RESTRICTED_DATA_MASK_CODE;
            }
            return this.countryCodeUnmasked;
        }

        @Override
        public String getPhoneNumberUnmasked() {
            return this.phoneNumberUnmasked;
        }

        @Override
        public String getExtensionNumberUnmasked() {
            return this.extensionNumberUnmasked;
        }

        @Override
        public String getCountryCodeUnmasked() {
            return this.countryCodeUnmasked;
        }

        @Override
        public String getFormattedPhoneNumber() {
            if (isSuppressPhone()) {
                return KimApiConstants.RestrictedMasks.RESTRICTED_DATA_MASK;
            }
            return this.getFormattedPhoneNumberUnmasked();
        }

        @Override
        public String getFormattedPhoneNumberUnmasked() {
            StringBuffer sb = new StringBuffer( 30 );

            // TODO: get extension from country code table
            // TODO: append "+xxx" if country is not the default country
            sb.append( this.phoneNumberUnmasked );
            if ( StringUtils.isNotBlank( this.extensionNumberUnmasked) ) {
                sb.append( " x" );
                sb.append( this.extensionNumberUnmasked );
            }

            return sb.toString();
        }

        @Override
        public boolean isSuppressPhone() {
            return this.suppressPhone;
        }

        @Override
        public boolean isDefaultValue() {
            return this.defaultValue;
        }

        @Override
        public Long getVersionNumber() {
            return this.versionNumber;
        }

        @Override
        public String getObjectId() {
            return this.objectId;
        }

        @Override
        public boolean isActive() {
            return this.active;
        }

        public void setId(String id) {
            if (StringUtils.isWhitespace(id)) {
                throw new IllegalArgumentException("id is blank");
            }
            this.id = id;
        }

        public void setEntityTypeCode(String entityTypeCode) {
            this.entityTypeCode = entityTypeCode;
        }

        public void setEntityId(String entityId) {
            this.entityId = entityId;
        }

        public void setPhoneType(CodedAttribute.Builder phoneType) {
            this.phoneType = phoneType;
        }

        public void setPhoneNumber(String phoneNumber) {
            this.phoneNumberUnmasked = phoneNumber;
        }

        public void setExtensionNumber(String extensionNumber) {
            this.extensionNumberUnmasked = extensionNumber;
        }

        public void setCountryCode(String countryCode) {
            this.countryCodeUnmasked = countryCode;
        }

        private void setSuppressPhone(boolean suppressPhone) {
            this.suppressPhone = suppressPhone;
        }

        public void setDefaultValue(boolean defaultValue) {
            this.defaultValue = defaultValue;
        }

        public void setVersionNumber(Long versionNumber) {
            this.versionNumber = versionNumber;
        }

        public void setObjectId(String objectId) {
            this.objectId = objectId;
        }

        public void setActive(boolean active) {
            this.active = active;
        }

    }

    /**
     * Defines some internal constants used on this class.
     *
     */
    static class Constants {

        final static String ROOT_ELEMENT_NAME = "entityPhone";
        final static String TYPE_NAME = "EntityPhoneType";
    }

    /**
     * A private class which exposes constants which define the XML element names to use when this object is marshalled to XML.
     *
     */
    static class Elements {

        final static String ID = "id";
        final static String ENTITY_TYPE_CODE = "entityTypeCode";
        final static String ENTITY_ID = "entityId";
        final static String PHONE_TYPE = "phoneType";
        final static String PHONE_NUMBER = "phoneNumber";
        final static String EXTENSION_NUMBER = "extensionNumber";
        final static String COUNTRY_CODE = "countryCode";
        final static String PHONE_NUMBER_UNMASKED = "phoneNumberUnmasked";
        final static String EXTENSION_NUMBER_UNMASKED = "extensionNumberUnmasked";
        final static String COUNTRY_CODE_UNMASKED = "countryCodeUnmasked";
        final static String FORMATTED_PHONE_NUMBER = "formattedPhoneNumber";
        final static String FORMATTED_PHONE_NUMBER_UNMASKED = "formattedPhoneNumberUnmasked";
        final static String SUPPRESS_PHONE = "suppressPhone";
        final static String DEFAULT_VALUE = "defaultValue";
        final static String ACTIVE = "active";

    }

}


text:
<?php

class RouterTest extends PHPUnit_Framework_TestCase
{
    private $router;

    public static function tearDownAfterClass() {
        $dir = __DIR__."/tests_tmp";
        if(!is_dir($dir)) {
            return;
        }

        foreach(glob($dir."/*") as $file) {
            unlink($file);
        }

        rmdir($dir);
    }

    public function setUp() {
        $storage = new \FabysCore\Component\Cache\Storage\FileStorage(__DIR__."/tests_tmp");
        $cache = new \FabysCore\Component\Cache\Cache($storage);
        $this->router = new \FabysCore\Kernel\Router($cache);
    }

    public function testAddRouteSimple() {
        $this->router->addRoute(["get"], "/testroute", ["TestController", "indexAction"]);
        $this->assertEquals(["get" => ["/testroute" => ["action" => ["TestController", "indexAction"], "before" => [], "after" => []]]], $this->router->getRoutes());

        $this->router->addRoute(["get", "post"], "/route", ["TestController", "postAction"], [["Service", "Method"]]);
        $this->assertEquals(["get" => ["/testroute" => ["action" => ["TestController", "indexAction"], "before" => [], "after" => []], "/route" => ["action" => ["TestController", "postAction"], "before" => [["Service", "Method"]], "after" => []],], "post" => ["/route" => ["action" => ["TestController", "postAction"], "before" => [["Service", "Method"]], "after" => []],]], $this->router->getRoutes());
    }

    public function testAddRouteDynamic() {
        $this->router->addRoute(["get"], "/route/{name}", ["TestController", "nameAction"]);

        $this->assertEquals(["get" => ["?" => [0 => ["regex" => '\/route\/([a-zA-Z-_0-9.]+)', "arguments" => ["{name}"], "action" => ["TestController", "nameAction"], "before" => [], "after" => []]]]], $this->router->getRoutes());

        $this->router->addRoute(["get"], "/route/{name}/test/{param}/name/", ["TestController", "nameParamAction"], [["Service", "Method"], ["Service2", "Method2"]]);

        $this->assertEquals(["get" => ["?" => [0 => ["regex" => '\/route\/([a-zA-Z-_0-9.]+)', "arguments" => ["{name}"], "action" => ["TestController", "nameAction"], "before" => [], "after" => []], 1 => ["regex" => '\/route\/([a-zA-Z-_0-9.]+)\/test\/([a-zA-Z-_0-9.]+)\/name\/', "arguments" => ["{name}", "{param}"], "action" => ["TestController", "nameParamAction"], "before" => [["Service", "Method"], ["Service2", "Method2"]], "after" => []]]]], $this->router->getRoutes());
    }

    public function testLoadRouteNotFound() {
        $this->setExpectedException('FabysCore\Kernel\Exception\RouteNotFoundException');
        $this->router->loadRoute("/notfound");
    }

    public function testLoadRouteError() {
        $this->setExpectedException('FabysCore\Kernel\Exception\RouteNotFoundException');

        $this->router->addRoute(["get", "post"], "/route", ["TestController", "postAction"], [["Service", "Method"]]);
        $this->router->addRoute(["get", "post"], "/route/{name}", ["TestController", "nameAction"]);
        $this->router->addRoute(["get", "post"], "/route/{name}/test/{param}/name/", ["TestController", "nameParamAction"], [["Service", "Method"], ["Service2", "Method2"]]);

        $this->router->loadRoute("/*2<\\$/-\"5 ");
    }

    public function testLoadRouteNotFoundError() {
        $this->setExpectedException('FabysCore\Kernel\Exception\RouteNotFoundException');

        $this->router->addRoute(["get", "post"], "/route", ["TestController", "postAction"], [["Service", "Method"]]);
        $this->router->addRoute(["get", "post"], "/route/{name}", ["TestController", "nameAction"]);
        $this->router->addRoute(["get", "post"], "/route/{name}/test/{param}/name/", ["TestController", "nameParamAction"], [["Service", "Method"], ["Service2", "Method2"]]);

        $this->router->loadRoute("/notfound");
    }

    public function testLoadRouteNotFoundMethod() {
        $this->setExpectedException('FabysCore\Kernel\Exception\RouteNotFoundException');

        $this->router->addRoute(["get"], "/route", ["TestController", "postAction"], [["Service", "Method"]]);
        $this->router->addRoute(["get", "post"], "/route/{name}/test/{param}/name/", ["TestController", "nameParamAction"], [["Service", "Method"], ["Service2", "Method2"]]);

        $this->router->loadRoute("/route", "post");
    }

    public function testLoadRoute() {
        $this->router->addRoute(["get"], "/testroute", ["TestController", "nameAction"]);
        $this->router->addRoute(["get", "post"], "/route", ["TestController", "postAction"], [["Service", "Method"]]);
        $this->router->addRoute(["get", "post"], "/route/{name}", ["TestController", "postAction"], [["Service", "Method"]]);
        $this->router->addRoute(["post"], "/route/{name}/test/{param}/name/", ["TestController", "nameParamAction"], [["Service", "Method"], ["Service2", "Method2"]]);

        $route = $this->router->loadRoute("/testroute");
        $this->assertEquals(["TestController", "nameAction"], $route["action"]);
        $this->assertEmpty($route["before"]);
        $this->assertArrayHasKey("parsedArguments", $route);

        $route = $this->router->loadRoute("/route", "post");
        $this->assertEquals(["TestController", "postAction"], $route["action"]);
        $this->assertEquals([["Service", "Method"]], $route["before"]);
        $this->assertArrayHasKey("parsedArguments", $route);

        $route = $this->router->loadRoute("/route/core/test/attr/name/", "post");
        $this->assertEquals(["TestController", "nameParamAction"], $route["action"]);
        $this->assertEquals([["Service", "Method"], ["Service2", "Method2"]], $route["before"]);
        $this->assertEquals(["name" => "core", "param" => "attr"], $route["parsedArguments"]);

        $route = $this->router->loadRoute("/route/core", "post");
        $this->assertEquals(["TestController", "postAction"], $route["action"]);
        $this->assertEquals([["Service", "Method"]], $route["before"]);
        $this->assertEquals(["name" => "core"], $route["parsedArguments"]);
    }

    public function testCache() {
        $this->assertFalse($this->router->loadFromCache());

        $this->router->addRoute(["get"], "/testroute", ["TestController", "indexAction"]);

        $this->router->saveToCache();
        $this->assertFileExists(__DIR__."/tests_tmp/routes");

        $this->assertTrue($this->router->loadFromCache());
        $this->assertEquals(["get" => ["/testroute" => ["action" => ["TestController", "indexAction"], "before" => [], "after" => []]]], $this->router->getRoutes());
    }

    public function testReset() {
        $this->router->addRoute(["get"], "/testroute", ["TestController", "indexAction"]);
        $this->assertNotEmpty($this->router->getRoutes());

        $this->router->reset();
        $this->assertEmpty($this->router->getRoutes());
    }
}

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

module Serials.Route.App where

import Control.Applicative
import Control.Monad.Reader
import Control.Monad.Except
import Control.Monad.Trans.Either
import Control.Monad.IO.Class (liftIO)

import Data.Pool (Pool)
import Data.Monoid
import Data.Text (Text, unpack)
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.Text.Lazy.Encoding as TLE
import qualified Data.Text.Lazy as TL
import qualified Database.RethinkDB as RethinkDB
import Database.RethinkDB (RethinkDBHandle)

import Serials.Types

import Servant hiding (Get, Post, Put, Delete, ReqBody)
import qualified Servant

-- if you use (Maybe a) with liftIO it will return null instead of a 404
-- this is intentional for some routes

-- we only read / write JSON
type Get    a  = Servant.Get     '[JSON] a
type Post   a  = Servant.Post    '[JSON] a
type Put    a  = Servant.Put     '[JSON] a
type Delete a  = Servant.Delete  '[JSON] a
type ReqBody a = Servant.ReqBody '[JSON] a

---------------------------------------------------------------------

checkNotFound :: App (Maybe a) -> App a
checkNotFound action = do
    res <- action
    case res of
      Nothing -> throwError $ err404
      Just v  -> return v

-- map to a generic error
checkError :: Show e => App (Either e a) -> App a
checkError action = do
    res <- action
    case res of
      Left e -> throwError $ err500 { errBody = BL.pack $ show e }
      Right v -> return v

checkErrorText :: ServantErr -> App (Either Text a) -> App a
checkErrorText err action = do
    res <- action
    case res of
      Left e -> throwError $ err { errBody = TLE.encodeUtf8 $ TL.fromStrict e }
      Right v -> return v

-- what if it could return an invalid error OR an application error?
-- well, it already handles fail, just have it throw if needed
-- it might be nice to map other types, like .... using ExceptT for invalid stuff

----------------------------------------------------------------

--type TestAPI =
         --"a" :> Get String
    -- :<|> "b" :> Get String
    -- :<|> "c" :> Get String

--testServer' :: AppConfig -> Server TestAPI
--testServer' config = enter (Nat $ (runAppT config)) testServerT

---- wow, it's IN My monad here! that's swell
--testServerT ::ServerT TestAPI App
--testServerT = getA :<|> getB :<|> getC
  --where

    --getA :: App String
    --getA = giveMeAMessage
    ---- you can also lift IO functions
    ----getA = liftIO $ woot

    ---- I can map app functions that return Maybes and Eithers to
    ---- app exceptions using little functions like this
    --getB :: App String
    --getB = isNotFound $ testWoot

    --getC :: App String
    --getC = isError $ testErr

--giveMeAMessage :: App String
--giveMeAMessage = do
    --one <- asks appName
    --two <- return "asdf"
    ----throwError $ Invalid "Goooo"
    --return $ show one <> two

--testWoot :: App (Maybe String)
--testWoot = return $ Nothing

--testErr :: App (Either String String)
--testErr = return $ Left "Oh no!"

----getProgName' :: MonadIO m => m String
----getProgName' = liftIO $ getProgName

--woot :: IO String
--woot = return "hello"

-- ToStatus ------------------------------------------------------

--class ToStatus a where
  --toStatus :: a val -> Either ServantErr val

--instance ToStatus Maybe where
  --toStatus Nothing  = Left $ err404
  --toStatus (Just v) = Right v

--instance Show a => ToStatus (Either a) where
  --toStatus (Left e) = Left $ err500 { errBody = "Server Error: " <> BL.pack (show e) }
  --toStatus (Right v) = Right v

--liftE :: ToStatus a => IO (a v) -> EitherT ServantErr IO v
--liftE action = EitherT $ toStatus <$> action

--errUnauthorized :: Text -> ServantErr
--errUnauthorized err = err401 { errReasonPhrase = unpack err }

--errText :: ServantErr -> Text -> ServantErr
--errText err txt = err { errBody = TLE.encodeUtf8 $ TL.fromStrict txt }

--liftErr :: (err -> ServantErr) -> IO (Either err res) -> EitherT ServantErr IO res
--liftErr toErr action = do
    --eres <- liftIO action
    --case eres of
      --Left err -> left (toErr err)
      --Right res -> return res

--liftErrText :: ServantErr -> IO (Either Text res) -> EitherT ServantErr IO res
--liftErrText err = liftErr (errText err)

--liftDb :: Pool RethinkDBHandle -> RethinkIO a -> Handler a
--liftDb h a = liftIO $ runReaderT a h


text:
Ubiquo::Engine.routes.draw do
  match "" => "home#index", :via => :get, :as => :home
  resources :ubiquo_settings
end


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tipkovne bližnjice</title>
<link rel="stylesheet" type="text/css" href="../vodnik_1404.css">
<link rel="stylesheet" type="text/css" href="../vodnik_1404.css">

Ubuntu Slovenija | Uradna spletna stran slovenske skupnosti Linux distribucije Ubuntu

Novice

Forum

Kaj je Ubuntu?

Pogosta vprašanja

Skupnost

Povezave

					</script>

Ubuntu Dokumentacija » Ubuntu 11.04 » Namizni vodnik Ubuntu » Namigi in triki »

Ubuntu Dokumentacija » Ubuntu 11.04 » Namizni vodnik Ubuntu » Pregled »

Tipkovne bližnjice

Uporaba Pregledne plošče in Zaganjalnika

Pritisnite na tipko Meta

Odpre Pregledno ploščo. Pritisnite še enkrat za zaprtje.

Pregledna plošča se odpre z žariščem na iskalnim poljem za iskanje programov in datotek. Uporaba smernih tipk bo krmarila med rezultati. Za zagon uporabite Enter.

Držite tipko Meta

Pokaže zaganjalnik.

Meta+1

Zažene prvi predmet zaganjalnika ali preklopi nanj, če že teče. V primeru da pritisnete tudi Shift odpre novo okno.

Meta+2

Zažene drug predmet zaganjalnika ali preklopi nanj, če se že izvaja. Vzorec se nadaljuje do Meta+0, ki odpre deseti predmet.

Alt+F1

Odpre zaganjalnik. Uporabite smerne tipke za krmarjenje in Enter za zagon stikala ali programa.

Alt+F2

Odpre Pregledno ploščo v posebnem načinu za zagon vnesenih ukazov. Pritisnite Enter za poganjanje trenutnega ukaza. Za izbiro drugačnega ukaza lahko uporabite smerne tipke in za zagon pritisnite Enter.

Meta+A

Odpre lečo Programi.

Meta+F

Odpre Lečo datoteke in mape.

Meta+T

Odpre Smeti.

Ctrl+Alt+T

Odpre Terminal.

Alt

Prikaže Meni programov Pritisnite Alt+F za odprtje menija Datoteka.

F10

Odpre meni. Uporabite smerne tipke za krmarjenje. Dostopate lahko tudi do menijev kazalnikov.

Spoznavanje namizja

Alt+F4

Zapre trenutno okno.

Alt+F10

Razpne trenutno okno. V primeru da je okno že razpeto, ga pomanjša.

Alt+Tabulator

Hiter preklop med okni. Držite Shift za obratni vrstni red.

Meta+D

Skrije vsa okna in pokaže namizje. Za obnovitev svojih oken ponovno pritisnite tipki.

Meta+S

Omogoči preklopnik delovnih površin. Oddalji se od vseh delovnih površin.

Meta+W

Omogoči način "Galerija". Prikaže vsa okna z vseh delovnih površin.

Shift+Alt+↑

Omogoči način "Galerija". Prikaže vsa okna s trenutne delovne površine.

Ctrl+Alt+Tipke puščic

Preklop med delovnimi površinami.

Ctrl+Alt+Shift+Tipke puščic

Premakne trenutno okno na drugo delovno površino.

Ctrl+Alt+L

Zaklene zaslon.

Pogoste bližnjice urejanje

Ctrl+A

Izbere vse besedilo ali predmete na seznamu.

Ctrl+X

Izreže (odstrani) izbrano besedilo ali predmete in jih postavi na odložišče.

Ctrl+C

Kopira izbrano besedilo ali predmete na odložišče.

Ctrl+V

Prilepi vsebino odložišča.

Ctrl+Z

Razveljavi zadnje dejanje.

Zajame zaslon

Shrani zaslonski posnetek

Zajeme zaslonsko sliko.

Alt+Shrani zaslonski posnetek

Zajem zaslonske slike dejavnega okna.

Več podrobnosti

Namigi in triki — Posebni znaki, bližnjice s srednjim klikom ...

Pregled namizja — Pregled različnih delov namizja.

Pogjejte tudi

Kaj je tipka "meta"? — Tipka meta zagotavlja dostop do pregledne plošče in zaganjalnika. Običajno jo lahko na tipkovnici najdete poleg tipke Alt.

Material v tem dokumentu je na voljo pod prosto licenco. To je prevod dokumentacije Ubuntu, ki jo je sestavila Ubuntu dokumentacijska ekpa za Ubuntu. V slovenščino jo je prevedla skupina Ubuntu prevajalcev. Za poročanje napak v prevodih v tej dokumentaciji ali Ubuntuju pošljite sporočilo na dopisni seznam.


text:
package com.mentos1386.evegator;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mentos1386.evegator.Controllers.AuthController;
import com.mentos1386.evegator.Interfaces.EndpointInterface;
import com.mentos1386.evegator.Models.AuthObject;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.Request;
import org.asynchttpclient.RequestBuilder;

public class Endpoint implements EndpointInterface {

    private final String base = "https://crest-tq.eveonline.com/";
    private AuthObject AuthObject;
    private String uri;
    private boolean auth = true;

    public Endpoint(String uri) {

        this.AuthObject = AuthController.getAuth();
        this.uri = uri;
    }

    public Endpoint(String uri, boolean auth) {
        this.AuthObject = AuthController.getAuth();
        this.uri = uri;
        this.auth = auth;
    }

    private RequestBuilder request(String method) {

        if (this.auth) {
            // Create request builder with necessary headers
            RequestBuilder builder = new RequestBuilder(method);
            return builder.setUrl(this.base + this.uri)
                    .addHeader("Authorization", "Bearer " + this.AuthObject.ACCESS_TOKEN)
                    .addHeader("User-Agent", "EveGator");
        } else {
            // Create request builder with necessary headers
            RequestBuilder builder = new RequestBuilder(method);
            return builder.setUrl(this.base + this.uri)
                    .addHeader("User-Agent", "EveGator");
        }
    }

    /*
     * Request Executioner
     */
    private JsonObject execute(Request request) {
        AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
        String response = "";

        // Try to make request
        try {
            response = asyncHttpClient.executeRequest(request).get().getResponseBody();
            asyncHttpClient.close();
        } catch (Exception e) {
            new ExceptionHandler(e);
        }

        JsonElement jsonResponse = new JsonParser().parse(response);

        // Return as JsonObject
        if(jsonResponse != null && response != null && !response.isEmpty())
        {
            return jsonResponse.getAsJsonObject();
        } else {
            return new JsonObject();
        }
    }

    /*
    * GET Request
    */
    @Override
    public JsonObject get() {

        // Create request
        Request request = this.request("GET").build();

        // Return response
        return this.execute(request);
    }

    /*
    * POST Request
    */
    public JsonObject post(String body) {

        // Create request
        Request request = this.request("POST")
                .setBody(body)
                .build();

        // Return response
        return this.execute(request);
    }

    @Override
    public void delete() {

    }
}


text:
package org.apache.spark.deploy.client

import java.util.concurrent.ConcurrentLinkedQueue

import scala.concurrent.duration._

import org.scalatest.BeforeAndAfterAll
import org.scalatest.concurrent.{Eventually, ScalaFutures}

import org.apache.spark._
import org.apache.spark.deploy.{ApplicationDescription, Command}
import org.apache.spark.deploy.DeployMessages.{MasterStateResponse, RequestMasterState}
import org.apache.spark.deploy.master.{ApplicationInfo, Master}
import org.apache.spark.deploy.worker.Worker
import org.apache.spark.internal.Logging
import org.apache.spark.rpc.RpcEnv
import org.apache.spark.util.Utils

/**
 * End-to-end tests for application client in standalone mode.
 */
class AppClientSuite
    extends SparkFunSuite
    with LocalSparkContext
    with BeforeAndAfterAll
    with Eventually
    with ScalaFutures {
  private val numWorkers = 2
  private val conf = new SparkConf()
  private val securityManager = new SecurityManager(conf)

  private var masterRpcEnv: RpcEnv = null
  private var workerRpcEnvs: Seq[RpcEnv] = null
  private var master: Master = null
  private var workers: Seq[Worker] = null

  /**
   * Start the local cluster.
   * Note: local-cluster mode is insufficient because we want a reference to the Master.
   */
  override def beforeAll(): Unit = {
    super.beforeAll()
    masterRpcEnv = RpcEnv.create(Master.SYSTEM_NAME, "localhost", 0, conf, securityManager)
    workerRpcEnvs = (0 until numWorkers).map { i =>
      RpcEnv.create(Worker.SYSTEM_NAME + i, "localhost", 0, conf, securityManager)
    }
    master = makeMaster()
    workers = makeWorkers(10, 2048)
    // Wait until all workers register with master successfully
    eventually(timeout(60.seconds), interval(10.millis)) {
      assert(getMasterState.workers.size === numWorkers)
    }
  }

  override def afterAll(): Unit = {
    try {
      workerRpcEnvs.foreach(_.shutdown())
      masterRpcEnv.shutdown()
      workers.foreach(_.stop())
      master.stop()
      workerRpcEnvs = null
      masterRpcEnv = null
      workers = null
      master = null
    } finally {
      super.afterAll()
    }
  }

  test("interface methods of AppClient using local Master") {
    val ci = new AppClientInst(masterRpcEnv.address.toSparkURL)

    ci.client.start()

    // Client should connect with one Master which registers the application
    eventually(timeout(10.seconds), interval(10.millis)) {
      val apps = getApplications()
      assert(ci.listener.connectedIdList.size === 1, "client listener should have one connection")
      assert(apps.size === 1, "master should have 1 registered app")
    }

    // Send message to Master to request Executors, verify request by change in executor limit
    val numExecutorsRequested = 1
    whenReady(
        ci.client.requestTotalExecutors(numExecutorsRequested),
        timeout(10.seconds),
        interval(10.millis)) { acknowledged =>
      assert(acknowledged)
    }

    eventually(timeout(10.seconds), interval(10.millis)) {
      val apps = getApplications()
      assert(apps.head.getExecutorLimit === numExecutorsRequested, s"executor request failed")
    }

    // Send request to kill executor, verify request was made
    val executorId: String = getApplications().head.executors.head._2.fullId
    whenReady(
        ci.client.killExecutors(Seq(executorId)),
        timeout(10.seconds),
        interval(10.millis)) { acknowledged =>
      assert(acknowledged)
    }

    // Issue stop command for Client to disconnect from Master
    ci.client.stop()

    // Verify Client is marked dead and unregistered from Master
    eventually(timeout(10.seconds), interval(10.millis)) {
      val apps = getApplications()
      assert(ci.listener.deadReasonList.size === 1, "client should have been marked dead")
      assert(apps.isEmpty, "master should have 0 registered apps")
    }
  }

  test("request from AppClient before initialized with master") {
    val ci = new AppClientInst(masterRpcEnv.address.toSparkURL)

    // requests to master should fail immediately
    whenReady(ci.client.requestTotalExecutors(3), timeout(1.seconds)) { success =>
      assert(success === false)
    }
  }

  // ===============================
  // | Utility methods for testing |
  // ===============================

  /** Return a SparkConf for applications that want to talk to our Master. */
  private def appConf: SparkConf = {
    new SparkConf()
      .setMaster(masterRpcEnv.address.toSparkURL)
      .setAppName("test")
      .set("spark.executor.memory", "256m")
  }

  /** Make a master to which our application will send executor requests. */
  private def makeMaster(): Master = {
    val master = new Master(masterRpcEnv, masterRpcEnv.address, 0, securityManager, conf)
    masterRpcEnv.setupEndpoint(Master.ENDPOINT_NAME, master)
    master
  }

  /** Make a few workers that talk to our master. */
  private def makeWorkers(cores: Int, memory: Int): Seq[Worker] = {
    (0 until numWorkers).map { i =>
      val rpcEnv = workerRpcEnvs(i)
      val worker = new Worker(rpcEnv, 0, cores, memory, Array(masterRpcEnv.address),
        Worker.ENDPOINT_NAME, null, conf, securityManager)
      rpcEnv.setupEndpoint(Worker.ENDPOINT_NAME, worker)
      worker
    }
  }

  /** Get the Master state */
  private def getMasterState: MasterStateResponse = {
    master.self.askSync[MasterStateResponse](RequestMasterState)
  }

  /** Get the applications that are active from Master */
  private def getApplications(): Seq[ApplicationInfo] = {
    getMasterState.activeApps
  }

  /** Application Listener to collect events */
  private class AppClientCollector extends StandaloneAppClientListener with Logging {
    val connectedIdList = new ConcurrentLinkedQueue[String]()
    @volatile var disconnectedCount: Int = 0
    val deadReasonList = new ConcurrentLinkedQueue[String]()
    val execAddedList = new ConcurrentLinkedQueue[String]()
    val execRemovedList = new ConcurrentLinkedQueue[String]()

    def connected(id: String): Unit = {
      connectedIdList.add(id)
    }

    def disconnected(): Unit = {
      synchronized {
        disconnectedCount += 1
      }
    }

    def dead(reason: String): Unit = {
      deadReasonList.add(reason)
    }

    def executorAdded(
        id: String,
        workerId: String,
        hostPort: String,
        cores: Int,
        memory: Int): Unit = {
      execAddedList.add(id)
    }

    def executorRemoved(
        id: String, message: String, exitStatus: Option[Int], workerLost: Boolean): Unit = {
      execRemovedList.add(id)
    }
  }

  /** Create AppClient and supporting objects */
  private class AppClientInst(masterUrl: String) {
    val rpcEnv = RpcEnv.create("spark", Utils.localHostName(), 0, conf, securityManager)
    private val cmd = new Command(TestExecutor.getClass.getCanonicalName.stripSuffix("$"),
      List(), Map(), Seq(), Seq(), Seq())
    private val desc = new ApplicationDescription("AppClientSuite", Some(1), 512, cmd, "ignored")
    val listener = new AppClientCollector
    val client = new StandaloneAppClient(rpcEnv, Array(masterUrl), desc, listener, new SparkConf)
  }

}


text:
jCarousel - Riding carousels with jQuery
========================================

jCarousel is a jQuery plugin for controlling a list of items in horizontal or
vertical order. It provides a full-featured and flexible toolset for navigating
any HTML based content in a carousel-like fashion.

**Note**: Version 0.3.x and 0.2.x are **not** compatible. Old versions can be
downloaded from the [release page](https://github.com/jsor/jcarousel/releases).

Documentation
-------------

The documentation can be found [here](http://sorgalla.com/jcarousel/docs/).

### Reference

  * [Installation](http://sorgalla.com/jcarousel/docs/reference/installation.html)
  * [Configuration](http://sorgalla.com/jcarousel/docs/reference/configuration.html)
  * [API](http://sorgalla.com/jcarousel/docs/reference/api.html)
  * [Usage](http://sorgalla.com/jcarousel/docs/reference/usage.html)
  * [Events](http://sorgalla.com/jcarousel/docs/reference/events.html)

### Plugins

By default, the jCarousel core only contains the minimum functionality needed to
create carousel widgets. Specialized features are provided through plugins.

jCarousel comes with the following plugins:

  * [Control Plugin](http://sorgalla.com/jcarousel/docs/plugins/control/)
  * [Pagination Plugin](http://sorgalla.com/jcarousel/docs/plugins/pagination/)
  * [Autoscroll Plugin](http://sorgalla.com/jcarousel/docs/plugins/autoscroll/)
  * [ScrollIntoView Plugin](http://sorgalla.com/jcarousel/docs/plugins/scrollintoview/)

#### Third-Party Plugins

* [jcarouselSwipe](https://github.com/snake-345/jcarouselSwipe) - Adds support for user-friendly swipe gestures.
* [jcarouselLazyLoading](https://github.com/snake-345/jcarouselLazyLoading) - Adds lazy loading to jcarousel.
* [jcarouselFade](https://github.com/snake-345/jcarouselFade) - New method for support fade animation to jcarousel.
* [jcarousel-status](https://github.com/fzoccara/jcarousel-status) - Display the status of your carousel.
* [jcarousel-smoothscroll](https://github.com/aduth/jcarousel-smoothscroll) - Animates a jCarousel at a constant pace, regardless of varying item widths.

Download
--------

All ready-to-use files are located in the [`dist/`](dist/) directory.

The [`jquery.jcarousel.js`](dist/jquery.jcarousel.js?raw=1) and
[`jquery.jcarousel.min.js`](dist/jquery.jcarousel.min.js?raw=1) files contain
the core and all plugins concenated together.

All files are also available from [CDNJS](http://cdnjs.com/libraries/jcarousel).

Examples
--------

You can find some example implementations in the [`examples/`](examples/)
directory. You can also browse the [functional tests](test/functional/) to get
an impression of how to setup jCarousel.

Credits
-------

jCarousel is written on top of [jQuery](http://jquery.com) and was originally
inspired by the [Carousel Component](http://billwscott.com/carousel/) by
[Bill Scott](http://looksgoodworkswell.com).

License
-------

Copyright (c) 2006-2016 Jan Sorgalla.
Released under the [MIT](LICENSE?raw=1) license.


text:
Standalone commandline applications for working with Flux and Metamorph scripts

## Quickstart ##

1. Download the latest distribution package from [the metafacture-runner/releases](https://github.com/culturegraph/metafacutre-runner/releases) page. Make sure that you do download a distribution package and _not_ a source code package. The latest distribution package is [metafacture-runner 3.1.1](https://github.com/culturegraph/metafacture-runner/releases/download/metafacture-runner-3.1.1/metafacture-runner-3.1.1-dist.tar.gz).
2. Extract the downloaded archive:
   ```bash
   $ tar xzf metafacture-runner-3.1.1-dist.tar.gz
   ```
   This will create a new directory containing a ready-to-use metafacture distribution.
3. Change into the newly created directory:
   ```bash
   $ cd metafacture-runner-3.1.1
   ```
4. Run one of the example scripts:
   ```bash
   $ ./flux.sh examples/read/marc21/read-marc21.flux
   ```
   This example will print a number of marc21 records on standard out.

The _examples_ folder contains many more examples which provide a good starting point for learning metafacture. If you have any questions please join our [mailing list](http://lists.dnb.de/mailman/listinfo/metafacture) or use our issue-based discussion forum over at [metafacture-documentation](https://github.com/culturegraph/metafacture-documentation).


text:
describe("Collector", function () {

  var collector = require("./collector");

  before(function () {
  });

  it("should invoke callback with a single element array when a filename is provided", function () {
    var callCount = 0

    collector.collect("", "fake_spec.js", function (err, paths) {
      callCount++;
      value(paths).shouldEqual(["fake_spec.js"]);
    });

    value(callCount).shouldEqual(1);

  });

  after(function() {
  });
});


text:
package com.grumoon.glauncher;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;

public class FolderEditText extends EditText {

    private Folder mFolder;

    public FolderEditText(Context context) {
        super(context);
    }

    public FolderEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FolderEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void setFolder(Folder folder) {
        mFolder = folder;
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        // Catch the back button on the soft keyboard so that we can just close the activity
        if (event.getKeyCode() == android.view.KeyEvent.KEYCODE_BACK) {
            mFolder.doneEditingFolderName(true);
        }
        return super.onKeyPreIme(keyCode, event);
    }
}


text:
'use strict';

/**
 * Module dependencies
 */
var path = require('path'),
	mongoose = require('mongoose'),
	Group = mongoose.model('Group'),
	errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

/**
 * Create a group
 */
exports.create = function (req, res) {
	var group = new Group(req.body);
	group.save(function (err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		res.json(group);
	});
};

/**
 * Update a group
 */
exports.update = function (req, res) {
	var group = req.group;
	group.name = req.body.name;
	group.supervisor = req.body.supervisor !== '' ? req.body.supervisor : null;
	group.members = req.body.members;
	group.save(function (err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		res.json(group);
	});
};

/**
 * Show the current group
 */
exports.read = function (req, res) {
	res.json(req.group);
};

/**
 * List of groups
 */
exports.list = function (req, res) {
	var options = {};
	// If not admin or teacher, only select groups supervised by logged user
	if (req.user.roles.indexOf('admin') === -1 && req.user.roles.indexOf('teacher') === -1) {
		options = {supervisor: req.user};
	}
	// Find list of groups
	Group.find(options).exec(function (err, groups) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		res.json(groups);
	});
};

/**
 * Group middleware
 */
exports.groupByID = function (req, res, next, id) {
	if (! mongoose.Types.ObjectId.isValid(id)) {
		return res.status(400).send({
			message: 'Group is invalid.'
		});
	}

	Group.findById(id, 'name supervisor members').populate('supervisor', 'displayName').populate('members', 'firstName lastName').exec(function (err, group) {
		if (err) {
			return next(err);
		}
		if (! group) {
			return res.status(404).send({
				message: 'No group with that identifier has been found.'
			});
		}
	    req.group = group;
		next();
	});
};


text:
{% extends "frame.html" %}

{% block content %}

zScore Privacy Policy

Basically, we can do whatever we want with your data.

You put your data into zScore at your own risk.
In general, we're not unreasonable people, and will try to respect the privacy settings you set in zScore.
On the other hand, we also screw up sometimes, so we make no guarantees; it's possible that we'll accidentally let everyone on the internet see everything you've ever entered.
Similarly, most days we won't use our backend access to get data that we couldn't otherwise, but some days we might be feeling evil, and we definitely reserve the right to abuse our power.
Nobody's asked us if they can buy user sleep data yet, so we don't know what we will do if someone does.
We will also compute and publish aggregate stats if they're interesting.
In general we'll try not to expose individual data in those, but again, we might screw up.

Regarding the NSA and PRISM: whether or not we can, we won't confirm or deny whether we're currently providing user data to any government agencies.
We aren't responsible for any black helicopters, unmanned drones, crazy penguins, or FBI agents that visit right after you go to sleep.
We're working on a mobile app with push notifications to any monsters that may be hiding under your bed.

Regarding passwords and security: our passwords are encrypted using PBKDF2_SHA256, which the cryptographers claim is plenty secure.
If you use the site over HTTP (the default), though, anyone on your Wi-Fi network can probably read your password if they know what they're doing.
If you want the NSA to have to do a bit more work to get your password, use our secure site at https://zscore.mit.edu.
That said, if we're feeling evil, we can impersonate our secure server, so if you use your zScore password on any other sites, expect us to hack your accounts soon.

Our warrant canary: We have not been served with any warrants, National Security Letters, NSA PRISM requests, or requests under sections 213, 214, 216, or 217 of the USA PATRIOT Act.  We also haven't been asked for data by any members of the MIT administration.  If we do get any of those, we will probably leave this message here, because we aim to confuse.

Of course, we will always reserve the right to have a trollish privacy policy, and to change it without notice.

If you're someone who is unhappy with any the above, or whose sleep data is classified information or a trade secret, don't use the site!
The code is open-source, so you can even make your own version with a "better" privacy policy.

{% endblock %}


text:
<?php
/**
 * Grouped product add to cart
 *
 * @author 		WooThemes
 * @package 	WooCommerce/Templates
 * @version     1.6.4
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

global $woocommerce, $product;

// Put grouped products into an array
$grouped_products = array();
$quantites_required = false;

foreach ( $product->get_children() as $child_id ) {
	$child_product = $product->get_child( $child_id );

	if ( ! $child_product->is_sold_individually() && ! $child_product->is_type('external') )
		$quantites_required = true;

	$grouped_products[] = array(
		'product' => $child_product,
		'availability' => $child_product->get_availability()
	);
}
?>

<?php do_action('woocommerce_before_add_to_cart_form'); ?>

<form action="<?php echo esc_url( $product->add_to_cart_url() ); ?>" class="cart" method="post" enctype='multipart/form-data'>

			<?php foreach ( $grouped_products as $child_product ) : ?>

						<?php if ( $child_product['product']->is_type('external') ) : ?>

							<a href="<?php echo esc_url( $child_product['product']->get_product_url() ); ?>" rel="nofollow" class="button alt"><?php echo apply_filters('single_add_to_cart_text', esc_html( $child_product['product']->get_button_text() ), 'external'); ?>

						<?php elseif ( ! $quantites_required ) : ?>

							<a href="<?php echo esc_url( $child_product['product']->add_to_cart_url() ); ?>" rel="nofollow" class="single_add_to_cart_button button alt"><?php echo apply_filters( 'single_add_to_cart_text', __( 'Add to cart', 'woocommerce' ), $child_product['product']->product_type ); ?>

						<?php else : ?>

							<?php woocommerce_quantity_input( array( 'input_name' => 'quantity['.$child_product['product']->id.']', 'input_value' => '0' ) ); ?>

						<?php endif; ?>

					<label for="product-<?php echo $child_product['product']->id; ?>"><?php

						if ($child_product['product']->is_visible())
							echo 'id ) . '">' . $child_product['product']->post->post_title . '';
						else
							echo $child_product['product']->post->post_title;

					?>

					<?php do_action ( 'woocommerce_grouped_product_list_before_price', $child_product['product'] ); ?>

					<?php echo $child_product['product']->get_price_html(); ?>
					<?php echo apply_filters( 'woocommerce_stock_html', ''.$child_product['availability']['availability'].'', $child_product['availability']['availability'] ); ?>

			<?php endforeach; ?>

	<?php if ( $quantites_required ) : ?>

		<?php do_action('woocommerce_before_add_to_cart_button'); ?>

		<button type="submit" class="single_add_to_cart_button btn-system alt"><?php echo apply_filters('single_add_to_cart_text', __( 'Add to cart', 'woocommerce' ), $product->product_type); ?></button>

		<?php do_action('woocommerce_after_add_to_cart_button'); ?>

	<?php endif; ?>

</form>

<?php do_action('woocommerce_after_add_to_cart_form'); ?>


text:
export class ContentResponse<T> implements Response {

    constructor(public readonly baseResponse: Response, public readonly content: T) {    }

    public get body(): ReadableStream | null { return this.baseResponse.body;}

    public get bodyUsed(): boolean { return this.baseResponse.bodyUsed;}

    public get headers(): Headers { return this.baseResponse.headers;}

    public get ok(): boolean { return this.baseResponse.ok;}

    public get redirected(): boolean { return this.baseResponse.redirected;}

    public get status(): number { return this.baseResponse.status;}

    public get statusText(): string { return this.baseResponse.statusText;}

    public get trailer(): Promise<Headers> { return this.baseResponse.trailer;}

    public get type(): ResponseType { return this.baseResponse.type;}

    public get url(): string { return this.baseResponse.url;}

    public arrayBuffer(): Promise<ArrayBuffer> {return this.baseResponse.arrayBuffer(); }

    public blob(): Promise<Blob> { return this.baseResponse.blob(); }

    public clone(): Response {return this.baseResponse.clone(); }

    public formData(): Promise<FormData> {return this.baseResponse.formData(); }

    public json(): Promise<any> {return this.baseResponse.json(); }

    public text(): Promise<string> {return this.baseResponse.text();}
}


text:
from six.moves.urllib.parse import urljoin

import django
if django.VERSION[0] == 1 and django.VERSION[1] == 3:
    from django.conf.urls.defaults import patterns, include
else:
    from django.conf.urls import patterns, include

from django.test import TestCase

from collection_json import Collection
from rest_framework import status
from rest_framework.exceptions import ParseError
from rest_framework.relations import HyperlinkedIdentityField
from rest_framework.response import Response
from rest_framework.routers import DefaultRouter
from rest_framework.serializers import (
    HyperlinkedModelSerializer, ModelSerializer
)
from rest_framework.status import HTTP_204_NO_CONTENT
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet

from rest_framework_cj.renderers import CollectionJsonRenderer
from rest_framework_cj.fields import LinkField

from testapp.models import Dummy, Idiot, Moron, Simple

class MoronHyperlinkedModelSerializer(HyperlinkedModelSerializer):
    class Meta(object):
        model = Moron
        fields = ('url', 'name')

class MoronReadOnlyModelViewSet(ReadOnlyModelViewSet):
    renderer_classes = (CollectionJsonRenderer, )
    queryset = Moron.objects.all()
    serializer_class = MoronHyperlinkedModelSerializer

class IdiotHyperlinkedModelSerializer(HyperlinkedModelSerializer):
    class Meta(object):
        model = Idiot
        fields = ('url', 'name')

class IdiotReadOnlyModelViewSet(ReadOnlyModelViewSet):
    renderer_classes = (CollectionJsonRenderer, )
    queryset = Idiot.objects.all()
    serializer_class = IdiotHyperlinkedModelSerializer

class DummyHyperlinkedModelSerializer(HyperlinkedModelSerializer):
    other_stuff = LinkField('get_other_link')
    empty_link = LinkField('get_empty_link')
    some_link = HyperlinkedIdentityField(view_name='moron-detail')

    class Meta(object):
        model = Dummy
        fields = ('url', 'name', 'moron', 'idiots', 'other_stuff', 'some_link', 'empty_link')

    def get_other_link(self, obj):
        return 'http://other-stuff.com/'

    def get_empty_link(self, obj):
        return None

class DummyReadOnlyModelViewSet(ReadOnlyModelViewSet):
    renderer_classes = (CollectionJsonRenderer, )
    queryset = Dummy.objects.all()
    serializer_class = DummyHyperlinkedModelSerializer

class NoSerializerView(APIView):
    renderer_classes = (CollectionJsonRenderer, )

    def get(self, request):
        return Response({'foo': '1'})

class SimpleGetTest(TestCase):
    urls = 'testapp.tests.test_renderers'
    endpoint = ''

    def setUp(self):
        self.response = self.client.get(self.endpoint)
        self.collection = Collection.from_json(self.response.content.decode('utf8'))

def create_models():
    bob = Moron.objects.create(name='Bob LawLaw')
    dummy = Dummy.objects.create(name='Yolo McSwaggerson', moron=bob)
    dummy.idiots.add(Idiot.objects.create(name='frick'))
    dummy.idiots.add(Idiot.objects.create(name='frack'))

class TestCollectionJsonRenderer(SimpleGetTest):
    endpoint = '/rest-api/dummy/'

    def setUp(self):
        create_models()
        super(TestCollectionJsonRenderer, self).setUp()

    def test_it_has_the_right_response_code(self):
        self.assertEqual(self.response.status_code, status.HTTP_200_OK)

    def test_it_has_the_right_content_type(self):
        content_type = self.response['Content-Type']
        self.assertEqual(content_type, 'application/vnd.collection+json')

    def test_it_has_the_version_number(self):
        self.assertEqual(self.collection.version, '1.0')

    def test_it_has_an_href(self):
        href = self.collection.href
        self.assertEqual(href, 'http://testserver/rest-api/dummy/')

    def get_dummy(self):
        return self.collection.items[0]

    def test_the_dummy_item_has_an_href(self):
        href = self.get_dummy().href
        self.assertEqual(href, 'http://testserver/rest-api/dummy/1/')

    def test_the_dummy_item_contains_name(self):
        name = self.get_dummy().data.find('name')[0].value
        self.assertEqual(name, 'Yolo McSwaggerson')

    def get_dummy_link(self, rel):
        links = self.get_dummy()['links']
        return next(x for x in links if x['rel'] == rel)

    def test_the_dummy_item_links_to_child_elements(self):
        href = self.get_dummy().links.find(rel='moron')[0].href
        self.assertEqual(href, 'http://testserver/rest-api/moron/1/')

    def test_link_fields_are_rendered_as_links(self):
        href = self.get_dummy().links.find(rel='other_stuff')[0].href
        self.assertEqual(href, 'http://other-stuff.com/')

    def test_empty_link_fields_are_not_rendered_as_links(self):
        links = self.get_dummy().links.find(rel='empty_link')
        self.assertEqual(len(links), 0)

    def test_attribute_links_are_rendered_as_links(self):
        href = self.get_dummy().links.find(rel='some_link')[0].href
        self.assertEqual(href, 'http://testserver/rest-api/moron/1/')

    def test_many_to_many_relationships_are_rendered_as_links(self):
        idiots = self.get_dummy().links.find(rel='idiots')
        self.assertEqual(idiots[0].href, 'http://testserver/rest-api/idiot/1/')
        self.assertEqual(idiots[1].href, 'http://testserver/rest-api/idiot/2/')

class TestNoSerializerViews(SimpleGetTest):
    endpoint = '/rest-api/no-serializer/'

    def setUp(self):
        create_models()
        super(TestNoSerializerViews, self).setUp()

    def test_views_without_a_serializer_work(self):
        value = self.collection.items[0].data.find('foo')[0].value
        self.assertEqual(value, '1')

class SimpleModelSerializer(ModelSerializer):

    class Meta(object):
        model = Dummy
        fields = ('name', )

class SimpleViewSet(ReadOnlyModelViewSet):
    renderer_classes = (CollectionJsonRenderer, )
    queryset = Simple.objects.all()
    serializer_class = SimpleModelSerializer

class TestNormalModels(SimpleGetTest):
    endpoint = '/rest-api/normal-model/'

    def setUp(self):
        Simple.objects.create(name='Foobar Baz')
        super(TestNormalModels, self).setUp()

    def test_items_dont_have_a_href(self):
        href_count = len(self.collection.items[0].find(name='href'))
        self.assertEqual(href_count, 0)

class PaginatedDataView(APIView):
    renderer_classes = (CollectionJsonRenderer, )

    def get(self, request):
        return Response({
            'next': 'http://test.com/colleciton/next',
            'previous': 'http://test.com/colleciton/previous',
            'results': [{'foo': 1}],
        })

class TestCollectionJsonRendererPagination(SimpleGetTest):
    endpoint = '/rest-api/paginated/'

    def test_paginated_views_display_data(self):
        foo = self.collection.items[0].find(name='foo')[0]
        self.assertEqual(foo.value, 1)

    def test_paginated_views_display_next(self):
        next_link = self.collection.links.find(rel='next')[0]
        self.assertEqual(next_link.href, 'http://test.com/colleciton/next')

    def test_paginated_views_display_previous(self):
        next_link = self.collection.links.find(rel='previous')[0]
        self.assertEqual(next_link.href, 'http://test.com/colleciton/previous')

class NonePaginatedDataView(APIView):
    renderer_classes = (CollectionJsonRenderer, )

    def get(self, request):
        return Response({
            'next': None,
            'previous': None,
            'results': [{'foo': 1}],
        })

class TestCollectionJsonRendererPaginationWithNone(SimpleGetTest):
    endpoint = '/rest-api/none-paginated/'

    def test_paginated_view_does_not_display_next(self):
        self.assertEqual(len(self.collection.links.find(rel='next')), 0)

    def test_paginated_view_does_not_display_previous(self):
        self.assertEqual(len(self.collection.links.find(rel='previous')), 0)

class ParseErrorView(APIView):
    renderer_classes = (CollectionJsonRenderer, )

    def get(self, request):
        raise ParseError('lol nice one')

class TestErrorHandling(SimpleGetTest):
    endpoint = '/rest-api/parse-error/'

    def test_errors_are_reported(self):
        self.assertEqual(self.collection.error.message, 'lol nice one')

class UrlRewriteRenderer(CollectionJsonRenderer):
    def get_href(self, request):
        return urljoin('http://rewritten.com', request.path)

class UrlRewriteView(APIView):
    renderer_classes = (UrlRewriteRenderer, )

    def get(self, request):
        return Response({'foo': 'bar'})

class TestUrlRewrite(SimpleGetTest):
    endpoint = '/rest-api/url-rewrite/'

    def test_the_href_url_can_be_rewritten(self):
        rewritten_url = "http://rewritten.com/rest-api/url-rewrite/"
        self.assertEqual(self.collection.href, rewritten_url)

class EmptyView(APIView):
    renderer_classes = (CollectionJsonRenderer, )

    def get(self, request):
        return Response(status=HTTP_204_NO_CONTENT)

class TestEmpty(TestCase):
    urls = 'testapp.tests.test_renderers'

    def test_empty_content_works(self):
        response = self.client.get('/rest-api/empty/')
        self.assertEqual(response.status_code, HTTP_204_NO_CONTENT)
        self.assertEqual(response.content.decode('utf8'), '')

router = DefaultRouter()
router.register('dummy', DummyReadOnlyModelViewSet)
router.register('moron', MoronReadOnlyModelViewSet)
router.register('idiot', IdiotReadOnlyModelViewSet)
router.register('normal-model', SimpleViewSet)
urlpatterns = patterns(
    '',
    (r'^rest-api/', include(router.urls)),
    (r'^rest-api/no-serializer/', NoSerializerView.as_view()),
    (r'^rest-api/paginated/', PaginatedDataView.as_view()),
    (r'^rest-api/none-paginated/', NonePaginatedDataView.as_view()),
    (r'^rest-api/parse-error/', ParseErrorView.as_view()),
    (r'^rest-api/url-rewrite/', UrlRewriteView.as_view()),
    (r'^rest-api/empty/', EmptyView.as_view()),
)


text:
namespace app { namespace Android { namespace android { namespace os { struct Parcel; } } } }
namespace app { namespace Android { namespace java { namespace lang { struct String; } } } }

namespace app {
namespace Android {
namespace android {
namespace view {
namespace accessibility {

struct AccessibilityEvent;

extern jclass AccessibilityEvent___javaClass_3;
extern jmethodID AccessibilityEvent__describeContents_20784_ID;
extern jmethodID AccessibilityEvent__toString_20785_ID;
extern jmethodID AccessibilityEvent__writeToParcel_20783_ID;

struct AccessibilityEvent__uType : ::app::Android::java::lang::Object__uType
{
    ::app::Android::android::os::Parcelable __interface_2;
};

AccessibilityEvent__uType* AccessibilityEvent__typeof();

void AccessibilityEvent___Init_3(::uStatic* __this);
int AccessibilityEvent__describeContents(AccessibilityEvent* __this);
int AccessibilityEvent__describeContents_IMPL_20784(::uStatic* __this, bool arg0_, jobject arg1_);
::app::Android::java::lang::String* AccessibilityEvent__toString(AccessibilityEvent* __this);
::uObject* AccessibilityEvent__toString_IMPL_20785(::uStatic* __this, bool arg0_, jobject arg1_);
void AccessibilityEvent__writeToParcel(AccessibilityEvent* __this, ::app::Android::android::os::Parcel* arg0, int arg1);
void AccessibilityEvent__writeToParcel_IMPL_20783(::uStatic* __this, bool arg0_, jobject arg1_, ::uObject* arg2_, int arg3_);

struct AccessibilityEvent : ::app::Android::java::lang::Object
{
    int describeContents() { return AccessibilityEvent__describeContents(this); }
    void writeToParcel(::app::Android::android::os::Parcel* arg0, int arg1) { AccessibilityEvent__writeToParcel(this, arg0, arg1); }
};

}}}}}

#endif


text:
import run from 'ember-metal/run_loop';

module('system/run_loop/run_bind_test');

test('Ember.run.bind builds a run-loop wrapped callback handler', function() {
  expect(3);

  var obj = {
    value: 0,
    increment: function(increment) {
      ok(run.currentRunLoop, 'expected a run-loop');
      return this.value += increment;
    }
  };

  var proxiedFunction = run.bind(obj, obj.increment, 1);
  equal(proxiedFunction(), 1);
  equal(obj.value, 1);
});


text:
package org.ovirt.engine.api.restapi.resource;

import java.util.Collection;

import javax.ws.rs.core.Response;

import org.ovirt.engine.api.model.VM;
import org.ovirt.engine.api.model.VMs;
import org.ovirt.engine.api.resource.StorageDomainContentResource;
import org.ovirt.engine.api.resource.RemovableStorageDomainContentsResource;
import org.ovirt.engine.core.common.action.RemoveVmFromImportExportParamenters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.queries.GetAllFromExportDomainQueryParameters;
import org.ovirt.engine.core.common.queries.StorageDomainQueryTopSizeVmsParameters;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;

public class BackendStorageDomainVmsResource
    extends AbstractBackendStorageDomainContentsResource<VMs, VM, org.ovirt.engine.core.common.businessentities.VM>
    implements RemovableStorageDomainContentsResource<VMs, VM> {

    public BackendStorageDomainVmsResource(Guid storageDomainId) {
        super(storageDomainId, VM.class, org.ovirt.engine.core.common.businessentities.VM.class);
    }

    @Override
    public VMs list() {
        VMs vms = new VMs();
        vms.getVMs().addAll(getCollection());
        return vms;
    }

    @Override
    protected VM addParents(VM vm) {
        vm.setStorageDomain(getStorageDomainModel());
        return vm;
    }

    @Override
    protected Collection<org.ovirt.engine.core.common.businessentities.VM> getEntitiesFromDataDomain() {
        return getBackendCollection(VdcQueryType.GetTopSizeVmsFromStorageDomain,
                                    new StorageDomainQueryTopSizeVmsParameters(storageDomainId, -1));
    }

    @Override
    protected Collection<org.ovirt.engine.core.common.businessentities.VM> getEntitiesFromExportDomain() {
        GetAllFromExportDomainQueryParameters params =
            new GetAllFromExportDomainQueryParameters(getDataCenterId(storageDomainId), storageDomainId);
        params.setGetAll(true);

        return getBackendCollection(VdcQueryType.GetVmsFromExportDomain, params);
    }

    @Override
    @SingleEntityResource
    public StorageDomainContentResource<VM> getStorageDomainContentSubResource(String id) {
        return inject(new BackendStorageDomainVmResource(this, id));
    }

    @Override
    public Response performRemove(String id) {
        org.ovirt.engine.core.common.businessentities.VM vm = new org.ovirt.engine.core.common.businessentities.VM();
        vm.setId(Guid.createGuidFromString(id));
        RemoveVmFromImportExportParamenters params = new RemoveVmFromImportExportParamenters(
                vm,
                storageDomainId,
                getDataCenterId(storageDomainId));
        return performAction(VdcActionType.RemoveVmFromImportExport, params);
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\models\Paymentype */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'type')->textInput() ?>

    <?= $form->field($model, 'description')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'crtdt')->textInput() ?>

    <?= $form->field($model, 'crtby')->textInput() ?>

    <?= $form->field($model, 'upddt')->textInput() ?>

    <?= $form->field($model, 'updby')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
#ifndef IDRAWING_H
#define IDRAWING_H

#include <allegro5/allegro5.h>
#include <allegro5/allegro_image.h>

#include <iostream>
#include "Point.h"
namespace tour {
    class IDrawing
    {
        public:
            IDrawing(Point point, int actions, bool isactive);
            virtual ~IDrawing();

            /*
                Setta _hasFocus para true caso a posição @param (mouse_x, mouse_y)
                esteja em cima da imagem
            */
            virtual void checkOver(Point p) = 0;

            virtual bool checkCollision(tour::IDrawing* d) = 0;

            virtual int getActions() = 0;

            virtual int getWidth() = 0;
            virtual int getHeight() = 0;

            tour::Point getPoint();

            virtual ALLEGRO_BITMAP* getBitmap() = 0;

            virtual void destroy() = 0;

            bool hasFocus();
            bool isActive();
            void setActive(bool isactive);

            virtual void move(Point p) = 0;
            virtual void moveTo(Point p) = 0;

            void addActions(unsigned int acts);
            void removeActions(unsigned int acts);
         protected:
         	tour::Point _point;

         	bool _hasFocus = false;
         	bool _isActive = false;

         	unsigned int _actions = 0;
    };
}
#endif // DRAWING_H


text:
const _get = require("lodash.get"),
  getCacheKey = require("./helpers/getcachekey.js"),
  getCachingStrategy = require("./helpers/getcachingstrategy.js"),
  P = require("bluebird");

const caching = ({ cache, options }) => {
  const isProduction = () => process.env.NODE_ENV === "production";

  const getValue = key => {
    if (_get(options, "callbacks.onAttempt")) {
      options.callbacks.onAttempt(key);
    }
    const cacheGet = P.promisify(cache.get);
    return cacheGet(key)
      .catch(err => {
        if (!isProduction()) {
          console.warn("Error retrieving value from cache: " + err);
        }
        if (_get(options, "callbacks.onError")) {
          options.callbacks.onError(err, key);
        }
      });
  };

  const getTtl = key => {
    if (typeof cache.ttl !== "function") {
      return P.resolve();
    }
    const cacheTtl = P.promisify(cache.ttl);
    return cacheTtl(key)
      .catch(err => {
        if (!isProduction()) {
          console.warn("Error retrieving ttl from cache: " + err);
        }
        if (_get(options, "callbacks.onError")) {
          options.callbacks.onError(err, key);
        }
      });
  };

  const setCacheControlHeader = (res, accessibility, ttl) => {
    if (ttl) {
      if (accessibility) {
        res.set("cache-control", `${accessibility}, max-age=${ttl}`);
      } else {
        res.set("cache-control", `max-age=${ttl}`);
      }
    }
  };

  const handleCacheHit = (res, key, value) => {
    if (!value) {
      return P.resolve(false);
    }

    if (_get(options, "callbacks.onHit")) {
      options.callbacks.onHit(key, value);
    }

    return getTtl(key)
      .then(ttl => setCacheControlHeader(res, value.accessibility, ttl))
      .then(() => {
        // This is dumb, but it results in a prettier JSON format
        try {
          const obj = JSON.parse(value.body);
          res.status(value.statusCode).json(obj);
        } catch (err) {
          res.status(value.statusCode).send(value.body);
        }
      })
      .return(true);
  };

  const handleCacheMiss = (res, key) => {
    if (_get(options, "callbacks.onMiss")) {
      options.callbacks.onMiss(key);
    }
    const send = res.send.bind(res);

    res.send = body => {
      const ret = send(body);

      if (/^2/.test(res.statusCode) || /^304$/.test(res.statusCode)) {
        const cachingStrategy = getCachingStrategy({ response: res });
        if (cachingStrategy) {
          const cacheSet = P.promisify(cache.set);
          const cacheValue = {
            statusCode: res.statusCode,
            body: body,
            accessibility: cachingStrategy.accessibility
          };
          cacheSet(key, cacheValue, { ttl: cachingStrategy.maxAge })
            .catch(err => {
              if (!isProduction()) {
                console.warn("Error setting value in cache: " + err);
              }
              if (_get(options, "callbacks.onError")) {
                options.callbacks.onError(err, key);
              }
            });
        }
      }

      return ret;
    };
  };

  const middleware = (req, res, next) => {
    if (!cache) {
      next();
      return;
    }

    const key = getCacheKey({ request: req, options });
    getValue(key)
      .then(value => handleCacheHit(res, key, value))
      .then(isHit => {
        if (!isHit) {
          handleCacheMiss(res, key);
          next();
        }
      });
  };

  return middleware;
};

module.exports = caching;


text:
// +build linux

package preflight

import (
	"github.com/pkg/errors"
	"k8s.io/kubernetes/cmd/kubeadm/app/util"
	"k8s.io/kubernetes/pkg/proxy/ipvs"
	"k8s.io/utils/exec"

	utilipset "k8s.io/kubernetes/pkg/util/ipset"
)

// Check validates if Docker is setup to use systemd as the cgroup driver.
func (idsc IsDockerSystemdCheck) Check() (warnings, errorList []error) {
	driver, err := util.GetCgroupDriverDocker(exec.New())
	if err != nil {
		return nil, []error{err}
	}
	if driver != util.CgroupDriverSystemd {
		err = errors.Errorf("detected %q as the Docker cgroup driver. "+
			"The recommended driver is %q. "+
			"Please follow the guide at https://kubernetes.io/docs/setup/cri/",
			driver,
			util.CgroupDriverSystemd)
		return []error{err}, nil
	}
	return nil, nil
}

// Check determines if IPVS proxier can be used or not
func (ipvspc IPVSProxierCheck) Check() (warnings, errors []error) {
	ipsetInterface := utilipset.New(ipvspc.exec)
	kernelHandler := ipvs.NewLinuxKernelHandler()
	if _, err := ipvs.CanUseIPVSProxier(kernelHandler, ipsetInterface); err != nil {
		return nil, []error{err}
	}
	return nil, nil
}


text:
package adapter

import (
	"bytes"
	"context"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	cloudevents "github.com/cloudevents/sdk-go/v2"
	"go.uber.org/zap"

	"gopkg.in/go-playground/webhooks.v5/gitlab"

	"knative.dev/eventing-gitlab/pkg/apis/sources/v1alpha1"
	"knative.dev/eventing/pkg/adapter/v2"
	adaptertest "knative.dev/eventing/pkg/adapter/v2/test"
	"knative.dev/pkg/logging"
	pkgtesting "knative.dev/pkg/reconciler/testing"
)

const (
	secretToken = "gitlabsecret"
	projectURL  = "http://gitlab.example.com/myuser/myproject"
)

// testCase holds a single row of our GitLabSource table tests
type testCase struct {
	// name is a descriptive name for this test suitable as a first argument to t.Run()
	name string

	// wantErr is the expected error returned in the server's response
	wantErr error

	// which status code server should return
	statusCode int

	// payload contains the GitLab event payload
	payload interface{}

	// eventType is the GitLab event type
	eventType gitlab.Event
}

var testCases = []testCase{
	{
		name:       "valid comment",
		payload:    gitlab.CommentEventPayload{},
		eventType:  gitlab.CommentEvents,
		statusCode: 202,
	}, {
		name:       "valid issues",
		payload:    gitlab.IssueEventPayload{},
		eventType:  gitlab.IssuesEvents,
		statusCode: 202,
	}, {
		name:       "valid push",
		payload:    gitlab.PushEventPayload{},
		eventType:  gitlab.PushEvents,
		statusCode: 202,
	}, {
		name:       "valid tag event",
		payload:    gitlab.TagEventPayload{},
		eventType:  gitlab.TagEvents,
		statusCode: 202,
	}, {
		name:       "valid confidential issue event",
		payload:    gitlab.ConfidentialIssueEventPayload{},
		eventType:  gitlab.ConfidentialIssuesEvents,
		statusCode: 202,
	}, {
		name:       "valid merge request event",
		payload:    gitlab.MergeRequestEventPayload{},
		eventType:  gitlab.MergeRequestEvents,
		statusCode: 202,
	}, {
		name:       "valid wiki page event",
		payload:    gitlab.WikiPageEventPayload{},
		eventType:  gitlab.WikiPageEvents,
		statusCode: 202,
	}, {
		name:       "valid pipeline event",
		payload:    gitlab.PipelineEventPayload{},
		eventType:  gitlab.PipelineEvents,
		statusCode: 202,
	}, {
		name:       "valid build event",
		payload:    gitlab.BuildEventPayload{},
		eventType:  gitlab.BuildEvents,
		statusCode: 202,
	}, {
		name:       "invalid nil payload",
		payload:    nil,
		eventType:  gitlab.Event("Invalid Hook"),
		wantErr:    gitlab.ErrEventNotFound,
		statusCode: 400,
	}, {
		name:       "invalid empty eventType",
		wantErr:    gitlab.ErrMissingGitLabEventHeader,
		statusCode: 400,
	},
}

func TestGracefulShutdown(t *testing.T) {
	ce := adaptertest.NewTestClient()
	ra := newTestAdapter(t, ce)
	ctx, cancel := context.WithCancel(context.Background())
	done := make(chan struct{})

	go func(ctx context.Context) {
		defer close(done)
		err := ra.Start(ctx)
		if err != nil {
			t.Error("Unexpected error:", err)
		}

	}(ctx)

	cancel()
	<-done
}
func TestServer(t *testing.T) {
	for _, tc := range testCases {
		ce := adaptertest.NewTestClient()
		ra := newTestAdapter(t, ce)
		hook, err := gitlab.New(gitlab.Options.Secret(ra.secretToken))
		if err != nil {
			t.Error(err)
		}
		router := ra.newRouter(hook)
		server := httptest.NewServer(router)
		defer server.Close()

		t.Run(tc.name, tc.runner(t, server.URL, ce))
	}
}

func newTestAdapter(t *testing.T, ce cloudevents.Client) *gitLabReceiveAdapter {
	env := envConfig{
		EnvConfig: adapter.EnvConfig{
			Namespace: "default",
		},
		EnvSecret:   secretToken,
		EventSource: projectURL,
	}
	ctx, _ := pkgtesting.SetupFakeContext(t)
	logger := zap.NewExample().Sugar()
	ctx = logging.WithLogger(ctx, logger)

	return NewAdapter(ctx, &env, ce).(*gitLabReceiveAdapter)
}

// runner returns a testing func that can be passed to t.Run.
func (tc *testCase) runner(t *testing.T, url string, ceClient *adaptertest.TestCloudEventsClient) func(*testing.T) {
	return func(t *testing.T) {
		reqBody, _ := json.Marshal(tc.payload)
		req, err := http.NewRequest("POST", url, bytes.NewReader(reqBody))
		if err != nil {
			t.Error(err)
		}
		req.Header.Set("X-Gitlab-Event", string(tc.eventType))
		req.Header.Set("X-Gitlab-Token", string(secretToken))

		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			t.Error(err)
		}
		defer resp.Body.Close()
		if resp.StatusCode != tc.statusCode {
			t.Errorf("Unexpected status code: %s", resp.Status)
		}

		respBody, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			t.Error(err)
		}

		tc.validateResponse(t, string(respBody))

		tc.validateAcceptedPayload(t, ceClient, tc.statusCode)
	}
}

func (tc *testCase) validateAcceptedPayload(t *testing.T, ce *adaptertest.TestCloudEventsClient, httpCode int) {
	sentEvents := ce.Sent()

	if httpCode/100 != 2 {
		require.Len(t, sentEvents, 0, "Event sent despite the non-success HTTP code")
		return
	}
	require.Len(t, sentEvents, 1, "More than 1 event was sent in reaction to the webhooks's message")

	expectCEType := v1alpha1.GitLabEventType(gitlabEventHeaderToEventType(string(tc.eventType)))
	expectCESource := projectURL
	expectCEExt := string(tc.eventType)
	expectData, err := json.Marshal(tc.payload)
	require.NoError(t, err, "Unable to serialize GitLab payload")

	sentEvent := ce.Sent()[0]

	assert.Equal(t, expectCEType, sentEvent.Type(),
		"CloudEvent type doesn't match the webhook's event header")
	assert.Equal(t, expectCESource, sentEvent.Source(),
		"CloudEvent source doesn't match the project's URL")
	assert.Equal(t, expectCEExt, sentEvent.Extensions()[glHeaderEventCEAttr],
		"CloudEvent extension doesn't match the match the webhook's event header")
	assert.Equal(t, expectData, sentEvent.Data(),
		"CloudEvent data differs from original payload")
}

func (tc *testCase) validateResponse(t *testing.T, body string) {
	if tc.wantErr != nil {
		assert.EqualError(t, tc.wantErr, body)
		return
	}
	assert.Empty(t, body)
}

func TestGitLabEventHeaderToEventType(t *testing.T) {
	testCases := map[string]struct {
		input  string
		expect string
	}{
		"bad format": {
			input:  "Missing The Suffix",
			expect: "",
		},
		"good format": {
			input:  "Legit Event Type Hook",
			expect: "legit_event_type",
		},
	}

	for name, tc := range testCases {
		t.Run(name, func(*testing.T) {
			assert.Equal(t, tc.expect, gitlabEventHeaderToEventType(tc.input))
		})
	}
}


text:
package kafka.server

import java.util.Properties

import org.junit.Assert._
import kafka.api.RequestKeys
import org.apache.kafka.common.metrics.Quota
import org.easymock.{Capture, EasyMock}
import org.junit.Test
import kafka.integration.KafkaServerTestHarness
import kafka.utils._
import kafka.common._
import kafka.log.LogConfig
import kafka.admin.{AdminOperationException, AdminUtils}

import scala.collection.Map

class DynamicConfigChangeTest extends KafkaServerTestHarness {
  def generateConfigs() = List(KafkaConfig.fromProps(TestUtils.createBrokerConfig(0, zkConnect)))

  @Test
  def testConfigChange() {
    assertTrue("Should contain a ConfigHandler for topics",
               this.servers(0).dynamicConfigHandlers.contains(ConfigType.Topic))
    val oldVal: java.lang.Long = 100000L
    val newVal: java.lang.Long = 200000L
    val tp = TopicAndPartition("test", 0)
    val logProps = new Properties()
    logProps.put(LogConfig.FlushMessagesProp, oldVal.toString)
    AdminUtils.createTopic(zkUtils, tp.topic, 1, 1, logProps)
    TestUtils.retry(10000) {
      val logOpt = this.servers(0).logManager.getLog(tp)
      assertTrue(logOpt.isDefined)
      assertEquals(oldVal, logOpt.get.config.flushInterval)
    }
    logProps.put(LogConfig.FlushMessagesProp, newVal.toString)
    AdminUtils.changeTopicConfig(zkUtils, tp.topic, logProps)
    TestUtils.retry(10000) {
      assertEquals(newVal, this.servers(0).logManager.getLog(tp).get.config.flushInterval)
    }
  }

  @Test
  def testClientQuotaConfigChange() {
    assertTrue("Should contain a ConfigHandler for topics",
               this.servers(0).dynamicConfigHandlers.contains(ConfigType.Client))
    val clientId = "testClient"
    val props = new Properties()
    props.put(ClientConfigOverride.ProducerOverride, "1000")
    props.put(ClientConfigOverride.ConsumerOverride, "2000")
    AdminUtils.changeClientIdConfig(zkUtils, clientId, props)

    TestUtils.retry(10000) {
      val configHandler = this.servers(0).dynamicConfigHandlers(ConfigType.Client).asInstanceOf[ClientIdConfigHandler]
      val quotaManagers: Map[Short, ClientQuotaManager] = servers(0).apis.quotaManagers
      val overrideProducerQuota = quotaManagers.get(RequestKeys.ProduceKey).get.quota(clientId)
      val overrideConsumerQuota = quotaManagers.get(RequestKeys.FetchKey).get.quota(clientId)

      assertEquals(s"ClientId $clientId must have overridden producer quota of 1000",
        Quota.upperBound(1000), overrideProducerQuota)
        assertEquals(s"ClientId $clientId must have overridden consumer quota of 2000",
        Quota.upperBound(2000), overrideConsumerQuota)
    }
  }

  @Test
  def testConfigChangeOnNonExistingTopic() {
    val topic = TestUtils.tempTopic
    try {
      val logProps = new Properties()
      logProps.put(LogConfig.FlushMessagesProp, 10000: java.lang.Integer)
      AdminUtils.changeTopicConfig(zkUtils, topic, logProps)
      fail("Should fail with AdminOperationException for topic doesn't exist")
    } catch {
      case e: AdminOperationException => // expected
    }
  }

  @Test
  def testProcessNotification {
    val props = new Properties()
    props.put("a.b", "10")

    // Create a mock ConfigHandler to record config changes it is asked to process
    val entityArgument = new Capture[String]()
    val propertiesArgument = new Capture[Properties]()
    val handler = EasyMock.createNiceMock(classOf[ConfigHandler])
    handler.processConfigChanges(
      EasyMock.and(EasyMock.capture(entityArgument), EasyMock.isA(classOf[String])),
      EasyMock.and(EasyMock.capture(propertiesArgument), EasyMock.isA(classOf[Properties])))
    EasyMock.expectLastCall().once()
    EasyMock.replay(handler)

    val configManager = new DynamicConfigManager(zkUtils, Map(ConfigType.Topic -> handler))
    // Notifications created using the old TopicConfigManager are ignored.
    configManager.processNotification(Some("not json"))

    // Incorrect Map. No version
    try {
      val jsonMap = Map("v" -> 1, "x" -> 2)
      configManager.processNotification(Some(Json.encode(jsonMap)))
      fail("Should have thrown an Exception while parsing incorrect notification " + jsonMap)
    }
    catch {
      case t: Throwable =>
    }
    // Version is provided. EntityType is incorrect
    try {
      val jsonMap = Map("version" -> 1, "entity_type" -> "garbage", "entity_name" -> "x")
      configManager.processNotification(Some(Json.encode(jsonMap)))
      fail("Should have thrown an Exception while parsing incorrect notification " + jsonMap)
    }
    catch {
      case t: Throwable =>
    }

    // EntityName isn't provided
    try {
      val jsonMap = Map("version" -> 1, "entity_type" -> ConfigType.Topic)
      configManager.processNotification(Some(Json.encode(jsonMap)))
      fail("Should have thrown an Exception while parsing incorrect notification " + jsonMap)
    }
    catch {
      case t: Throwable =>
    }

    // Everything is provided
    val jsonMap = Map("version" -> 1, "entity_type" -> ConfigType.Topic, "entity_name" -> "x")
    configManager.processNotification(Some(Json.encode(jsonMap)))

    // Verify that processConfigChanges was only called once
    EasyMock.verify(handler)
  }
}


text:
The `Type` property specifies which type of the image should be rendered.

The available types are:

* Default
* Thumbnail
* Responsive
* Rounded
* Circle


text:
#pragma once

#include "AttributeDataIB.h"
#include "AttributeStatusIB.h"
#include "StructBuilder.h"
#include "StructParser.h"

#include <app/AppBuildConfig.h>
#include <app/util/basic-types.h>
#include <lib/core/CHIPCore.h>
#include <lib/core/CHIPTLV.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/logging/CHIPLogging.h>

namespace chip {
namespace app {
namespace AttributeReportIB {
enum class Tag : uint8_t
{
    kAttributeStatus = 0,
    kAttributeData   = 1,
};

class Parser : public StructParser
{
public:
#if CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK
    /**
     *  @brief Roughly verify the message is correctly formed
     *   1) all mandatory tags are present
     *   2) all elements have expected data type
     *   3) any tag can only appear once
     *   4) At the top level of the structure, unknown tags are ignored for forward compatibility
     *  @note The main use of this function is to print out what we're
     *    receiving during protocol development and debugging.
     *    The encoding rule has changed in IM encoding spec so this
     *    check is only "roughly" conformant now.
     *
     *  @return #CHIP_NO_ERROR on success
     */
    CHIP_ERROR CheckSchemaValidity() const;
#endif

    /**
     *  @brief Get a TLVReader for the StatusIB. Next() must be called before accessing them.
     *
     *  @param [in] apAttributeStatus    A pointer to apAttributeStatus
     *
     *  @return #CHIP_NO_ERROR on success
     *          # CHIP_ERROR_WRONG_TLV_TYPE if there is such element but it's not a structure
     *          #CHIP_END_OF_TLV if there is no such element
     */
    CHIP_ERROR GetAttributeStatus(AttributeStatusIB::Parser * const apAttributeStatus) const;

    /**
     *  @brief Get a TLVReader for the AttributeDataIB. Next() must be called before accessing them.
     *
     *  @param [in] apAttributeData    A pointer to apAttributeData
     *
     *  @return #CHIP_NO_ERROR on success
     *          #CHIP_ERROR_WRONG_TLV_TYPE if there is such element but it's not a AttributeData
     *          #CHIP_END_OF_TLV if there is no such element
     */
    CHIP_ERROR GetAttributeData(AttributeDataIB::Parser * const apAttributeData) const;
};

class Builder : public StructBuilder
{
public:
    /**
     *  @brief Initialize a AttributeDataIB::Builder for writing into the TLV stream
     *
     *  @return A reference to AttributeDataIB::Builder
     */
    AttributeDataIB::Builder & CreateAttributeData();

    AttributeDataIB::Builder & GetAttributeData() { return mAttributeData; }
    /**
     *  @brief Initialize a StatusIB::Builder for writing into the TLV stream
     *
     *  @return A reference to StatusIB::Builder
     */
    AttributeStatusIB::Builder & CreateAttributeStatus();

    /**
     *  @brief Mark the end of this AttributeReportIB
     *
     *  @return A reference to *this
     */
    AttributeReportIB::Builder & EndOfAttributeReportIB();

private:
    AttributeStatusIB::Builder mAttributeStatus;
    AttributeDataIB::Builder mAttributeData;
};
} // namespace AttributeReportIB
} // namespace app
} // namespace chip


text:
         {{climbing.belay}}

                {{attempt.difficulty}}/+down

        <button type="button" ng-show='isEditable(climbing)' ng-click='edited(climbing)' class="btn btn-default btn-sm">

        </button>

        <button type="button" ng-click='remove(climbing)' class="btn btn-default btn-sm">

        </button>
        <training-climbing climbing='climbing' ng-show='isEditable(climbing)' />

            <training-climbing climbing='new_climbing' />

            <button type="button" ng-click='add(new_climbing)' class="btn btn-default btn-sm add-button">
                 Add
            </button>


text:
namespace System.Runtime.InteropServices
{

#if CONFIG_COM_INTEROP

[AttributeUsage(AttributeTargets.Method, Inherited=false)]
public sealed class ComUnregisterFunctionAttribute : Attribute
{
	// Constructor.
	public ComUnregisterFunctionAttribute() {}

}; // class ComUnregisterFunctionAttribute

#endif // CONFIG_COM_INTEROP

}; // namespace System.Runtime.InteropServices


text:
package team.cs6365.payfive.ui.main;

import java.util.ArrayList;
import java.util.List;

import team.cs6365.payfive.PayFive;
import team.cs6365.payfive.R;
import team.cs6365.payfive.model.Transaction;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * A custom ArrayAdapter used by the {@link AppListFragment} to display the
 * device's installed applications.
 */
public class HistoryAdapter extends BaseAdapter {
	private LayoutInflater mInflater;
	private Context ctx;
	private List<Transaction> items;

	private TextView tvDate, tvAmount, tvType, tvPerson;
	private ImageView ivType;
	private Drawable drawableType;

	public HistoryAdapter(Context ctx) {
		this.ctx = ctx;
		mInflater = (LayoutInflater) ctx
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		items = new ArrayList<Transaction>();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view;

		if (convertView == null) {
			view = mInflater.inflate(R.layout.row_history, null);
		} else {
			view = convertView;
		}

		Transaction current = items.get(position);
		if (current != null) {

			tvDate = (TextView) view.findViewById(R.id.tv_date);
			tvAmount = (TextView) view.findViewById(R.id.tv_amount);
			tvType = (TextView) view.findViewById(R.id.tv_type);
			tvPerson = (TextView) view.findViewById(R.id.tv_person);
			ivType = (ImageView) view.findViewById(R.id.iv_type);

			String fromTo = "";

			tvDate.setText(current.getDate());
			tvAmount.setText(String.valueOf(current.getAmount()));
			if (current.isSendType()) {
				// if sending transaction
				drawableType = PayFive.getContext().getResources()
						.getDrawable(R.drawable.send);
				tvType.setText("sent to");
				tvPerson.setText(current.getRecipient().getName());
			} else {
				// if receiving transaction
				drawableType = PayFive.getContext().getResources()
						.getDrawable(R.drawable.recv);
				tvType.setText("received from");
				tvPerson.setText(current.getSender().getName());
			}
			ivType.setImageDrawable(drawableType);

		}

		return view;
	}

	public void setItems(List<Transaction> data) {
		if (items != null)
			items.clear();
		if (data != null) {
			items = data;
		}
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return items.size();
	}

	@Override
	public Transaction getItem(int position) {

		return items.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
}


text:
import wx
from cairis.core.armid import *
from ComponentPanel import ComponentPanel
from cairis.core.ComponentParameters import ComponentParameters
import DialogClassParameters

__author__ = 'Shamal Faily'

class ComponentDialog(wx.Dialog):
  def __init__(self,parent):
    wx.Dialog.__init__(self,parent,COMPONENT_ID,'Edit Component',style=wx.DEFAULT_DIALOG_STYLE|wx.MAXIMIZE_BOX|wx.THICK_FRAME|wx.RESIZE_BORDER,size=(400,500))
    self.theName = ''
    self.theDescription = ''
    self.theInterfaces = []
    self.theStructure = []
    self.theRequirements = []
    self.theGoals = []
    self.theComponentId = -1
    self.panel = 0
    self.buildControls()
    self.commitVerb = 'Add'

  def buildControls(self):
    mainSizer = wx.BoxSizer(wx.VERTICAL)
    self.panel = ComponentPanel(self)
    self.panel.buildControls()
    mainSizer.Add(self.panel,1,wx.EXPAND)
    self.SetSizer(mainSizer)
    wx.EVT_BUTTON(self,COMPONENT_BUTTONCOMMIT_ID,self.onCommit)

  def load(self,component):
    self.theComponentId = component.id()
    self.panel.loadControls(component)
    self.commitVerb = 'Edit'

  def onCommit(self,evt):
    commitLabel = self.commitVerb + ' component'
    nameCtrl = self.FindWindowById(COMPONENT_TEXTNAME_ID)
    descCtrl = self.FindWindowById(COMPONENT_TEXTDESCRIPTION_ID)
    ifCtrl = self.FindWindowById(COMPONENT_LISTINTERFACES_ID)
    structCtrl = self.FindWindowById(COMPONENT_LISTSTRUCTURE_ID)
    reqsCtrl = self.FindWindowById(COMPONENT_LISTREQUIREMENTS_ID)
    goalsCtrl = self.FindWindowById(COMPONENT_LISTGOALS_ID)
    self.theName = nameCtrl.GetValue()
    self.theDescription = descCtrl.GetValue()
    self.theInterfaces = ifCtrl.dimensions()
    self.theStructure = structCtrl.associations()
    self.theRequirements = reqsCtrl.dimensions()
    self.theGoals = reqsCtrl.dimensions()

    if len(self.theName) == 0:
      dlg = wx.MessageDialog(self,'Component name cannot be empty',commitLabel,wx.OK)
      dlg.ShowModal()
      dlg.Destroy()
      return
    if len(self.theDescription) == 0:
      dlg = wx.MessageDialog(self,'Description cannot be empty',commitLabel,wx.OK)
      dlg.ShowModal()
      dlg.Destroy()
      return
    if len(self.theInterfaces) == 0:
      dlg = wx.MessageDialog(self,'Interfaces need to be defined for components',commitLabel,wx.OK)
      dlg.ShowModal()
      dlg.Destroy()
      return
    else:
      self.EndModal(COMPONENT_BUTTONCOMMIT_ID)

  def parameters(self):
    parameters = ComponentParameters(self.theName,self.theDescription,self.theInterfaces,self.theStructure,self.theRequirements,self.theGoals,[])
    parameters.setId(self.theComponentId)
    return parameters


text:
import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';

const SprkFieldError = (props) => {
  const {
    children,
    additionalClasses,
    idString,
    analyticsString,
    id,
    forwardedRef,
    ...rest
  } = props;

  return (
    <div
      className={classNames('sprk-b-ErrorContainer', additionalClasses)}
      data-analytics={analyticsString}
      data-id={idString}
      id={id}
      ref={forwardedRef}
      {...rest}
    >
      {children}
    </div>
  );
};

SprkFieldError.propTypes = {
  /** Content to render inside of the component. */
  children: PropTypes.node,
  /**
   * Assigned to the `id` attribute
   * of the rendered component.
   */
  id: PropTypes.string.isRequired,
  /**
   * A space-separated string of
   * classes to add to the component.
   */
  additionalClasses: PropTypes.string,
  /**
   * Assigned to the `data-analytics`
   * attribute serving as a unique
   * selector for outside libraries to capture data.
   */
  analyticsString: PropTypes.string,
  /**
   * Assigned to the `data-id` attribute serving as
   * a unique selector for automated tools.
   */
  idString: PropTypes.string,
  /**
   * A ref passed in will be attached to the rendered component.
   */
  forwardedRef: PropTypes.oneOfType([PropTypes.shape(), PropTypes.func]),
};

export default SprkFieldError;