text:
struct Text {
    fsuint textId;
    float x;
    float y;
    float rotation;
    float alpha;
};

struct UserPtr {
    int screenRes;
    fsuint bufferId;
    std::vector<Text> texts;
};

void createTexTransforms(void* _userPtr, unsigned int _width, unsigned int _height) {
    REQUIRE(_width == TEXT_BUFFER_SIZE);
    REQUIRE(_height == TEXT_BUFFER_SIZE * 2);
}

void updateTransforms(void* _userPtr, unsigned int _xoff, unsigned int _yoff, unsigned int _width,
                              unsigned int _height, const unsigned int* _pixels, void* _ownerPtr) {
    UserPtr* ptr = static_cast<UserPtr*>(_userPtr);

    float screenRes = (float) ptr->screenRes;

    for(auto text : ptr->texts) {
        float i = fmod(text.textId * 2, TEXT_BUFFER_SIZE);
        float j = (text.textId * 2) / TEXT_BUFFER_SIZE;

        REQUIRE(i < TEXT_BUFFER_SIZE);
        REQUIRE(j < TEXT_BUFFER_SIZE * 2);

        unsigned int p = (unsigned int) (j * TEXT_BUFFER_SIZE + i);

        unsigned int packByte1 = _pixels[p];
        unsigned int packByte2 = _pixels[p + 1];

        int x = ((packByte1 & 0x000000ff) >>  0);
        int y = ((packByte1 & 0x0000ff00) >>  8);
        int r = ((packByte1 & 0x00ff0000) >> 16);
        int a = ((packByte1 & 0xff000000) >> 24);

        REQUIRE(a < 256); REQUIRE(a >= 0);
        REQUIRE(r < 256); REQUIRE(r >= 0);
        REQUIRE(x < 256); REQUIRE(x >= 0);
        REQUIRE(y < 256); REQUIRE(y >= 0);

        int px = (packByte2 & 0x000000ff) >> 0;
        int py = (packByte2 & 0x0000ff00) >> 8;

        REQUIRE(px < 256); REQUIRE(px >= 0);
        REQUIRE(py < 256); REQUIRE(py >= 0);

        float txe = screenRes / 255.0; // max translation x error
        float tye = screenRes / 255.0; // max translation y error

        float rx = (x / 255.0) * screenRes;
        float ry = (y / 255.0) * screenRes;

        // tests that the original results fits inside results with its logical error
        REQUIRE(text.x < rx + txe);
        REQUIRE(text.y < ry + tye);
        REQUIRE(text.x > rx - txe);
        REQUIRE(text.y > ry - tye);

        // compute the result and add the precision, see text.vs
        rx = rx + txe * (px / 255.0);
        ry = ry + tye * (py / 255.0);

        // result error
        float dx = fabs(text.x - rx);
        float dy = fabs(text.y - ry);

        // theoritical floating point precision error on precision encoding, see glfontstash.h
        float perror = 0.00196f;

        float epxe = txe * perror; // theoritical encoded error on translation x
        float epye = tye * perror; // theoritical encoded error on translation y

        // test that final result with its precision added is lower than the theoritical one
        REQUIRE(dx <= epxe);
        REQUIRE(dy <= epye);
    }
}

void updateAtlas(void* _userPtr, unsigned int _xoff, unsigned int _yoff,
                         unsigned int _width, unsigned int _height, const unsigned int* _pixels) {

}

void createAtlas(void* _userPtr, unsigned int _width, unsigned int _height) {
    REQUIRE(_width == ATLAS_WIDTH);
    REQUIRE(_height == ATLAS_HEIGHT);
}

bool errorCallback(void* _userPtr, fsuint buffer, GLFONSError error) {
    UserPtr* ptr = static_cast<UserPtr*>(_userPtr);

    REQUIRE(error == GLFONSError::ID_OVERFLOW);
    REQUIRE(ptr->bufferId == buffer);

    return false;
}

FONScontext* initContext(void* _usrPtr) {
    GLFONSparams params;

    params.errorCallback = errorCallback;
    params.createAtlas = createAtlas;
    params.createTexTransforms = createTexTransforms;
    params.updateAtlas = updateAtlas;
    params.updateTransforms = updateTransforms;

    return glfonsCreate(ATLAS_WIDTH, ATLAS_HEIGHT, FONS_ZERO_TOPLEFT, params, _usrPtr);
}

int initFont(FONScontext* _context) {
    unsigned int dataSize;
    unsigned char* data = bytesFromResource("Roboto-Regular.ttf", &dataSize);

    return fonsAddFont(_context, "droid-serif", data, dataSize);
}

TEST_CASE( "Test context initialization", "[Core][Fontstash][glfonsCreate]" ) {
    FONScontext* context = initContext(nullptr);

    REQUIRE(context != NULL);

    glfonsDelete(context);
}

TEST_CASE( "Test .ttf file initialization", "[Core][Fontstash][fonsAddFont]" ) {
    FONScontext* context = initContext(nullptr);
    int font = initFont(context);

    REQUIRE(font != FONS_INVALID);

    glfonsDelete(context);
}

TEST_CASE( "Test the buffer creation and the size of the required texture transform", "[Core][Fontstash][glfonsBufferCreate]" ) {
    FONScontext* context = initContext(nullptr);

    fsuint buffer;
    glfonsBufferCreate(context, TEXT_BUFFER_SIZE, &buffer);

    glfonsDelete(context);
}

TEST_CASE( "Test that the overflow callback gets called for the right overflow size", "[Core][Fontstash][errorCallback]" ) {
    UserPtr p;

    FONScontext* context = initContext(&p);
    int font = initFont(context);

    glfonsBufferCreate(context, TEXT_BUFFER_SIZE, &p.bufferId);
    glfonsBindBuffer(context, p.bufferId);

    fsuint id[ID_OVERFLOW_SIZE + 1];
    // create an overflow
    glfonsGenText(context, ID_OVERFLOW_SIZE + 1, id);

    glfonsDelete(context);
}

TEST_CASE( "Test that the number of vertices correspond to the logic", "[Core][Fontstash][glfonsVertices]" ) {
    UserPtr p;

    FONScontext* context = initContext(&p);
    int font = initFont(context);

    glfonsBufferCreate(context, TEXT_BUFFER_SIZE, &p.bufferId);
    glfonsBindBuffer(context, p.bufferId);

    fonsSetSize(context, 15.0);
    fonsSetFont(context, font);

    fsuint id;
    glfonsGenText(context, 1, &id);

    std::string text("tangram");
    glfonsRasterize(context, id, text.c_str());

    std::vector<float> vertices;
    int size = glfonsVerticesSize(context);
    vertices.resize(size * INNER_DATA_OFFSET);
    glfonsVertices(context, reinterpret_cast<float*>(vertices.data()));

    REQUIRE(size == text.size() * 6); // shoud have 6 vertices per glyph

    glfonsDelete(context);
}

TEST_CASE( "Test that unpacking the encoded transforms give expected results", "[Core][Fontstash][glfonsTransform]" ) {
    UserPtr p;
    FONScontext* context = initContext(&p);
    int font = initFont(context);

    glfonsBufferCreate(context, TEXT_BUFFER_SIZE, &p.bufferId);
    glfonsBindBuffer(context, p.bufferId);

    fonsSetSize(context, 15.0);
    fonsSetFont(context, font);

    p.screenRes = 1024;

    glfonsScreenSize(context, p.screenRes, p.screenRes);

    for(int i = 0; i < 1024; i+=24) {
        Text text;

        glfonsGenText(context, 1, &text.textId);

        text.x = i;
        text.y = i / 2.0;
        text.rotation = i * M_PI;
        text.alpha = 0.5;

        std::string str("tangram");
        glfonsRasterize(context, text.textId, str.c_str());
        glfonsTransform(context, text.textId, text.x, text.y, text.rotation, text.alpha);

        p.texts.push_back(text);
    }

    glfonsUpdateTransforms(context, nullptr);

    std::vector<float> vertices;
    int size = glfonsVerticesSize(context);
    vertices.resize(size * INNER_DATA_OFFSET);
    glfonsVertices(context, reinterpret_cast<float*>(vertices.data()));

    glfonsDelete(context);
}


text:
""" Test that import errors are detected. """
# pylint: disable=invalid-name, unused-import, no-absolute-import, bare-except, broad-except, wrong-import-order, wrong-import-position
import totally_missing # [import-error]

try:
    import maybe_missing
except ImportError:
    maybe_missing = None

try:
    import maybe_missing_1
except (ImportError, SyntaxError):
    maybe_missing_1 = None

try:
    import maybe_missing_2 # [import-error]
except ValueError:
    maybe_missing_2 = None

try:
    if maybe_missing:
        import really_missing
except ImportError:
    pass

from .collections import missing # [import-error]

from .syntax_error import toto # [syntax-error]

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
More Florida Lichens (New York), Incl. 10 Cent Tour Pyrenol. 155 (1995)

#### Original name
Strigula connivens R. C. Harris

### Remarks
null


text:
package com.jaquadro.minecraft.storagedrawers.util;

import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public final class WorldUtils {
    private WorldUtils() {}

    @NotNull
    public static BlockHitResult rayTraceEyes(@NotNull Level level, @NotNull Player player, @NotNull BlockPos blockPos) {
        Vec3 eyePos = player.getEyePosition(1);
        Vec3 lookVector = player.getViewVector(1);
        Vec3 endPos = eyePos.add(lookVector.scale(eyePos.distanceTo(Vec3.atCenterOf(blockPos)) + 1));
        ClipContext context = new ClipContext(eyePos, endPos, ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, player);
        return level.clip(context);
    }

    @Nullable
    public static <BE extends BlockEntity> BE getBlockEntity(@NotNull BlockGetter level, @NotNull BlockPos blockPos, @NotNull Class<BE> blockEntityClass) {
        if (level instanceof Level && !((Level) level).isLoaded(blockPos))
            return null;

        BlockEntity blockEntity = level.getBlockEntity(blockPos);
        return blockEntityClass.isInstance(blockEntity) ? blockEntityClass.cast(blockEntity) : null;
    }
}


text:
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
module Network.Yeller.Internals where
import qualified Data.Map as M
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.ByteString.Lazy as LBS
import qualified GHC.Stack
import qualified Control.Exception
import qualified Data.Typeable
import qualified Data.Aeson as JSON
import qualified Network.BSD
import qualified Network.HTTP.Client as HTTP
import qualified Network.HTTP.Types as HTTPStatus
import qualified Network.HTTP.Client.TLS as TLS
import System.IO as IO
import qualified Control.Concurrent.STM as STM
import Control.Applicative((<$>))
import Data.Monoid((<>))

-- | An error notification. This is what is sent to Yeller's servers
data ErrorNotification a = ErrorNotification {
    -- | The type of the error. E.g. SomeException, DivideByZero
    errorType :: T.Text

    -- | The message of the exception
  , errorMessage :: T.Text

    -- | The stacktrace of the error. Usually grabbed using 'GHC.Stack.whoCreated'
  , errorStackTrace :: [StackFrame]

    -- | The host that this error occurred on
  , errorHost :: T.Text

    -- | The application environment this error occurred in
  , errorEnvironment :: T.Text

    -- | The version of the yeller client reporting the error
  , errorClientVersion :: T.Text

    -- | See 'ExtraErrorInfo'
  , errorExtra :: ExtraErrorInfo a
} deriving (Show, Eq)

-- | A line of the stacktrace
data StackFrame = StackFrame {
    -- | The filename this line occurred in
    stackFilename :: T.Text

    -- | The line number(s) this line occurred in
  , stackLineNumber :: T.Text

    -- | The function this line occurred in
  , stackFunction :: T.Text

    -- See 'StackOptions'
  , stackOptions :: StackOptions
} deriving (Show, Eq)

-- | Options to be associated with each
-- line in the stacktrace. Currently
-- only supports if the line is in
-- the application or not.
data StackOptions = StackOptions {
  stackOptionsInApp :: Bool
} deriving (Show, Eq)

-- | Extra error information to be passed along with
-- an error. All fields are optional.
data ExtraErrorInfo a = ExtraErrorInfo {
    -- | If the error happened during a web request,
    -- the url that was hit during that request
    errorURL :: Maybe T.Text
    -- | A map of data that has to conform to Aeson's
    -- ToJSON typeclass. Can be anything
    -- you want that helps you debug the error.
  , errorCustomData :: Maybe (M.Map T.Text a)

    -- | What toplevel part of the application the
    -- request that caused the error came from
    -- e.g. web controller name, background job name
  , errorLocation :: Maybe T.Text

    -- | Which user the error happened from.
    -- Lets you see how many total users were affected by an error
  , errorUser :: Maybe UserInfo

    -- | Which http request was happening when
    -- the error occurred
  , errorHTTPRequest :: Maybe HTTPRequest
} deriving (Show, Eq)

-- | Lets you attach which user the error happened with
-- which lets you count the total number of affected users
data UserInfo = UserInfo {
  -- | The user id of the affected user
  userID :: Integer
} deriving (Show, Eq)

instance JSON.ToJSON UserInfo where
  toJSON u = JSON.object ["id" JSON..= userID u]

-- | Extra error info with all fields turned off.
--
-- Useful when getting started, but real apps should fill
-- in as many fields as possible for better debugging context
emptyExtraErrorInfo :: ExtraErrorInfo Int
emptyExtraErrorInfo = ExtraErrorInfo Nothing Nothing Nothing Nothing Nothing

-- | Lets you attach which http request was occurring when the
-- error happened
-- which lets you see the browser, if the request came from a spider
-- and so on
data HTTPRequest = HTTPRequest {
  -- | The user agent of the impacted http request
  httpRequestUserAgent :: T.Text
} deriving (Show, Eq)

instance JSON.ToJSON HTTPRequest where
  toJSON h = JSON.object ["user-agent" JSON..= httpRequestUserAgent h]

instance JSON.ToJSON StackOptions where
  toJSON s = JSON.object ["in-app" JSON..= stackOptionsInApp s]

instance JSON.ToJSON StackFrame where
  toJSON s = JSON.toJSON (stackFilename s, stackLineNumber s, stackFunction s, stackOptions s)

instance (JSON.ToJSON b) => JSON.ToJSON (ErrorNotification b) where
  toJSON e = JSON.object ["type" JSON..= errorType e
                          , "message" JSON..= errorMessage e
                          , "stacktrace" JSON..= errorStackTrace e
                          , "host" JSON..= errorHost e
                          , "application-environment" JSON..= errorEnvironment e
                          , "client-version" JSON..= errorClientVersion e
                          , "url" JSON..= errorURL ( errorExtra e)
                          , "location" JSON..= errorLocation ( errorExtra e)
                          , "custom-data" JSON..= makeJSONCustomData ( errorExtra e)
                          ]

makeJSONCustomData :: JSON.ToJSON a => ExtraErrorInfo a -> JSON.Value
makeJSONCustomData e = JSON.toJSON (maybeAddHTTPUserAgent e (maybeAddUser e withJSONVals))
  where withJSONVals = M.map JSON.toJSON (maybeOr (errorCustomData e) M.empty)

maybeAddUser :: ExtraErrorInfo a -> M.Map T.Text JSON.Value -> M.Map T.Text JSON.Value
maybeAddUser (ExtraErrorInfo { errorUser =  Nothing } ) m = m
maybeAddUser (ExtraErrorInfo { errorUser = (Just user) }) m =
  case M.lookup "user" m of
    Nothing -> M.insert "user" (JSON.toJSON user) m
    (Just (JSON.Object u)) -> M.insert "user" (JSON.Object (HM.insert "id" (JSON.toJSON (userID user)) u)) m
    (Just _)  -> m

maybeAddHTTPUserAgent :: ExtraErrorInfo a -> M.Map T.Text JSON.Value -> M.Map T.Text JSON.Value
maybeAddHTTPUserAgent (ExtraErrorInfo { errorHTTPRequest =  Nothing } ) m = m
maybeAddHTTPUserAgent (ExtraErrorInfo { errorHTTPRequest = (Just http) }) m =
  case M.lookup "http-request" m of
    Nothing -> M.insert "http-request" (JSON.toJSON http) m
    (Just (JSON.Object h)) -> M.insert "http-request" (JSON.Object (HM.insert "user-agent" (JSON.toJSON (httpRequestUserAgent http)) h)) m
    (Just _)  -> m

maybeOr :: Maybe a -> a -> a
maybeOr (Just a) _ = a
maybeOr Nothing a = a

yellerVersion :: T.Text
yellerVersion = T.pack "yeller-haskell: 0.1.0.4"

-- | An endpoint to send errors with. Must end with \"/\"
-- sample:
--
-- @
-- Backend \"https://collector1.yellerapp.com\"
-- @
newtype Backend = Backend T.Text

-- | A Yeller client.
-- Build one with 'client' like so:
-- @
-- client (defaultClientSettings { clientSettingsToken = YellerToken "YOUR_TOKEN_HERE" })
-- @
--
--
-- Used to keep persistent
-- http connections alive, keep track of
-- which endpoint to send to, and a bunch of
-- data that's sent along with the error.
data YellerClient = YellerClient {
    -- | The token used to authenticate with Yeller's servers.
    clientToken :: T.Text

    -- | The server this client is running on.
  , clientHost :: T.Text

    -- | The environment this client is running in
  , clientEnvironment :: T.Text

    -- | The version number of this client
  , clientVersion :: T.Text

    -- | The name of the application package that is using this client
  , clientApplicationPackage :: T.Text

    -- | The http manager for tracking open connections
  , clientManager :: HTTP.Manager

    -- | The set of backends to use. The next backend that will
    -- be used is second in the list.
  , clientBackends :: STM.TVar [Backend]
    -- | The client error handler. See 'YellerClientErrorHandler'
  , clientErrorHandler :: YellerClientErrorHandler
    -- | The maximum number of retries
  , clientMaxRetries :: Int
} | DisabledYellerClient

-- | An error handler, for dealing with errors when sending errors to Yeller's servers
-- 'defaultErrorHandler' just prints to stderr when receiving errors, but you
-- might want to override that to make it go to your logging system of choice.
data YellerClientErrorHandler = YellerClientErrorHandler {
    -- | Used when handling authentication (401, 403) failures from Yeller's servers.
    -- These errors are *not* retried like other ones.
    handleAuthenticationErrors :: HTTP.Response HTTP.BodyReader -> IO ()
    -- | Used when handling any errors that aren't authentication related.
    -- This function will only be called after 'clientMaxRetries' is
    -- exceeded.
  , handleIOErrors :: Control.Exception.SomeException -> ErrorNotification JSON.Value -> IO ()
}

-- | The Environment your client is running in. If set to 'TestEnvironment',
-- then no errors will be reported (which you should do for development/testing)
data ApplicationEnvironment =
  -- | Clients constructed with this environment don't send errors.
  TestEnvironment |
  -- | Any client in this kind of environment will report errors.
  ApplicationEnvironment T.Text

-- | The name of the package your application is in.
newtype ApplicationPackage = ApplicationPackage T.Text

-- | An api token. Get one from your project's settings page
newtype YellerToken = YellerToken T.Text

-- | Options you pass when creating a client, usually done like this:
--
-- @
-- 'client' ('defaultClientSettings' { 'clientSettingsToken' = 'YellerToken' \"YOUR_TOKEN_HERE\" })
-- @
data YellerClientSettings = YellerClientSettings {
    -- | The api token used for authenticating with Yeller's servers
    clientSettingsToken :: YellerToken

    -- | (optional): the name of the server this client is running on
    -- if set to 'Nothing', 'client' will default it to 'Network.BSD.getHostName'
  , clientSettingsHost :: Maybe T.Text

    -- | The name of the environment the application is running in
    -- for example: production, test etc
    -- if set to 'TestEnvironment', the client will be disabled
  , clientSettingsEnvironment :: ApplicationEnvironment

    -- | The name of the application package, used to
    -- filter out noisy stacktrace lines by default in
    -- the UI. Lines from functions starting with this
    -- are marked as \"in-app\", others will only show
    -- up via a toggle in the UI.
  , clientSettingsApplicationPackage :: ApplicationPackage

    -- | A list of servers to contact. Weird things will
    -- probably happen if it's set to []
  , clientSettingsBackends :: [Backend]

    -- | Used for handling errors when sending to Yeller's
    -- servers. See 'YellerClientErrorHandler' for more.
  , clientSettingsErrorHandler :: YellerClientErrorHandler

    -- | The maximum number of times to retry sending to
    -- the servers before logging a failure.
    -- Weird things will probably happen if set to less than 1.
  , clientSettingsMaxRetries :: Int
}

-- | The default client settings, used for constructing a client
defaultClientSettings :: YellerClientSettings
defaultClientSettings = YellerClientSettings {
    clientSettingsToken = YellerToken bogusClientToken
  , clientSettingsHost = Nothing
  , clientSettingsEnvironment = ApplicationEnvironment "production"
  , clientSettingsApplicationPackage = ApplicationPackage ""
  , clientSettingsBackends = map Backend defaultBackends
  , clientSettingsErrorHandler = defaultErrorHandler
  , clientSettingsMaxRetries = 10
}

-- | The default error handler, which logs errors when sending things to Yeller
-- to stderr
defaultErrorHandler :: YellerClientErrorHandler
defaultErrorHandler = YellerClientErrorHandler {
  handleAuthenticationErrors = \_ -> IO.hPutStrLn stderr "Failed to authenticate with the yeller servers. Check your api key is correct and try again."
  , handleIOErrors = \x n -> IO.hPrint stderr ("Error sending an exception to Yeller: " :: String, x, n)
}

bogusClientToken :: T.Text
bogusClientToken = "YOUR_API_TOKEN_HERE"

defaultBackends :: [T.Text]
defaultBackends = [
    "https://collector1.yellerapp.com/"
  , "https://collector2.yellerapp.com/"
  , "https://collector3.yellerapp.com/"
  , "https://collector4.yellerapp.com/"
  , "https://collector5.yellerapp.com/"
  ]

-- | A class for converting things into errors.
-- Means you can pass both exceptions, and any
-- other error like values in your code.
class (Data.Typeable.Typeable a, Show a) => ToError a where
  toError :: a -> ErrorNotification b -> ErrorNotification b

instance ToError Control.Exception.SomeException where
  toError = defaultToError

defaultToError :: (Data.Typeable.Typeable e, Show e) => e -> ErrorNotification b -> ErrorNotification b
defaultToError e current = current {
                               errorType = T.pack . show $ Data.Typeable.typeOf e
                             , errorMessage = T.pack $ show e
                           }

parseStackLine :: String -> StackFrame
parseStackLine x = StackFrame {
    stackFilename = filename
  , stackLineNumber = line
  , stackFunction = function
  , stackOptions = StackOptions { stackOptionsInApp = True }
  }
  where encoded = T.pack x
        function = T.takeWhile (/= ' ') encoded
        afterFunction = T.tail $ T.dropWhile (/= ' ') encoded
        filename = manageNoLocationFilename $ T.dropWhile (== '(') $ T.takeWhile (/= ':') afterFunction
        afterFilename = T.dropWhile (== ':') $ T.dropWhile (/= ':') afterFunction
        line = T.take (T.length afterFilename - 1) afterFilename

manageNoLocationFilename :: T.Text -> T.Text
manageNoLocationFilename t
  | t == "<no location info>)" = ""
  | otherwise = t

parseStackTrace :: [String] -> [StackFrame]
parseStackTrace = filter ((/= "Network.Yeller.sendError") . stackFunction) . map parseStackLine

markInApp :: T.Text -> StackFrame -> StackFrame
markInApp package frame
  | T.isPrefixOf package (stackFunction frame) = frame { stackOptions = StackOptions {stackOptionsInApp = True } }
  | otherwise = frame { stackOptions = StackOptions {stackOptionsInApp = False } }

filterInAppLines :: T.Text -> [StackFrame] -> [StackFrame]
filterInAppLines package = map (markInApp package)

-- | Sends an error to Yeller's servers
-- needs a client, something that can be turned into an error (via ToError), and
-- extra error information (which describes additional information to be sent
-- along with the error). See 'ExtraErrorInfo' for the extra info, and 'client' for
-- how to create a client.
--
-- Sample invocation:
--
-- @
-- sendError yellerClient someError 'emptyExtraErrorInfo'
-- @
sendError :: (ToError e, JSON.ToJSON a) => YellerClient -> e -> ExtraErrorInfo a -> IO ()
sendError DisabledYellerClient _ _ = return ()
sendError c e extra = do
  let forced = seq e e
  stack <- GHC.Stack.whoCreated forced
  let existing = ErrorNotification {
        errorType = T.pack . show $ Data.Typeable.typeOf e
      , errorMessage = T.pack $ show e
      , errorStackTrace = filterInAppLines (clientApplicationPackage c) (parseStackTrace stack)
      , errorHost = clientHost c
      , errorEnvironment = clientEnvironment c
      , errorClientVersion = clientVersion c
      , errorExtra = extra
      }
  sendNotification c $ toError e existing

sendNotification :: JSON.ToJSON a => YellerClient -> ErrorNotification a -> IO ()
sendNotification c n = sendNotificationWithRetry 0 c n (JSON.encode n)

sendNotificationWithRetry :: JSON.ToJSON a => Int -> YellerClient -> ErrorNotification a -> LBS.ByteString -> IO ()
sendNotificationWithRetry currentRetryCount c n encoded = do
  currentBackend <- cycleBackends c
  r <- makeRequest c currentBackend encoded
  res <- Control.Exception.try $ HTTP.withResponse r (clientManager c) return
  case res of
    (Left (err :: Control.Exception.SomeException)) -> if currentRetryCount > clientMaxRetries c then
                                                          sendNotificationWithRetry (currentRetryCount + 1) c n encoded
                                                        else
                                                          handleIOErrors (clientErrorHandler c) err (encodeCustomDataAsJSON n)
    (Right httpResponse) -> handleNonExceptionalSendRequest httpResponse currentRetryCount c n encoded

handleNonExceptionalSendRequest :: JSON.ToJSON a => HTTP.Response HTTP.BodyReader -> Int -> YellerClient -> ErrorNotification a -> LBS.ByteString -> IO ()
handleNonExceptionalSendRequest res currentRetryCount c n encoded
  | status == 403 || status == 401 = handleAuthenticationErrors (clientErrorHandler c) res
  | status > 299 = sendNotificationWithRetry (currentRetryCount + 1) c n encoded
  | otherwise = return ()
  where status = HTTPStatus.statusCode (HTTP.responseStatus res)

encodeCustomDataAsJSON :: JSON.ToJSON a => ErrorNotification a -> ErrorNotification JSON.Value
encodeCustomDataAsJSON n = n { errorExtra = (errorExtra n) { errorCustomData = Just (M.fromList [("data", JSON.toJSON (errorCustomData (errorExtra n)))]) } }

cycleBackends :: YellerClient -> IO Backend
cycleBackends c = STM.atomically $ do
  modifyTVar_ (clientBackends c) cycleBackends_
  head <$> STM.readTVar (clientBackends c)

cycleBackends_ :: [Backend] -> [Backend]
cycleBackends_ (x:xs) = xs ++ [x]
cycleBackends_ xs = xs

modifyTVar_ :: STM.TVar a -> (a -> a) -> STM.STM ()
modifyTVar_ tv f = STM.readTVar tv >>= STM.writeTVar tv . f

makeRequest :: YellerClient -> Backend -> LBS.ByteString -> IO HTTP.Request
makeRequest c (Backend b) n = do
  initReq <- HTTP.parseUrl $ T.unpack (b <> clientToken c)
  let req = initReq {
      HTTP.method = "POST"
    , HTTP.secure = True
    , HTTP.requestBody = HTTP.RequestBodyLBS n
    , HTTP.redirectCount = 0
    , HTTP.requestHeaders = [("User-Agent", TE.encodeUtf8 $ clientVersion c)]
    , HTTP.checkStatus = \_ _ _ -> Nothing
  }
  return req

-- | Initializes a Yeller client, given some client settings
-- Call it like this with the default client settings:
--
-- @
-- 'client' ('defaultClientSettings' { 'clientSettingsToken' = 'YellerToken' \"YOUR_TOKEN_HERE\" })
-- @
client :: YellerClientSettings -> IO YellerClient
client (YellerClientSettings {clientSettingsEnvironment=TestEnvironment}) = return DisabledYellerClient
client c@(YellerClientSettings {clientSettingsEnvironment=(ApplicationEnvironment env), clientSettingsApplicationPackage=(ApplicationPackage package), clientSettingsToken=(YellerToken token)}) = do
  h <- fmap T.pack Network.BSD.getHostName
  m <- HTTP.newManager TLS.tlsManagerSettings
  backends <- STM.newTVarIO (map Backend defaultBackends)
  return YellerClient {
        clientToken = token
      , clientHost = h
      , clientEnvironment = env
      , clientVersion = yellerVersion
      , clientApplicationPackage = package
      , clientManager = m
      , clientBackends = backends
      , clientErrorHandler = clientSettingsErrorHandler c
      , clientMaxRetries = clientSettingsMaxRetries c
    }

shutdownClient :: YellerClient -> IO ()
shutdownClient c = HTTP.closeManager (clientManager c)


text:
package pl.java.scalatech.concurrent;

import java.util.function.Function;

import org.junit.Test;

public class ParallelTest {
    public static long measureSumPerf(Function<Long, Long> adder, long n) {
        long fastest = Long.MAX_VALUE;
        for (int i = 0; i < 10; i++) {
            long start = System.nanoTime();
            long sum = adder.apply(n);
            long duration = (System.nanoTime() - start) / 1_000_000;
            System.out.println("Result: " + sum);
            if (duration < fastest)
                fastest = duration;
        }
        return fastest;
    }

    @Test
    public void testAdder() {
        System.out.println("Iterative sum done in: " + measureSumPerf(ParallelStreams::iterativeSum, 10_000_000) + " msecs");
        System.out.println("Sequential sum done in: " + measureSumPerf(ParallelStreams::sequentialSum, 10_000_000) + " msecs");
        System.out.println("Parallel sum done in: " + measureSumPerf(ParallelStreams::parallelSum, 10_000_000) + " msecs");
        System.out.println("Sequential sum done with Iterate in: " + measureSumPerf(ParallelStreams::sequentialSumInPrimitiveIterate, 10_000_000) + " msecs");
        System.out.println("Parallel sum done with Iterate in: " + measureSumPerf(ParallelStreams::parallelSumInPrimitiveWithIterate, 10_000_000) + " msecs");
        System.out.println(
                "Sequential sum done with RangeClosed in: " + measureSumPerf(ParallelStreams::sequentialSumInPrimitiveRangeClosed, 10_000_000) + " msecs");
        System.out
                .println("Parallel sum done with RangeClosed in: " + measureSumPerf(ParallelStreams::parallelSumInPrimitiveRangeClosed, 10_000_000) + " msecs");
    }
}


text:
<?php

/* @var $this yii\web\View */

use yii\web\View;
use common\models\Project;
use common\widgets\ProjectCard;

$this->title = 'Мастерская';

$this->registerJs(
		'$("#hero__fab").click(function (){'
			.'$(".mdl-layout__content").animate({'
				.'scrollTop: $(".section__hero").outerHeight()'
			.'}, 300);'
		.'});', View::POS_READY);
?>

			<?php
			foreach (Project::getAll() as $project){
				echo ProjectCard::widget(['project' => $project]);
			}
			?>


text:
package com.squareup.wire;

/**
 * Interface for generated {@link Enum} values to help serialization and
 * deserialization.
 */
public interface ProtoEnum {
  /**
   * The tag value of an enum constant.
   */
  int getValue();
}


text:
package com.dbychkov.data.mapper;

import java.util.List;

public interface Mapper <K, V> {

    K mapPojoToEntity(V pojo);

    List<K> mapPojoListToEntityList(List<V> pojoList);

    V mapEntityToPojo(K entity);

    List<V> mapEntityListToPojoList(List<K> entityList);

}


text:
import numpy as np

# TODO: MULTISTEP
LR_POLICY_NUM = 7
class LR_POLICY:
    FIXED, STEP, EXP, INV, MULTISTEP, POLY, SIGMOID = range(LR_POLICY_NUM)

class LRUpdater:
    def __init__(self, *args, **kwargs):
        if "base_lr" in kwargs:
            self.base_lr = kwargs["base_lr"]
        else:
            self.base_lr = kwargs.get("lr", 1.0)
        self.gamma = kwargs.get("gamma", None)
        self.stepsize = kwargs.get("stepsize", None)
        self.power = kwargs.get("power", None)
        self.max_iter = kwargs.get("max_iter", None)
        self.method = None
        self.lr_policy = kwargs.get("lr_policy", LR_POLICY.FIXED)
        self.set_policy(self.lr_policy)
    def set_policy(self, p):
        self.lr_policy = p
        self.method = LRUpdater.METHODS[p]
    def get_lr(self, iter_num):
        return self.method(self, iter_num)
    def fixed(self, iter_num):
        return self.base_lr
    def step(self, iter_num):
        # gamma, stepsize
        return self.base_lr * np.power(self.gamma, (iter_num // self.stepsize))
    def exp(self, iter_num):
        # gamma
        return self.base_lr * np.power(self.gamma, iter_num)
    def inv(self, iter_num):
        # gamma, power
        return self.base_lr * np.power(1.0 + self.gamma * iter_num, -self.power)
    def poly(self, iter_num):
        # power, max_iter
        return self.base_lr * np.power(1 - iter_num * 1.0 / self.max_iter, self.power)
    def sigmoid(self, iter_num):
        # gamma, stepsize
        return self.base_lr * (1.0 / (1.0 + np.exp(-self.gamma * (iter_num - self.stepsize))))

LRUpdater.METHODS = [None] * LR_POLICY_NUM
LRUpdater.METHODS[LR_POLICY.FIXED] = LRUpdater.fixed
LRUpdater.METHODS[LR_POLICY.STEP] = LRUpdater.step
LRUpdater.METHODS[LR_POLICY.EXP] = LRUpdater.exp
LRUpdater.METHODS[LR_POLICY.INV] = LRUpdater.inv
LRUpdater.METHODS[LR_POLICY.POLY] = LRUpdater.poly
LRUpdater.METHODS[LR_POLICY.SIGMOID] = LRUpdater.sigmoid


text:
package org.specs.mock
import org.specs._
import org.specs.runner._
import org.specs.specification._

object countingNamingSchemeSpecification extends Specification {
  "A counting naming scheme" should {
    val scheme = new CountingNamingScheme
    "use the CamelCase scheme for a single mock. 'JMocker' -> 'jMocker'" in {
      scheme.defaultNameFor(classOf[JMocker]) must_== "jMocker"
    }
    "add a 2 to the second named mock. 'JMocker' -> 'jMocker 2'" in {
      scheme.defaultNameFor(classOf[JMocker])
      scheme.defaultNameFor(classOf[JMocker]) must_== "jMocker 2"
    }
  }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <title>Loading...</title>
    <link rel="stylesheet" href="/stylesheets/styles.css">
    <link rel="stylesheet" href="/stylesheets/github-light.css">
    <meta name="viewport" content="width=device-width">

Test

assets/contact.md

assets/profile.md


text:
namespace password_manager {

// static
void JNI_PasswordManagerClientBridgeForTesting_SetLeakDialogWasShownForTesting(
    JNIEnv* env,
    const base::android::JavaParamRef<jobject>& j_web_contents,
    jboolean j_value) {
  content::WebContents* web_contents =
      content::WebContents::FromJavaWebContents(j_web_contents);

  return ChromePasswordManagerClient::FromWebContents(web_contents)
      ->SetCredentialLeakDialogWasShownForTesting(j_value);
}

}  // namespace password_manager


text:
namespace Urho3D
{

void Graphics::SetExternalWindow(void* window)
{
    if (!window_)
        externalWindow_ = window;
    else
        URHO3D_LOGERROR("Window already opened, can not set external window");
}

void Graphics::SetWindowTitle(const String& windowTitle)
{
    windowTitle_ = windowTitle;
    if (window_)
        SDL_SetWindowTitle(window_, windowTitle_.CString());
}

void Graphics::SetWindowIcon(Image* windowIcon)
{
    windowIcon_ = windowIcon;
    if (window_)
        CreateWindowIcon();
}

void Graphics::SetWindowPosition(const IntVector2& position)
{
    if (window_)
        SDL_SetWindowPosition(window_, position.x_, position.y_);
    else
        position_ = position; // Sets as initial position for OpenWindow()
}

void Graphics::SetWindowPosition(int x, int y)
{
    SetWindowPosition(IntVector2(x, y));
}

void Graphics::SetOrientations(const String& orientations)
{
    orientations_ = orientations.Trimmed();
    SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
}

bool Graphics::ToggleFullscreen()
{
    return SetMode(width_, height_, !fullscreen_, borderless_, resizable_, highDPI_, vsync_, tripleBuffer_, multiSample_, monitor_, refreshRate_);
}

void Graphics::SetShaderParameter(StringHash param, const Variant& value)
{
    switch (value.GetType())
    {
    case VAR_BOOL:
        SetShaderParameter(param, value.GetBool());
        break;

    case VAR_INT:
        SetShaderParameter(param, value.GetInt());
        break;

    case VAR_FLOAT:
    case VAR_DOUBLE:
        SetShaderParameter(param, value.GetFloat());
        break;

    case VAR_VECTOR2:
        SetShaderParameter(param, value.GetVector2());
        break;

    case VAR_VECTOR3:
        SetShaderParameter(param, value.GetVector3());
        break;

    case VAR_VECTOR4:
        SetShaderParameter(param, value.GetVector4());
        break;

    case VAR_COLOR:
        SetShaderParameter(param, value.GetColor());
        break;

    case VAR_MATRIX3:
        SetShaderParameter(param, value.GetMatrix3());
        break;

    case VAR_MATRIX3X4:
        SetShaderParameter(param, value.GetMatrix3x4());
        break;

    case VAR_MATRIX4:
        SetShaderParameter(param, value.GetMatrix4());
        break;

    case VAR_BUFFER:
        {
            const PODVector<unsigned char>& buffer = value.GetBuffer();
            if (buffer.Size() >= sizeof(float))
                SetShaderParameter(param, reinterpret_cast<const float*>(&buffer[0]), buffer.Size() / sizeof(float));
        }
        break;

    default:
        // Unsupported parameter type, do nothing
        break;
    }
}

IntVector2 Graphics::GetWindowPosition() const
{
    if (window_)
        return position_;
    return IntVector2::ZERO;
}

PODVector<IntVector3> Graphics::GetResolutions(int monitor) const
{
    PODVector<IntVector3> ret;
    // Emscripten is not able to return a valid list
#ifndef __EMSCRIPTEN__
    unsigned numModes = (unsigned)SDL_GetNumDisplayModes(monitor);

    for (unsigned i = 0; i < numModes; ++i)
    {
        SDL_DisplayMode mode;
        SDL_GetDisplayMode(monitor, i, &mode);
        int width = mode.w;
        int height = mode.h;
        int rate = mode.refresh_rate;

        // Store mode if unique
        bool unique = true;
        for (unsigned j = 0; j < ret.Size(); ++j)
        {
            if (ret[j].x_ == width && ret[j].y_ == height && ret[j].z_ == rate)
            {
                unique = false;
                break;
            }
        }

        if (unique)
            ret.Push(IntVector3(width, height, rate));
    }
#endif

    return ret;
}

IntVector2 Graphics::GetDesktopResolution(int monitor) const
{
#if !defined(__ANDROID__) && !defined(IOS) && !defined(TVOS)
    SDL_DisplayMode mode;
    SDL_GetDesktopDisplayMode(monitor, &mode);
    return IntVector2(mode.w, mode.h);
#else
    // SDL_GetDesktopDisplayMode() may not work correctly on mobile platforms. Rather return the window size
    return IntVector2(width_, height_);
#endif
}

int Graphics::GetMonitorCount() const
{
    return SDL_GetNumVideoDisplays();
}

void Graphics::Maximize()
{
    if (!window_)
        return;

    SDL_MaximizeWindow(window_);
}

void Graphics::Minimize()
{
    if (!window_)
        return;

    SDL_MinimizeWindow(window_);
}

void Graphics::BeginDumpShaders(const String& fileName)
{
    shaderPrecache_ = new ShaderPrecache(context_, fileName);
}

void Graphics::EndDumpShaders()
{
    shaderPrecache_.Reset();
}

void Graphics::PrecacheShaders(Deserializer& source)
{
    URHO3D_PROFILE(PrecacheShaders);

    ShaderPrecache::LoadShaders(this, source);
}

void Graphics::SetShaderCacheDir(const String& path)
{
    String trimmedPath = path.Trimmed();
    if (trimmedPath.Length())
        shaderCacheDir_ = AddTrailingSlash(trimmedPath);
}

void Graphics::AddGPUObject(GPUObject* object)
{
    MutexLock lock(gpuObjectMutex_);

    gpuObjects_.Push(object);
}

void Graphics::RemoveGPUObject(GPUObject* object)
{
    MutexLock lock(gpuObjectMutex_);

    gpuObjects_.Remove(object);
}

void* Graphics::ReserveScratchBuffer(unsigned size)
{
    if (!size)
        return 0;

    if (size > maxScratchBufferRequest_)
        maxScratchBufferRequest_ = size;

    // First check for a free buffer that is large enough
    for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
    {
        if (!i->reserved_ && i->size_ >= size)
        {
            i->reserved_ = true;
            return i->data_.Get();
        }
    }

    // Then check if a free buffer can be resized
    for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
    {
        if (!i->reserved_)
        {
            i->data_ = new unsigned char[size];
            i->size_ = size;
            i->reserved_ = true;

            URHO3D_LOGDEBUG("Resized scratch buffer to size " + String(size));

            return i->data_.Get();
        }
    }

    // Finally allocate a new buffer
    ScratchBuffer newBuffer;
    newBuffer.data_ = new unsigned char[size];
    newBuffer.size_ = size;
    newBuffer.reserved_ = true;
    scratchBuffers_.Push(newBuffer);
    return newBuffer.data_.Get();

    URHO3D_LOGDEBUG("Allocated scratch buffer with size " + String(size));
}

void Graphics::FreeScratchBuffer(void* buffer)
{
    if (!buffer)
        return;

    for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
    {
        if (i->reserved_ && i->data_.Get() == buffer)
        {
            i->reserved_ = false;
            return;
        }
    }

    URHO3D_LOGWARNING("Reserved scratch buffer " + ToStringHex((unsigned)(size_t)buffer) + " not found");
}

void Graphics::CleanupScratchBuffers()
{
    for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
    {
        if (!i->reserved_ && i->size_ > maxScratchBufferRequest_ * 2 && i->size_ >= 1024 * 1024)
        {
            i->data_ = maxScratchBufferRequest_ > 0 ? new unsigned char[maxScratchBufferRequest_] : 0;
            i->size_ = maxScratchBufferRequest_;

            URHO3D_LOGDEBUG("Resized scratch buffer to size " + String(maxScratchBufferRequest_));
        }
    }

    maxScratchBufferRequest_ = 0;
}

void Graphics::CreateWindowIcon()
{
    if (windowIcon_)
    {
        SDL_Surface* surface = windowIcon_->GetSDLSurface();
        if (surface)
        {
            SDL_SetWindowIcon(window_, surface);
            SDL_FreeSurface(surface);
        }
    }
}

void RegisterGraphicsLibrary(Context* context)
{
    Animation::RegisterObject(context);
    Material::RegisterObject(context);
    Model::RegisterObject(context);
    Shader::RegisterObject(context);
    Technique::RegisterObject(context);
    Texture2D::RegisterObject(context);
    Texture2DArray::RegisterObject(context);
    Texture3D::RegisterObject(context);
    TextureCube::RegisterObject(context);
    Camera::RegisterObject(context);
    Drawable::RegisterObject(context);
    Light::RegisterObject(context);
    StaticModel::RegisterObject(context);
    StaticModelGroup::RegisterObject(context);
    Skybox::RegisterObject(context);
    AnimatedModel::RegisterObject(context);
    AnimationController::RegisterObject(context);
    BillboardSet::RegisterObject(context);
    ParticleEffect::RegisterObject(context);
    ParticleEmitter::RegisterObject(context);
    RibbonTrail::RegisterObject(context);
    CustomGeometry::RegisterObject(context);
    DecalSet::RegisterObject(context);
    Terrain::RegisterObject(context);
    TerrainPatch::RegisterObject(context);
    DebugRenderer::RegisterObject(context);
    Octree::RegisterObject(context);
    Zone::RegisterObject(context);
}

}


text:
import mock
from neutron_lib.api import attributes
from neutron_lib.callbacks import events
from neutron_lib import context
from neutron_lib.db import constants as db_const
from neutron_lib.plugins import directory
from oslo_config import cfg
from oslo_policy import policy as oslo_policy
from oslo_serialization import jsonutils

from neutron.db.quota import driver as quota_driver
from neutron import manager
from neutron.pecan_wsgi.controllers import resource
from neutron import policy
from neutron.tests.functional.pecan_wsgi import test_functional

class TestOwnershipHook(test_functional.PecanFunctionalTest):

    def test_network_ownership_check(self):
        net_response = self.app.post_json(
            '/v2.0/networks.json',
            params={'network': {'name': 'meh'}},
            headers={'X-Project-Id': 'tenid'})
        network_id = jsonutils.loads(net_response.body)['network']['id']
        port_response = self.app.post_json(
            '/v2.0/ports.json',
            params={'port': {'network_id': network_id,
                             'admin_state_up': True}},
            headers={'X-Project-Id': 'tenid'})
        self.assertEqual(201, port_response.status_int)

class TestQueryParametersHook(test_functional.PecanFunctionalTest):

    def test_if_match_on_update(self):
        net_response = jsonutils.loads(self.app.post_json(
            '/v2.0/networks.json',
            params={'network': {'name': 'meh'}},
            headers={'X-Project-Id': 'tenid'}).body)
        network_id = net_response['network']['id']
        response = self.app.put_json('/v2.0/networks/%s.json' % network_id,
                                     params={'network': {'name': 'cat'}},
                                     headers={'X-Project-Id': 'tenid',
                                              'If-Match': 'revision_number=0'},
                                     expect_errors=True)
        # revision plugin not supported by default, so badrequest
        self.assertEqual(400, response.status_int)

class TestQueryParametersHookWithRevision(test_functional.PecanFunctionalTest):

    def setUp(self):
        cfg.CONF.set_override('service_plugins', ['revisions'])
        super(TestQueryParametersHookWithRevision, self).setUp()

    def test_if_match_on_update(self):
        net_response = jsonutils.loads(self.app.post_json(
            '/v2.0/networks.json',
            params={'network': {'name': 'meh'}},
            headers={'X-Project-Id': 'tenid'}).body)
        network_id = net_response['network']['id']
        rev = net_response['network']['revision_number']
        stale = rev - 1

        response = self.app.put_json(
            '/v2.0/networks/%s.json' % network_id,
            params={'network': {'name': 'cat'}},
            headers={'X-Project-Id': 'tenid',
                     'If-Match': 'revision_number=%s' % stale},
            expect_errors=True)
        self.assertEqual(412, response.status_int)
        self.app.put_json('/v2.0/networks/%s.json' % network_id,
                          params={'network': {'name': 'cat'}},
                          headers={'X-Project-Id': 'tenid',
                                   'If-Match': 'revision_number=%s' % rev})

class TestQuotaEnforcementHook(test_functional.PecanFunctionalTest):

    def test_quota_enforcement_single(self):
        ctx = context.get_admin_context()
        quota_driver.DbQuotaDriver.update_quota_limit(
            ctx, 'tenid', 'network', 1)
        # There is enough headroom for creating a network
        response = self.app.post_json(
            '/v2.0/networks.json',
            params={'network': {'name': 'meh'}},
            headers={'X-Project-Id': 'tenid'})
        self.assertEqual(response.status_int, 201)
        # But a second request will fail
        response = self.app.post_json(
            '/v2.0/networks.json',
            params={'network': {'name': 'meh-2'}},
            headers={'X-Project-Id': 'tenid'},
            expect_errors=True)
        self.assertEqual(response.status_int, 409)

    def test_quota_enforcement_bulk_request(self):
        ctx = context.get_admin_context()
        quota_driver.DbQuotaDriver.update_quota_limit(
            ctx, 'tenid', 'network', 3)
        # There is enough headroom for a bulk request creating 2 networks
        response = self.app.post_json(
            '/v2.0/networks.json',
            params={'networks': [
                {'name': 'meh1'},
                {'name': 'meh2'}]},
            headers={'X-Project-Id': 'tenid'})
        self.assertEqual(response.status_int, 201)
        # But it won't be possible to create 2 more networks...
        response = self.app.post_json(
            '/v2.0/networks.json',
            params={'networks': [
                {'name': 'meh3'},
                {'name': 'meh4'}]},
            headers={'X-Project-Id': 'tenid'},
            expect_errors=True)
        self.assertEqual(response.status_int, 409)

class TestPolicyEnforcementHook(test_functional.PecanFunctionalTest):

    FAKE_RESOURCE = {
        'mehs': {
            'id': {'allow_post': False, 'allow_put': False,
                   'is_visible': True, 'primary_key': True},
            'attr': {'allow_post': True, 'allow_put': True,
                     'is_visible': True, 'default': ''},
            'restricted_attr': {'allow_post': True, 'allow_put': True,
                                'is_visible': True, 'default': ''},
            'tenant_id': {'allow_post': True, 'allow_put': False,
                          'required_by_policy': True,
                          'validate': {'type:string':
                                       db_const.PROJECT_ID_FIELD_SIZE},
                          'is_visible': True}
        }
    }

    def setUp(self):
        # Create a controller for a fake resource. This will make the tests
        # independent from the evolution of the API (so if one changes the API
        # or the default policies there won't be any risk of breaking these
        # tests, or at least I hope so)
        super(TestPolicyEnforcementHook, self).setUp()
        self.mock_plugin = mock.Mock()
        attributes.RESOURCES.update(self.FAKE_RESOURCE)
        manager.NeutronManager.set_plugin_for_resource('mehs',
                                                       self.mock_plugin)
        fake_controller = resource.CollectionsController('mehs', 'meh')
        manager.NeutronManager.set_controller_for_resource(
            'mehs', fake_controller)
        # Inject policies for the fake resource
        policy.init()
        policy._ENFORCER.set_rules(
            oslo_policy.Rules.from_dict(
                {'create_meh': '',
                 'update_meh': 'rule:admin_only',
                 'delete_meh': 'rule:admin_only',
                 'get_meh': 'rule:admin_only or field:mehs:id=xxx',
                 'get_meh:restricted_attr': 'rule:admin_only'}),
            overwrite=False)

    def test_before_on_create_authorized(self):
        # Mock a return value for an hypothetical create operation
        self.mock_plugin.create_meh.return_value = {
            'id': 'xxx',
            'attr': 'meh',
            'restricted_attr': '',
            'tenant_id': 'tenid'}
        response = self.app.post_json('/v2.0/mehs.json',
                                      params={'meh': {'attr': 'meh'}},
                                      headers={'X-Project-Id': 'tenid'})
        # We expect this operation to succeed
        self.assertEqual(201, response.status_int)
        self.assertEqual(0, self.mock_plugin.get_meh.call_count)
        self.assertEqual(1, self.mock_plugin.create_meh.call_count)

    def test_before_on_put_not_authorized(self):
        # The policy hook here should load the resource, and therefore we must
        # mock a get response
        self.mock_plugin.get_meh.return_value = {
            'id': 'xxx',
            'attr': 'meh',
            'restricted_attr': '',
            'tenant_id': 'tenid'}
        # The policy engine should trigger an exception in 'before', and the
        # plugin method should not be called at all
        response = self.app.put_json('/v2.0/mehs/xxx.json',
                                     params={'meh': {'attr': 'meh'}},
                                     headers={'X-Project-Id': 'tenid'},
                                     expect_errors=True)
        self.assertEqual(403, response.status_int)
        self.assertEqual(1, self.mock_plugin.get_meh.call_count)
        self.assertEqual(0, self.mock_plugin.update_meh.call_count)

    def test_before_on_put_not_found_when_not_authorized_to_get(self):
        # the user won't even have permission to view this resource
        # so the error on unauthorized updates should be translated into
        # a 404
        self.mock_plugin.get_meh.return_value = {
            'id': 'yyy',
            'attr': 'meh',
            'restricted_attr': '',
            'tenant_id': 'tenid'}
        response = self.app.put_json('/v2.0/mehs/yyy.json',
                                     params={'meh': {'attr': 'meh'}},
                                     headers={'X-Project-Id': 'tenid'},
                                     expect_errors=True)
        self.assertEqual(404, response.status_int)
        self.assertEqual(1, self.mock_plugin.get_meh.call_count)
        self.assertEqual(0, self.mock_plugin.update_meh.call_count)

    def test_before_on_delete_not_authorized(self):
        # The policy hook here should load the resource, and therefore we must
        # mock a get response
        self.mock_plugin.delete_meh.return_value = None
        self.mock_plugin.get_meh.return_value = {
            'id': 'xxx',
            'attr': 'meh',
            'restricted_attr': '',
            'tenant_id': 'tenid'}
        # The policy engine should trigger an exception in 'before', and the
        # plugin method should not be called
        response = self.app.delete_json('/v2.0/mehs/xxx.json',
                                        headers={'X-Project-Id': 'tenid'},
                                        expect_errors=True)
        self.assertEqual(403, response.status_int)
        self.assertEqual(1, self.mock_plugin.get_meh.call_count)
        self.assertEqual(0, self.mock_plugin.delete_meh.call_count)

    def test_after_on_get_not_found(self):
        # The GET test policy will deny access to anything whose id is not
        # 'xxx', so the following request should be forbidden and presented
        # to the user as an HTTPNotFound
        self.mock_plugin.get_meh.return_value = {
            'id': 'yyy',
            'attr': 'meh',
            'restricted_attr': '',
            'tenant_id': 'tenid'}
        # The policy engine should trigger an exception in 'after', and the
        # plugin method should be called
        response = self.app.get('/v2.0/mehs/yyy.json',
                                headers={'X-Project-Id': 'tenid'},
                                expect_errors=True)
        self.assertEqual(404, response.status_int)
        self.assertEqual(1, self.mock_plugin.get_meh.call_count)

    def test_after_on_get_excludes_admin_attribute(self):
        self.mock_plugin.get_meh.return_value = {
            'id': 'xxx',
            'attr': 'meh',
            'restricted_attr': '',
            'tenant_id': 'tenid'}
        response = self.app.get('/v2.0/mehs/xxx.json',
                                headers={'X-Project-Id': 'tenid'})
        self.assertEqual(200, response.status_int)
        json_response = jsonutils.loads(response.body)
        self.assertNotIn('restricted_attr', json_response['meh'])

    def test_after_on_list_excludes_admin_attribute(self):
        self.mock_plugin.get_mehs.return_value = [{
            'id': 'xxx',
            'attr': 'meh',
            'restricted_attr': '',
            'tenant_id': 'tenid'}]
        response = self.app.get('/v2.0/mehs',
                                headers={'X-Project-Id': 'tenid'})
        self.assertEqual(200, response.status_int)
        json_response = jsonutils.loads(response.body)
        self.assertNotIn('restricted_attr', json_response['mehs'][0])

    def test_after_inits_policy(self):
        self.mock_plugin.get_mehs.return_value = [{
            'id': 'xxx',
            'attr': 'meh',
            'restricted_attr': '',
            'tenant_id': 'tenid'}]
        policy.reset()
        response = self.app.get('/v2.0/mehs',
                                headers={'X-Project-Id': 'tenid'})
        self.assertEqual(200, response.status_int)

class TestMetricsNotifierHook(test_functional.PecanFunctionalTest):

    def setUp(self):
        patcher = mock.patch('neutron.pecan_wsgi.hooks.notifier.NotifierHook.'
                             '_notifier')
        self.mock_notifier = patcher.start().info
        super(TestMetricsNotifierHook, self).setUp()

    def test_post_put_delete_triggers_notification(self):
        req_headers = {'X-Project-Id': 'tenid', 'X-Roles': 'admin'}
        payload = {'network': {'name': 'meh'}}
        response = self.app.post_json(
            '/v2.0/networks.json',
            params=payload, headers=req_headers)
        self.assertEqual(201, response.status_int)
        json_body = jsonutils.loads(response.body)
        self.assertEqual(
            [mock.call(mock.ANY, 'network.create.start', payload),
             mock.call(mock.ANY, 'network.create.end', json_body)],
            self.mock_notifier.mock_calls)
        self.mock_notifier.reset_mock()
        network_id = json_body['network']['id']

        payload = {'network': {'name': 'meh-2'}}
        response = self.app.put_json(
            '/v2.0/networks/%s.json' % network_id,
            params=payload, headers=req_headers)
        self.assertEqual(200, response.status_int)
        json_body = jsonutils.loads(response.body)
        # id should be in payload sent to notifier
        payload['id'] = network_id
        self.assertEqual(
            [mock.call(mock.ANY, 'network.update.start', payload),
             mock.call(mock.ANY, 'network.update.end', json_body)],
            self.mock_notifier.mock_calls)
        self.mock_notifier.reset_mock()

        before_payload = {'network_id': network_id}
        after_payload = before_payload.copy()
        after_payload['network'] = directory.get_plugin().get_network(
            context.get_admin_context(), network_id)
        response = self.app.delete(
            '/v2.0/networks/%s.json' % network_id, headers=req_headers)
        self.assertEqual(204, response.status_int)
        self.assertEqual(
            [mock.call(mock.ANY, 'network.delete.start', before_payload),
             mock.call(mock.ANY, 'network.delete.end', after_payload)],
            self.mock_notifier.mock_calls)

    def test_bulk_create_triggers_notification(self):
        req_headers = {'X-Project-Id': 'tenid', 'X-Roles': 'admin'}
        payload = {'networks': [{'name': 'meh_1'}, {'name': 'meh_2'}]}
        response = self.app.post_json(
            '/v2.0/networks.json',
            params=payload,
            headers=req_headers)
        self.assertEqual(201, response.status_int)
        json_body = jsonutils.loads(response.body)
        self.assertEqual(2, self.mock_notifier.call_count)
        self.mock_notifier.assert_has_calls(
            [mock.call(mock.ANY, 'network.create.start', payload),
             mock.call(mock.ANY, 'network.create.end', json_body)])

    def test_bad_create_doesnt_emit_end(self):
        req_headers = {'X-Project-Id': 'tenid', 'X-Roles': 'admin'}
        payload = {'network': {'name': 'meh'}}
        plugin = directory.get_plugin()
        with mock.patch.object(plugin, 'create_network',
                               side_effect=ValueError):
            response = self.app.post_json(
                '/v2.0/networks.json',
                params=payload, headers=req_headers,
                expect_errors=True)
        self.assertEqual(500, response.status_int)
        self.assertEqual(
            [mock.call(mock.ANY, 'network.create.start', mock.ANY)],
            self.mock_notifier.mock_calls)

    def test_bad_update_doesnt_emit_end(self):
        req_headers = {'X-Project-Id': 'tenid', 'X-Roles': 'admin'}
        payload = {'network': {'name': 'meh'}}
        response = self.app.post_json(
            '/v2.0/networks.json',
            params=payload, headers=req_headers,
            expect_errors=True)
        self.assertEqual(201, response.status_int)
        json_body = jsonutils.loads(response.body)
        self.mock_notifier.reset_mock()
        plugin = directory.get_plugin()
        with mock.patch.object(plugin, 'update_network',
                               side_effect=ValueError):
            response = self.app.put_json(
                '/v2.0/networks/%s.json' % json_body['network']['id'],
                params=payload, headers=req_headers,
                expect_errors=True)
            self.assertEqual(500, response.status_int)
        self.assertEqual(
            [mock.call(mock.ANY, 'network.update.start', mock.ANY)],
            self.mock_notifier.mock_calls)

    def test_bad_delete_doesnt_emit_end(self):
        req_headers = {'X-Project-Id': 'tenid', 'X-Roles': 'admin'}
        payload = {'network': {'name': 'meh'}}
        response = self.app.post_json(
            '/v2.0/networks.json',
            params=payload, headers=req_headers,
            expect_errors=True)
        self.assertEqual(201, response.status_int)
        json_body = jsonutils.loads(response.body)
        self.mock_notifier.reset_mock()
        plugin = directory.get_plugin()
        with mock.patch.object(plugin, 'delete_network',
                               side_effect=ValueError):
            response = self.app.delete(
                '/v2.0/networks/%s.json' % json_body['network']['id'],
                headers=req_headers, expect_errors=True)
            self.assertEqual(500, response.status_int)
        self.assertEqual(
            [mock.call(mock.ANY, 'network.delete.start', mock.ANY)],
            self.mock_notifier.mock_calls)

class TestCallbackRegistryNotifier(test_functional.PecanFunctionalTest):

    def setUp(self):
        super(TestCallbackRegistryNotifier, self).setUp()
        patcher = mock.patch('neutron.pecan_wsgi.hooks.notifier.registry')
        self.mock_notifier = patcher.start().publish

    def _create(self, bulk=False):
        if bulk:
            body = {'networks': [{'name': 'meh-1'}, {'name': 'meh-2'}]}
        else:
            body = {'network': {'name': 'meh-1'}}
        response = self.app.post_json(
            '/v2.0/networks.json',
            params=body, headers={'X-Project-Id': 'tenid'})
        return response.json

    def test_create(self):
        self._create()
        self.mock_notifier.assert_called_once_with(
            'network', events.BEFORE_RESPONSE, mock.ANY, payload=mock.ANY)

        payload = self.mock_notifier.call_args[1]['payload']
        self.assertEqual('network.create.end', payload.method_name)
        self.assertEqual('create_network', payload.action)
        self.assertEqual('networks', payload.collection_name)

        actual = payload.latest_state
        self.assertEqual('meh-1', actual['network']['name'])

    def test_create_bulk(self):
        self._create(bulk=True)
        self.mock_notifier.assert_called_once_with(
            'network', events.BEFORE_RESPONSE, mock.ANY, payload=mock.ANY)

        payload = self.mock_notifier.call_args[1]['payload']
        self.assertEqual('network.create.end', payload.method_name)
        self.assertEqual('create_network', payload.action)
        self.assertEqual('networks', payload.collection_name)
        actual = payload.latest_state
        self.assertEqual(2, len(actual['networks']))
        self.assertEqual('meh-1', actual['networks'][0]['name'])
        self.assertEqual('meh-2', actual['networks'][1]['name'])

    def test_update(self):
        network_id = self._create()['network']['id']
        self.mock_notifier.reset_mock()
        self.app.put_json('/v2.0/networks/%s.json' % network_id,
                          params={'network': {'name': 'new-meh'}},
                          headers={'X-Project-Id': 'tenid'})
        self.mock_notifier.assert_called_once_with(
            'network', events.BEFORE_RESPONSE, mock.ANY, payload=mock.ANY)

        payload = self.mock_notifier.call_args[1]['payload']
        self.assertEqual('network.update.end', payload.method_name)
        self.assertEqual('update_network', payload.action)
        self.assertEqual('networks', payload.collection_name)

        actual_new = payload.latest_state
        self.assertEqual('new-meh', actual_new['network']['name'])
        actual_original = payload.states[0]
        self.assertEqual(network_id, actual_original['id'])

    def test_delete(self):
        network_id = self._create()['network']['id']
        self.mock_notifier.reset_mock()
        self.app.delete(
            '/v2.0/networks/%s.json' % network_id,
            headers={'X-Project-Id': 'tenid'})
        self.mock_notifier.assert_called_once_with(
            'network', events.BEFORE_RESPONSE, mock.ANY, payload=mock.ANY)

        payload = self.mock_notifier.call_args[1]['payload']
        self.assertEqual('network.delete.end', payload.method_name)
        self.assertEqual('delete_network', payload.action)
        self.assertEqual('networks', payload.collection_name)

        actual = payload.latest_state
        self.assertEqual(network_id, actual['network']['id'])


text:
package com.github.tommykw.sample;

import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;

/**
 * fab-flex interface
 */
public interface FabFlex {
    void setDrawable(Drawable drawable);
    void setColor(@ColorInt int color);
    void setFabKind(@FabSourceKind int fabKind);
    Drawable getDrawable();
    @ColorInt int getColor();
    @FabSourceKind int getFabKind();

}


text:
using System;
using System.Linq;
using Marten.Linq;
using Marten.Schema;
using Marten.Schema.Identity;
using Marten.Services;
using Marten.Testing.Documents;
using Npgsql;
using NpgsqlTypes;
using Shouldly;
using Xunit;

namespace Marten.Testing
{
    public class StoreOptionsTests
    {
        [Fact]
        public void add_document_types()
        {
            var options = new StoreOptions();
            options.RegisterDocumentType<User>();
            options.RegisterDocumentType(typeof(Company));
            options.RegisterDocumentTypes(new Type[] {typeof(Target), typeof(Issue)});

            options.AllDocumentMappings.OrderBy(x => x.DocumentType.Name).Select(x => x.DocumentType.Name)
                .ShouldHaveTheSameElementsAs("Company", "Issue", "Target", "User");
        }

        [Fact]
        public void default_logger_is_the_nullo()
        {
            var options = new StoreOptions();
            options.Logger().ShouldBeOfType<NulloMartenLogger>();

            options.Logger(null);

            // doesn't matter, nullo is the default
            options.Logger().ShouldBeOfType<NulloMartenLogger>();
        }

        [Fact]
        public void can_overwrite_the_logger()
        {
            var logger = new ConsoleMartenLogger();

            var options = new StoreOptions();
            options.Logger(logger);

            options.Logger().ShouldBeSameAs(logger);
        }

        public void using_console_logger()
        {
            // SAMPLE: plugging-in-marten-logger
            var store = DocumentStore.For(_ =>
            {
                _.Logger(new ConsoleMartenLogger());
            });
            // ENDSAMPLE

            // SAMPLE: plugging-in-session-logger
            using (var session = store.OpenSession())
            {
                // Replace the logger for only this one session
                session.Logger = new RecordingLogger();
            }
            // ENDSAMPLE
        }

        [Fact]
        public void default_ddl_rules()
        {
            var options = new StoreOptions();

            options.DdlRules.TableCreation.ShouldBe(CreationStyle.DropThenCreate);
            options.DdlRules.UpsertRights.ShouldBe(SecurityRights.Invoker);
        }

        public class FakeUserStorage : IDocumentStorage, IdAssignment<User>
        {
            public Type DocumentType { get; } = typeof (User);
            public NpgsqlDbType IdType { get; }
            public NpgsqlCommand LoaderCommand(object id)
            {
                throw new NotImplementedException();
            }

            public NpgsqlCommand DeleteCommandForId(object id)
            {
                throw new NotImplementedException();
            }

            public NpgsqlCommand DeleteCommandForEntity(object entity)
            {
                throw new NotImplementedException();
            }

            public NpgsqlCommand LoadByArrayCommand<TKey>(TKey[] ids)
            {
                throw new NotImplementedException();
            }

            public object Identity(object document)
            {
                throw new NotImplementedException();
            }

            public void RegisterUpdate(UpdateBatch batch, object entity)
            {
                throw new NotImplementedException();
            }

            public void RegisterUpdate(UpdateBatch batch, object entity, string json)
            {
                throw new NotImplementedException();
            }

            public void Remove(IIdentityMap map, object entity)
            {
                throw new NotImplementedException();
            }

            public void Delete(IIdentityMap map, object id)
            {
                throw new NotImplementedException();
            }

            public void Store(IIdentityMap map, object id, object entity)
            {
                throw new NotImplementedException();
            }

            public IStorageOperation DeletionForId(object id)
            {
                throw new NotImplementedException();
            }

            public IStorageOperation DeletionForEntity(object entity)
            {
                throw new NotImplementedException();
            }

            public IStorageOperation DeletionForWhere(IWhereFragment @where)
            {
                throw new NotImplementedException();
            }

            public object Assign(User document, out bool assigned)
            {
                throw new NotImplementedException();
            }

            public void Assign(User document, object id)
            {
                document.Id = (Guid) id;
            }
        }

        public class FakeCompanyStorage : IDocumentStorage, IdAssignment<Company>
        {
            public Type DocumentType { get; } = typeof (Company);
            public NpgsqlDbType IdType { get; }
            public NpgsqlCommand LoaderCommand(object id)
            {
                throw new NotImplementedException();
            }

            public NpgsqlCommand DeleteCommandForId(object id)
            {
                throw new NotImplementedException();
            }

            public NpgsqlCommand DeleteCommandForEntity(object entity)
            {
                throw new NotImplementedException();
            }

            public NpgsqlCommand LoadByArrayCommand<TKey>(TKey[] ids)
            {
                throw new NotImplementedException();
            }

            public object Identity(object document)
            {
                throw new NotImplementedException();
            }

            public void RegisterUpdate(UpdateBatch batch, object entity)
            {
                throw new NotImplementedException();
            }

            public void RegisterUpdate(UpdateBatch batch, object entity, string json)
            {
                throw new NotImplementedException();
            }

            public void Remove(IIdentityMap map, object entity)
            {
                throw new NotImplementedException();
            }

            public void Delete(IIdentityMap map, object id)
            {
                throw new NotImplementedException();
            }

            public void Store(IIdentityMap map, object id, object entity)
            {
                throw new NotImplementedException();
            }

            public IStorageOperation DeletionForId(object id)
            {
                throw new NotImplementedException();
            }

            public IStorageOperation DeletionForEntity(object entity)
            {
                throw new NotImplementedException();
            }

            public IStorageOperation DeletionForWhere(IWhereFragment @where)
            {
                throw new NotImplementedException();
            }

            public object Assign(Company document, out bool assigned)
            {
                throw new NotImplementedException();
            }

            public void Assign(Company document, object id)
            {
                document.Id = (Guid) id;
            }
        }

        [Fact]
        public void default_name_data_length_is_64()
        {
            new StoreOptions().NameDataLength.ShouldBe(64);
        }

        [Fact]
        public void assert_identifier_length_happy_path()
        {
            var options = new StoreOptions();

            for (var i = 1; i < options.NameDataLength; i++)
            {
                var text = new string('a', i);

                options.AssertValidIdentifier(text);
            }
        }

        [Fact]
        public void assert_identifier_must_not_contain_space()
        {
            var random = new Random();
            var options = new StoreOptions();

            for (var i = 1; i < options.NameDataLength; i++)
            {
                var text = new string('a', i);
                var position = random.Next(0, i);

                Exception<PostgresqlIdentifierInvalidException>.ShouldBeThrownBy(() =>
                {
                    options.AssertValidIdentifier(text.Remove(position).Insert(position, " "));
                });
            }
        }

        [Fact]
        public void assert_identifier_null_or_whitespace()
        {
            var options = new StoreOptions();

            Exception<PostgresqlIdentifierInvalidException>.ShouldBeThrownBy(() =>
            {
                options.AssertValidIdentifier(null);
            });

            for (var i = 0; i < options.NameDataLength; i++)
            {
                var text = new string(' ', i);

                Exception<PostgresqlIdentifierInvalidException>.ShouldBeThrownBy(() =>
                {
                    options.AssertValidIdentifier(text);
                });
            }
        }

        [Fact]
        public void assert_identifier_length_exceeding_maximum()
        {
            var options = new StoreOptions();

            var text = new string('a', options.NameDataLength);

            Exception<PostgresqlIdentifierTooLongException>.ShouldBeThrownBy(() =>
            {
                options.AssertValidIdentifier(text);
            });
        }

        public void set_the_maximum_name_length()
        {
            // SAMPLE: setting-name-data-length
            var store = DocumentStore.For(_ =>
            {
                // If you have overridden NAMEDATALEN in your
                // Postgresql database to 100
                _.NameDataLength = 100;
            });
            // ENDSAMPLE
        }
    }
}


text:
/**
 * Module dependencies.
 */

var pathRegexp = require('path-to-regexp');
var debug = require('debug')('express:router:layer');

/**
 * Module variables.
 */

var hasOwnProperty = Object.prototype.hasOwnProperty;

/**
 * Expose `Layer`.
 */

module.exports = Layer;

function Layer(path, options, fn) {
  if (!(this instanceof Layer)) {
    return new Layer(path, options, fn);
  }

  debug('new %s', path);
  options = options || {};

  this.handle = fn;
  this.name = fn.name || '<anonymous>';
  this.params = undefined;
  this.path = undefined;
  this.regexp = pathRegexp(path, this.keys = [], options);

  if (path === '/' && options.end === false) {
    this.regexp.fast_slash = true;
  }
}

/**
 * Handle the error for the layer.
 *
 * @param {Error} error
 * @param {Request} req
 * @param {Response} res
 * @param {function} next
 * @api private
 */

Layer.prototype.handle_error = function handle_error(error, req, res, next) {
  var fn = this.handle;

  if (fn.length !== 4) {
    // not a standard error handler
    return next(error);
  }

  try {
    fn(error, req, res, next);
  } catch (err) {
    next(err);
  }
};

/**
 * Handle the request for the layer.
 *
 * @param {Request} req
 * @param {Response} res
 * @param {function} next
 * @api private
 */

Layer.prototype.handle_request = function handle(req, res, next) {
  var fn = this.handle;

  if (fn.length > 3) {
    // not a standard request handler
    return next();
  }

  try {
    fn(req, res, next);
  } catch (err) {
    next(err);
  }
};

/**
 * Check if this route matches `path`, if so
 * populate `.params`.
 *
 * @param {String} path
 * @return {Boolean}
 * @api private
 */

Layer.prototype.match = function match(path) {
  if (path == null) {
    // no path, nothing matches
    this.params = undefined;
    this.path = undefined;
    return false;
  }

  if (this.regexp.fast_slash) {
    // fast path non-ending match for / (everything matches)
    this.params = {};
    this.path = '';
    return true;
  }

  var m = this.regexp.exec(path);

  if (!m) {
    this.params = undefined;
    this.path = undefined;
    return false;
  }

  // store values
  this.params = {};
  this.path = m[0];

  var keys = this.keys;
  var params = this.params;
  var prop;
  var n = 0;
  var key;
  var val;

  for (var i = 1, len = m.length; i < len; ++i) {
    key = keys[i - 1];
    prop = key
      ? key.name
      : n++;
    val = decode_param(m[i]);

    if (val !== undefined || !(hasOwnProperty.call(params, prop))) {
      params[prop] = val;
    }
  }

  return true;
};

/**
 * Decode param value.
 *
 * @param {string} val
 * @return {string}
 * @api private
 */

function decode_param(val){
  if (typeof val !== 'string') {
    return val;
  }

  try {
    return decodeURIComponent(val);
  } catch (e) {
    var err = new TypeError("Failed to decode param '" + val + "'");
    err.status = 400;
    throw err;
  }
}


text:
namespace Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Details about the API request error.
    /// </summary>
    public partial class ComputerVisionOcrError
    {
        /// <summary>
        /// Initializes a new instance of the ComputerVisionOcrError class.
        /// </summary>
        public ComputerVisionOcrError()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ComputerVisionOcrError class.
        /// </summary>
        /// <param name="code">The error code.</param>
        /// <param name="message">A message explaining the error reported by
        /// the service.</param>
        /// <param name="requestId">A unique request identifier.</param>
        public ComputerVisionOcrError(object code, string message, string requestId = default(string))
        {
            Code = code;
            Message = message;
            RequestId = requestId;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the error code.
        /// </summary>
        [JsonProperty(PropertyName = "code")]
        public object Code { get; set; }

        /// <summary>
        /// Gets or sets a message explaining the error reported by the
        /// service.
        /// </summary>
        [JsonProperty(PropertyName = "message")]
        public string Message { get; set; }

        /// <summary>
        /// Gets or sets a unique request identifier.
        /// </summary>
        [JsonProperty(PropertyName = "requestId")]
        public string RequestId { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Code == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Code");
            }
            if (Message == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Message");
            }
        }
    }
}


text:
 if [ "$#" -eq 2 ]; then

   COMPONENT=$1
   LEG=$2

   EXP=t001
   ECEDIR=/lustre3/projects/CMIP6/reerink/ec-earth-3/trunk/$EXP/output/$COMPONENT/$LEG
   ECEMODEL=EC-EARTH-AOGCM
   METADATA=/nfs/home/users/reerink/ec-earth-3/trunk/runtime/classic/ctrl/cmip6-output-control-files/CMIP/EC-EARTH-AOGCM/cmip6-experiment-CMIP-piControl/metadata-cmip6-CMIP-piControl-EC-EARTH-AOGCM-$COMPONENT-template.json
   TEMPDIR=/lustre3/projects/CMIP6/reerink/temp-cmor-dir/$EXP/$COMPONENT/$LEG
   VARLIST=/nfs/home/users/reerink/ec-earth-3/trunk/runtime/classic/ctrl/cmip6-output-control-files/test-all-ece-mip-variables/ece-cmip6-data-request-varlist-all-EC-EARTH-AOGCM.json
   ODIR=/lustre3/projects/CMIP6/reerink/cmorised-results/cmor-cmip-test-all/$EXP

   if [ ! -d "$ECEDIR"       ]; then echo "Error: EC-Earth3 data output directory: " $ECEDIR " does not exist. Aborting job: " $0 >&2; exit 1; fi
   if [ ! "$(ls -A $ECEDIR)" ]; then echo "Error: EC-Earth3 data output directory: " $ECEDIR " is empty. Aborting job:" $0 >&2; exit 1; fi

   mkdir -p $ODIR
   if [ -d $TEMPDIR ]; then rm -rf $TEMPDIR; fi
   mkdir -p $TEMPDIR

   source /lustre2/projects/model_testing/reerink/miniconda2/etc/profile.d/conda.sh
   conda activate ece2cmor3

   export HDF5_USE_FILE_LOCKING=FALSE
   export UVCDAT_ANONYMOUS_LOG=false
  #export ECE2CMOR3_IFS_CLEANUP=FALSE

   ece2cmor $ECEDIR --exp               $EXP      \
                    --ececonf           $ECEMODEL \
                    --$COMPONENT                  \
                    --meta              $METADATA \
                    --varlist           $VARLIST  \
                    --tmpdir            $TEMPDIR  \
                    --odir              $ODIR     \
                    --npp               28        \
                    --overwritemode     replace   \
                    --skip_alevel_vars            \
                    --log

   mkdir -p $ODIR/logs
   mv -f $EXP-$COMPONENT-$LEG-*.log $ODIR/logs/
  #if [ -d $TEMPDIR ]; then rm -rf $TEMPDIR; fi

   # Launching the next job for the next leg:
   arg0=$0
   arg1=$1
   arg2previous=$2
   arg2next=$((10#${arg2previous}+16))  # Note +8 combines with the {nemo,ifs}-for-loop example below to 16 simultaneous jobs
   arg2=$(printf %.3d ${arg2next} )
   if [ ${arg2next} -lt 30 ] ; then
    echo ' A next job is launched:'
    echo ' ' sbatch --job-name=cmorise-${arg1}-${arg2} ${arg0} ${arg1} ${arg2}
    sbatch --job-name=cmorise-${arg1}-${arg2} ${arg0} ${arg1} ${arg2}
   else
    echo ' No next job is launched.'
   fi

 else
  echo
  echo '  Illegal number of arguments: the script requires two arguments:'
  echo '   1st argument: model component'
  echo '   2nd argument: leg'
  echo '  For instance:'
  echo '   sbatch ' $0 ' ifs 001'
  echo '  Or use:'
  echo '   for j in {001..015}; do sbatch --job-name=cmorise-ifs-$j  ' $0 ' ifs  $j; done'
  echo '   for j in {001..015}; do sbatch --job-name=cmorise-nemo-$j ' $0 ' nemo $j; done'
  echo
 fi


text:
from __future__ import division, print_function, unicode_literals

# collision_model tests

# circles1 test
import cocos.collision_model as cm
import cocos.euclid as eu
from math import sin, cos, radians

class Obj_with_shape(object):
    def __init__(self, name, cshape):
        self.name = name
        self.cshape = cshape

def create_obj_with_circle(name, center, r):
    shape = cm.CircleShape(center, r)
    obj = Obj_with_shape(name, shape)
    return obj

def pprint_container(heading, container):
    sl = [s.name for s in container]
    sl.sort()
    print(heading)
    for s in sl:
        print("\t%s"%s)

# see circle1_data.png for visualization, was ploted with func
# plot_circle_data1
def circle_data1(offset):
    r1 = 1.5
    center = eu.Vector2(0.0, 0.0) + offset

    center_circle = create_obj_with_circle('center', center, r1)

    r2 = 0.3
    d1 = (r1 + r2) - 0.1
    angles = [a for a in range(360, 1, -360//12)]
    ring_touching = set()
    for a in angles:
        center = d1 * eu.Vector2(cos(radians(a)), sin(radians(a))) + offset
        circle = create_obj_with_circle("ring_touching, distance 0.0, angle %3s"%a, center, r2)
        ring_touching.add(circle)

    near_distance = 0.1
    d2 = (r1 + r2) + near_distance
    angles = [a for a in range(360, 1, -360//12)]
    ring_near = set()
    for a in angles:
        center = d2 * eu.Vector2(cos(radians(a)), sin(radians(a))) + offset
        circle = create_obj_with_circle("ring_near, distance 0.1, angle %3s"%a,
                                        center, r2)
        ring_near.add(circle)

    far_distance = 0.2
    d3 = (r1 + r2) + far_distance
    angles = [a for a in range(360, 1, -360//12)]
    ring_far = set()
    for a in angles:
        center = d3 * eu.Vector2(cos(radians(a)), sin(radians(a))) + offset
        circle = create_obj_with_circle("ring_far, distance 0.2, angle %3s"%a,
                                        center, r2)
        ring_far.add(circle)

    return (center_circle, ring_touching, ring_near, ring_far,
            near_distance, far_distance, angles)

def plot_circle_data1(offset):
    (center_circle, ring_touching, ring_near, ring_far,
     near_distance, far_distance, angles) = circle_data1(offset)

    def get_params(obj):
        x, y = obj.cshape.center
        return obj.name, x, y, obj.cshape.r

    import pylab
    fig = pylab.figure(figsize=(6.0, 6.0)) #size in inches
    fig.suptitle('circle_data1', fontsize=12)
    pylab.axes().set_aspect('equal') # aspect ratio

    name, x, y, r = get_params(center_circle)
    cir = pylab.Circle((x,y), radius=r,  ec='black', fc='none')
    pylab.gca().add_patch(cir)
    xmax = r

    for ring, color in [ (ring_touching, 'r'), (ring_near, 'g'),
                         (ring_far, 'b') ]:
        for obj in ring:
            name, x, y, r = get_params(obj)
            cir = pylab.Circle((x,y), radius=r,  ec=color, fc='none')
            pylab.gca().add_patch(cir)
    ymin = -(xmax + (2*r + far_distance)*3)
    xmax = xmax + (2*r + far_distance)*2

    # axis: xmin, xmax, ymin, ymax
    pylab.axis([-xmax, xmax, ymin, xmax])

    # make legends
    labels = ['center_circle', 'overlapping ring', 'near ring', 'far ring']
    colors = ['black', 'r', 'g', 'b' ]
    dummys = [ pylab.Line2D([0,1], [0,1], lw=2.0, c=e) for e in colors]
    pylab.gca().legend(dummys, labels, ncol=2, loc='lower center')

    #pylab.show()
    pylab.savefig('circle1_data.png')

def pytest_generate_tests(metafunc):
    param_names = ['variant', 'ctor_args', 'offset']
    cases = {
        "BruteForce":
            ('CollisionManagerBruteForce', [], (2.2, 3.7)),
        "Grid, target don't crosses bucket edges":
            ('CollisionManagerGrid',
             [0.0, 100.0, 0.0, 100.0, 4.0, 4.0],
             (2.0, 2.0)
             ),
        "Grid, target crosses horizontal bucket edge":
            ('CollisionManagerGrid',
             [0.0, 100.0, 0.0, 100.0, 4.0, 4.0],
             (2.0, 4.0)
             ),
        "Grid, target crosses vertical bucket edge":
            ('CollisionManagerGrid',
             [0.0, 100.0, 0.0, 100.0, 4.0, 4.0],
             (4.0, 2.0)
             ),
        "Grid, target crosses vertical and horizontal bucket edges":
            ('CollisionManagerGrid',
             [0.0, 100.0, 0.0, 100.0, 4.0, 4.0],
             (4.0, 4.0)
             ),
        "Grid, target bigger than cell":
            ('CollisionManagerGrid',
             [0.0, 100.0, 0.0, 100.0, 2.0, 2.0],
             (2.0, 2.0)
             ),
        }

    for name in cases:
        metafunc.addcall(id=name, funcargs=dict(zip(param_names, cases[name])))

fe = 1.0e-4
def test_collman_circles(variant, ctor_args, offset):
    """
    Tests collision manager basic behavoir when shape is circle,
    test data is defined by circle_data1(offset),
    the collision manager variant is determined by 'variant',
    and 'ctor_args' provide the parameters needed to instantiate the
    collision manager.

    'variant' is the class name to use, and the class definition is assumed
    to be in the module cocos.collision_model
    """
    emptyset = set()
    (center_circle, ring_touching, ring_near, ring_far,
     near_distance, far_distance, angles) = circle_data1(eu.Vector2(*offset))

    collman_cls = getattr(cm, variant)
    collman = collman_cls(*ctor_args)

    collman.add(center_circle)
    for ring in [ ring_touching, ring_near, ring_far ]:
        for circle in ring:
            collman.add(circle)

    # all objs in data1 are known
    assert collman.knows(center_circle)
    for ring in [ ring_touching, ring_near, ring_far ]:
        for circle in ring:
            collman.knows(circle)

    # the set of know objects is exactly the set of objects in data1
    assert collman.known_objs() == (set([center_circle]) | ring_touching |
                                  ring_near | ring_far)

    touching_result = collman.objs_colliding(center_circle)

    # no repetitions
    touching = set(touching_result)
    assert len(touching) == len(touching_result)

    # obj is not in objs_colliding_with(obj)
    assert center_circle not in touching

    # any in ring_touching is touching
    assert ring_touching <= touching

    # none of ring_near touches
    assert (ring_near & touching) == emptyset

    # none of ring_far touches
    assert (ring_far & touching) == emptyset

    # no extraneous values in touching
    assert ring_touching == touching

    # the generator form of touching gives same result than objs_colliding
    touching_from_generator = [e for e in collman.iter_colliding(center_circle)]
    assert len(touching_from_generator) == len(touching)
    assert set(touching_from_generator) == touching

    # test with short near_distance, should be same as before
    short_distance = 0.9 * near_distance
    nears1_result = collman.objs_near(center_circle, short_distance)
    #  no repetitions
    nears1 = set(nears1_result)
    assert len(nears1) == len(nears1_result)
    #  expected due to short near_distance
    assert nears1 == ring_touching

    # similar using objs_near_wdistance
    od_list = collman.objs_near_wdistance(center_circle, short_distance)
    assert len(od_list) == len(ring_touching)
    assert set([a for a,b in od_list]) == ring_touching
    # and distances are near 0.0
    for a,d in od_list:
        assert abs(d-0.0)<fe

    # test with near distance to accept ring_near and reject ring_far
    n_distance = 0.9*near_distance + 0.1*far_distance
    nears2 = set(collman.objs_near(center_circle, n_distance))
    assert (ring_far & nears2) == emptyset
    pprint_container('nears2:', nears2)
    pprint_container('ring_near', ring_near)
    assert nears2 == (ring_touching | ring_near)

    # similar using objs_near_wdistance
    od_list = collman.objs_near_wdistance(center_circle, n_distance)
    nears2 = set(od_list)
    assert len(od_list) == len(nears2)
    assert set([a for a,b in od_list]) == (ring_touching | ring_near)
    # and distances match
    for a,d in od_list:
        assert ((a in ring_touching and abs(d) < fe) or
                (a in ring_near and abs(d-near_distance)<fe))

    # all_collisions
    li_touching_center = []
    d = {}
    for a in angles:
        d[" angle %3s"%a] = []

    for obj, other in collman.iter_all_collisions():
        # no collision with itself
        assert obj is not other
        if obj.name == 'center' or other.name == 'center':
            if obj.name == 'center':
                li_touching_center.append(other)
            else:
                li_touching_center.append(obj)
        else:
            obj_ring, obj_distance, obj_angle = obj.name.split(',')
            other_ring, other_distance, other_angle = obj.name.split(',')
            assert obj_angle == other_angle
            assert obj_angle in d
            if id(obj)>id(other):
                obj, other = other, obj
            d[obj_angle].append((obj, other))

    #      the ones touching center are correct
    assert len(li_touching_center) == len(touching)
    assert set(li_touching_center) == touching

    #      all the others
    for k in d:
        # no repetitions
        li = d[k]; si = set(li)
        assert len(li) == len(si)
        # all collisions for the angle
        assert len(si) == 3

    # removing center_circle
    collman.remove_tricky(center_circle)
    assert not collman.knows(center_circle)
    assert center_circle not in collman.known_objs()
    assert collman.known_objs() == (ring_touching | ring_near | ring_far)

    # any_near, with obj not known
    r = center_circle.cshape.r
    small = create_obj_with_circle('small', center_circle.cshape.center,
                                    r - near_distance*2.0)
    #   param 'near_distance' selected to obtain return None
    assert collman.any_near(small, near_distance/2.0) is None

    #   param 'near_distance' selected to obtain  a known object (weak)
    assert collman.any_near(small, near_distance*2.1) is not None

    # any near with known object
    collman.add(small)
    assert collman.any_near(small, near_distance/2.0) is None

#plot_circle_data1(eu.Vector2(0.0, 0.0))