text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<TITLE>Man page of EPOLL</TITLE>

EPOLL

Section: Linux Programmer's Manual (7)
Updated: 2014-07-08
Index
Return to Main Contents

NAME

epoll - I/O event notification facility

SYNOPSIS

#include <sys/epoll.h>

DESCRIPTION

The
epoll

API performs a similar task to
poll(2):

monitoring multiple file descriptors to see if I/O is possible on any of them.
The
epoll

API can be used either as an edge-triggered or a level-triggered
interface and scales well to large numbers of watched file descriptors.
The following system calls are provided to
create and manage an
epoll

instance:

*

epoll_create(2)

creates an
epoll

instance and returns a file descriptor referring to that instance.
(The more recent
epoll_create1(2)

extends the functionality of
epoll_create(2).)

*

Interest in particular file descriptors is then registered via
epoll_ctl(2).

The set of file descriptors currently registered on an
epoll

instance is sometimes called an
epoll

set.

*

epoll_wait(2)

waits for I/O events,
blocking the calling thread if no events are currently available.

Level-triggered and edge-triggered

The
epoll

event distribution interface is able to behave both as edge-triggered
(ET) and as level-triggered (LT).
The difference between the two mechanisms
can be described as follows.
Suppose that
this scenario happens:

1.

The file descriptor that represents the read side of a pipe
(rfd)

is registered on the
epoll

instance.

2.

A pipe writer writes 2 kB of data on the write side of the pipe.

3.

A call to
epoll_wait(2)

is done that will return
rfd

as a ready file descriptor.

4.

The pipe reader reads 1 kB of data from
rfd.

5.

A call to
epoll_wait(2)

is done.

If the
rfd

file descriptor has been added to the
epoll

interface using the
EPOLLET

(edge-triggered)
flag, the call to
epoll_wait(2)

done in step
5

will probably hang despite the available data still present in the file
input buffer;
meanwhile the remote peer might be expecting a response based on the
data it already sent.
The reason for this is that edge-triggered mode
delivers events only when changes occur on the monitored file descriptor.
So, in step
5

the caller might end up waiting for some data that is already present inside
the input buffer.
In the above example, an event on
rfd

will be generated because of the write done in
2

and the event is consumed in
3.

Since the read operation done in
4

does not consume the whole buffer data, the call to
epoll_wait(2)

done in step
5

might block indefinitely.

An application that employs the
EPOLLET

flag should use nonblocking file descriptors to avoid having a blocking
read or write starve a task that is handling multiple file descriptors.
The suggested way to use
epoll

as an edge-triggered
(EPOLLET)

interface is as follows:

i

with nonblocking file descriptors; and

ii

by waiting for an event only after
read(2)

or
write(2)

return
EAGAIN.

By contrast, when used as a level-triggered interface
(the default, when
EPOLLET

is not specified),
epoll

is simply a faster
poll(2),

and can be used wherever the latter is used since it shares the
same semantics.

Since even with edge-triggered
epoll,

multiple events can be generated upon receipt of multiple chunks of data,
the caller has the option to specify the
EPOLLONESHOT

flag, to tell
epoll

to disable the associated file descriptor after the receipt of an event with
epoll_wait(2).

When the
EPOLLONESHOT

flag is specified,
it is the caller's responsibility to rearm the file descriptor using
epoll_ctl(2)

with
EPOLL_CTL_MOD.

Interaction with autosleep

If the system is in
autosleep

mode via
/sys/power/autosleep

and an event happens which wakes the device from sleep, the device
driver will only keep the device awake until that event is queued.
To keep the device awake until the event has been processed,
it is necessary to use the
epoll(7)

EPOLLWAKEUP

flag.

When the
EPOLLWAKEUP

flag is set in the
events

field for a
struct epoll_event,

the system will be kept awake from the moment the event is queued,
through the
epoll_wait(2)

call which returns the event until the subsequent
epoll_wait(2)

call.
If the event should keep the system awake beyond that time,
then a separate
wake_lock

should be taken before the second
epoll_wait(2)

call.

/proc interfaces

The following interfaces can be used to limit the amount of
kernel memory consumed by epoll:

/proc/sys/fs/epoll/max_user_watches (since Linux 2.6.28)

This specifies a limit on the total number of
file descriptors that a user can register across
all epoll instances on the system.
The limit is per real user ID.
Each registered file descriptor costs roughly 90 bytes on a 32-bit kernel,
and roughly 160 bytes on a 64-bit kernel.
Currently,

the default value for
max_user_watches

is 1/25 (4%) of the available low memory,
divided by the registration cost in bytes.

Example for suggested usage

While the usage of
epoll

when employed as a level-triggered interface does have the same
semantics as
poll(2),

the edge-triggered usage requires more clarification to avoid stalls
in the application event loop.
In this example, listener is a
nonblocking socket on which
listen(2)

has been called.
The function
do_use_fd()

uses the new ready file descriptor until
EAGAIN

is returned by either
read(2)

or
write(2).

An event-driven state machine application should, after having received
EAGAIN,

record its current state so that at the next call to
do_use_fd()

it will continue to
read(2)

or
write(2)

from where it stopped before.

#define MAX_EVENTS 10
struct epoll_event ev, events[MAX_EVENTS];
int listen_sock, conn_sock, nfds, epollfd;

/* Set up listening socket, 'listen_sock' (socket(),
   bind(), listen()) */

epollfd = epoll_create(10);
if (epollfd == -1) {
    perror("epoll_create");
    exit(EXIT_FAILURE);
}

ev.events = EPOLLIN;
ev.data.fd = listen_sock;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listen_sock, &ev) == -1) {
    perror("epoll_ctl: listen_sock");
    exit(EXIT_FAILURE);
}

for (;;) {
    nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
    if (nfds == -1) {
        perror("epoll_pwait");
        exit(EXIT_FAILURE);
    }

    for (n = 0; n < nfds; ++n) {
        if (events[n].data.fd == listen_sock) {
            conn_sock = accept(listen_sock,
                            (struct sockaddr *) &local, &addrlen);
            if (conn_sock == -1) {
                perror("accept");
                exit(EXIT_FAILURE);
            }
            setnonblocking(conn_sock);
            ev.events = EPOLLIN | EPOLLET;
            ev.data.fd = conn_sock;
            if (epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock,
                        &ev) == -1) {
                perror("epoll_ctl: conn_sock");
                exit(EXIT_FAILURE);
            }
        } else {
            do_use_fd(events[n].data.fd);
        }
    }
}

When used as an edge-triggered interface, for performance reasons, it is
possible to add the file descriptor inside the
epoll

interface
(EPOLL_CTL_ADD)

once by specifying
(EPOLLIN|EPOLLOUT).

This allows you to avoid
continuously switching between
EPOLLIN

and
EPOLLOUT

calling
epoll_ctl(2)

with
EPOLL_CTL_MOD.

Questions and answers

Q0

What is the key used to distinguish the file descriptors registered in an
epoll

set?

A0

The key is the combination of the file descriptor number and
the open file description
(also known as an "open file handle",
the kernel's internal representation of an open file).

Q1

What happens if you register the same file descriptor on an
epoll

instance twice?

A1

You will probably get
EEXIST.

However, it is possible to add a duplicate
(dup(2),

dup2(2),

fcntl(2)

F_DUPFD)

descriptor to the same
epoll

instance.

This can be a useful technique for filtering events,
if the duplicate file descriptors are registered with different
events

masks.

Q2

Can two
epoll

instances wait for the same file descriptor?
If so, are events reported to both
epoll

file descriptors?

A2

Yes, and events would be reported to both.
However, careful programming may be needed to do this correctly.

Q3

Is the
epoll

file descriptor itself poll/epoll/selectable?

A3

Yes.
If an
epoll

file descriptor has events waiting, then it will
indicate as being readable.

Q4

What happens if one attempts to put an
epoll

file descriptor into its own file descriptor set?

A4

The
epoll_ctl(2)

call will fail
(EINVAL).

However, you can add an
epoll

file descriptor inside another
epoll

file descriptor set.

Q5

Can I send an
epoll

file descriptor over a UNIX domain socket to another process?

A5

Yes, but it does not make sense to do this, since the receiving process
would not have copies of the file descriptors in the
epoll

set.

Q6

Will closing a file descriptor cause it to be removed from all
epoll

sets automatically?

A6

Yes, but be aware of the following point.
A file descriptor is a reference to an open file description (see
open(2)).

Whenever a descriptor is duplicated via
dup(2),

dup2(2),

fcntl(2)

F_DUPFD,

or
fork(2),

a new file descriptor referring to the same open file description is
created.
An open file description continues to exist until all
file descriptors referring to it have been closed.
A file descriptor is removed from an
epoll

set only after all the file descriptors referring to the underlying
open file description have been closed
(or before if the descriptor is explicitly removed using
epoll_ctl(2)

EPOLL_CTL_DEL).

This means that even after a file descriptor that is part of an
epoll

set has been closed,
events may be reported for that file descriptor if other file
descriptors referring to the same underlying file description remain open.

Q7

If more than one event occurs between
epoll_wait(2)

calls, are they combined or reported separately?

A7

They will be combined.

Q8

Does an operation on a file descriptor affect the
already collected but not yet reported events?

A8

You can do two operations on an existing file descriptor.
Remove would be meaningless for
this case.
Modify will reread available I/O.

Q9

Do I need to continuously read/write a file descriptor
until
EAGAIN

when using the
EPOLLET

flag (edge-triggered behavior) ?

A9

Receiving an event from
epoll_wait(2)

should suggest to you that such
file descriptor is ready for the requested I/O operation.
You must consider it ready until the next (nonblocking)
read/write yields
EAGAIN.

When and how you will use the file descriptor is entirely up to you.

For packet/token-oriented files (e.g., datagram socket,
terminal in canonical mode),
the only way to detect the end of the read/write I/O space
is to continue to read/write until
EAGAIN.

For stream-oriented files (e.g., pipe, FIFO, stream socket), the
condition that the read/write I/O space is exhausted can also be detected by
checking the amount of data read from / written to the target file
descriptor.
For example, if you call
read(2)

by asking to read a certain amount of data and
read(2)

returns a lower number of bytes, you
can be sure of having exhausted the read I/O space for the file
descriptor.
The same is true when writing using
write(2).

(Avoid this latter technique if you cannot guarantee that
the monitored file descriptor always refers to a stream-oriented file.)

Possible pitfalls and ways to avoid them

o Starvation (edge-triggered)

If there is a large amount of I/O space,
it is possible that by trying to drain
it the other files will not get processed causing starvation.
(This problem is not specific to
epoll.)

The solution is to maintain a ready list
and mark the file descriptor as ready
in its associated data structure, thereby allowing the application to
remember which files need to be processed but still round robin amongst
all the ready files.
This also supports ignoring subsequent events you
receive for file descriptors that are already ready.

o If using an event cache...

If you use an event cache or store all the file descriptors returned from
epoll_wait(2),

then make sure to provide a way to mark
its closure dynamically (i.e., caused by
a previous event's processing).
Suppose you receive 100 events from
epoll_wait(2),

and in event #47 a condition causes event #13 to be closed.
If you remove the structure and
close(2)

the file descriptor for event #13, then your
event cache might still say there are events waiting for that
file descriptor causing confusion.

One solution for this is to call, during the processing of event 47,
epoll_ctl(EPOLL_CTL_DEL)

to delete file descriptor 13 and
close(2),

then mark its associated
data structure as removed and link it to a cleanup list.
If you find another
event for file descriptor 13 in your batch processing,
you will discover the file descriptor had been
previously removed and there will be no confusion.

VERSIONS

The
epoll

API was introduced in Linux kernel 2.5.44.

Support was added to glibc in version 2.3.2.

CONFORMING TO

The
epoll

API is Linux-specific.
Some other systems provide similar
mechanisms, for example, FreeBSD has
kqueue,

and Solaris has
/dev/poll.

SEE ALSO

epoll_create(2),

epoll_create1(2),

epoll_ctl(2),

epoll_wait(2)

Index

NAME

SYNOPSIS

DESCRIPTION

Level-triggered and edge-triggered

Interaction with autosleep

/proc interfaces

Example for suggested usage

Questions and answers

Possible pitfalls and ways to avoid them

VERSIONS

CONFORMING TO

SEE ALSO

This document was created by
man2html,
using the manual pages.

Time: 02:55:21 GMT, September 18, 2014


text:
package com.avairebot.middleware;

import com.avairebot.AvaIre;
import com.avairebot.contracts.middleware.Middleware;
import com.avairebot.factories.MessageFactory;
import com.avairebot.language.I18n;
import com.avairebot.utilities.RestActionUtil;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;

import javax.annotation.Nonnull;
import java.util.concurrent.TimeUnit;

public class IsMusicChannelMiddleware extends Middleware {

    public IsMusicChannelMiddleware(AvaIre avaire) {
        super(avaire);
    }

    @Override
    public boolean handle(@Nonnull Message message, @Nonnull MiddlewareStack stack, String... args) {
        if (!message.getChannelType().isGuild() || stack.getDatabaseEventHolder().getGuild() == null) {
            return stack.next();
        }

        if (stack.getDatabaseEventHolder().getGuild().getMusicChannelText() == null) {
            return stack.next();
        }

        TextChannel textChannelById = message.getGuild().getTextChannelById(
            stack.getDatabaseEventHolder().getGuild().getMusicChannelText()
        );

        if (textChannelById == null) {
            return stack.next();
        }

        if (message.getChannel().getIdLong() == textChannelById.getIdLong()) {
            return stack.next();
        }

        return runMessageCheck(message, () -> {
            MessageFactory.makeWarning(message, I18n.get(message.getGuild()).getString(
                "music.internal.musicChannel",
                "You can only use music commands in the :channel channel."
            )).set("channel", textChannelById.getAsMention()).queue(
                musicMessage -> musicMessage.delete().queueAfter(30, TimeUnit.SECONDS, null, RestActionUtil.ignore),
                RestActionUtil.ignore
            );

            return false;
        });
    }
}

redpajama_set_name: RedPajamaGithub


text:
using namespace angle;

class OcclusionQueriesTest : public ANGLETest
{
  protected:
    OcclusionQueriesTest() : mProgram(0), mRNG(1)
    {
        setWindowWidth(128);
        setWindowHeight(128);
        setConfigRedBits(8);
        setConfigGreenBits(8);
        setConfigBlueBits(8);
        setConfigAlphaBits(8);
        setConfigDepthBits(24);
    }

    void SetUp() override
    {
        ANGLETest::SetUp();

        const std::string passthroughVS = SHADER_SOURCE
        (
            attribute highp vec4 position;
            void main(void)
            {
                gl_Position = position;
            }
        );

        const std::string passthroughPS = SHADER_SOURCE
        (
            precision highp float;
            void main(void)
            {
               gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
            }
        );

        mProgram = CompileProgram(passthroughVS, passthroughPS);
        ASSERT_NE(0u, mProgram);
    }

    void TearDown() override
    {
        glDeleteProgram(mProgram);

        ANGLETest::TearDown();
    }

    GLuint mProgram;
    RNG mRNG;
};

TEST_P(OcclusionQueriesTest, IsOccluded)
{
    if (getClientVersion() < 3 && !extensionEnabled("GL_EXT_occlusion_query_boolean"))
    {
        std::cout << "Test skipped because ES3 or GL_EXT_occlusion_query_boolean are not available."
                  << std::endl;
        return;
    }

    glDepthMask(GL_TRUE);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    // draw a quad at depth 0.3
    glEnable(GL_DEPTH_TEST);
    glUseProgram(mProgram);
    drawQuad(mProgram, "position", 0.3f);
    glUseProgram(0);

    EXPECT_GL_NO_ERROR();

    GLuint query = 0;
    glGenQueriesEXT(1, &query);
    glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_EXT, query);
    drawQuad(mProgram, "position", 0.8f); // this quad should be occluded by first quad
    glEndQueryEXT(GL_ANY_SAMPLES_PASSED_EXT);

    EXPECT_GL_NO_ERROR();

    swapBuffers();

    GLuint ready = GL_FALSE;
    while (ready == GL_FALSE)
    {
        angle::Sleep(0);
        glGetQueryObjectuivEXT(query, GL_QUERY_RESULT_AVAILABLE_EXT, &ready);
    }

    GLuint result = GL_TRUE;
    glGetQueryObjectuivEXT(query, GL_QUERY_RESULT_EXT, &result);

    EXPECT_GL_NO_ERROR();

    glDeleteQueriesEXT(1, &query);

    EXPECT_GLENUM_EQ(GL_FALSE, result);
}

TEST_P(OcclusionQueriesTest, IsNotOccluded)
{
    if (getClientVersion() < 3 && !extensionEnabled("GL_EXT_occlusion_query_boolean"))
    {
        std::cout << "Test skipped because ES3 or GL_EXT_occlusion_query_boolean are not available."
                  << std::endl;
        return;
    }

    glDepthMask(GL_TRUE);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    EXPECT_GL_NO_ERROR();

    GLuint query = 0;
    glGenQueriesEXT(1, &query);
    glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_EXT, query);
    drawQuad(mProgram, "position", 0.8f); // this quad should not be occluded
    glEndQueryEXT(GL_ANY_SAMPLES_PASSED_EXT);

    EXPECT_GL_NO_ERROR();

    swapBuffers();

    GLuint result = GL_TRUE;
    glGetQueryObjectuivEXT(query, GL_QUERY_RESULT_EXT, &result); // will block waiting for result

    EXPECT_GL_NO_ERROR();

    glDeleteQueriesEXT(1, &query);

    EXPECT_GLENUM_EQ(GL_TRUE, result);
}

TEST_P(OcclusionQueriesTest, Errors)
{
    if (getClientVersion() < 3 && !extensionEnabled("GL_EXT_occlusion_query_boolean"))
    {
        std::cout << "Test skipped because ES3 or GL_EXT_occlusion_query_boolean are not available."
                  << std::endl;
        return;
    }

    glDepthMask(GL_TRUE);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    EXPECT_GL_NO_ERROR();

    GLuint query = 0;
    GLuint query2 = 0;
    glGenQueriesEXT(1, &query);

    EXPECT_EQ(glIsQueryEXT(query), GL_FALSE);
    EXPECT_EQ(glIsQueryEXT(query2), GL_FALSE);

    glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_EXT, 0); // can't pass 0 as query id
    EXPECT_GL_ERROR(GL_INVALID_OPERATION);

    glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_EXT, query);
    glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, query2); // can't initiate a query while one's already active
    EXPECT_GL_ERROR(GL_INVALID_OPERATION);

    EXPECT_EQ(glIsQueryEXT(query), GL_TRUE);
    EXPECT_EQ(glIsQueryEXT(query2), GL_FALSE); // have not called begin

    drawQuad(mProgram, "position", 0.8f); // this quad should not be occluded
    glEndQueryEXT(GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT); // no active query for this target
    EXPECT_GL_ERROR(GL_INVALID_OPERATION);
    glEndQueryEXT(GL_ANY_SAMPLES_PASSED_EXT);

    glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, query); // can't begin a query as a different type than previously used
    EXPECT_GL_ERROR(GL_INVALID_OPERATION);

    glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, query2); // have to call genqueries first
    EXPECT_GL_ERROR(GL_INVALID_OPERATION);

    glGenQueriesEXT(1, &query2);
    glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, query2); // should be ok now
    EXPECT_EQ(glIsQueryEXT(query2), GL_TRUE);

    drawQuad(mProgram, "position", 0.3f); // this should draw in front of other quad
    glDeleteQueriesEXT(1, &query2); // should delete when query becomes inactive
    glEndQueryEXT(GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT); // should not incur error; should delete query + 1 at end of execution.
    EXPECT_GL_NO_ERROR();

    swapBuffers();

    EXPECT_GL_NO_ERROR();

    GLuint ready = GL_FALSE;
    glGetQueryObjectuivEXT(query2, GL_QUERY_RESULT_AVAILABLE_EXT, &ready); // this query is now deleted
    EXPECT_GL_ERROR(GL_INVALID_OPERATION);

    EXPECT_GL_NO_ERROR();
}

// Test that running multiple simultaneous queries from multiple EGL contexts returns the correct
// result for each query.  Helps expose bugs in ANGLE's virtual contexts.
TEST_P(OcclusionQueriesTest, MultiContext)
{
    if (getClientVersion() < 3 && !extensionEnabled("GL_EXT_occlusion_query_boolean"))
    {
        std::cout << "Test skipped because ES3 or GL_EXT_occlusion_query_boolean are not available."
                  << std::endl;
        return;
    }

    if (GetParam() == ES2_D3D9() || GetParam() == ES2_D3D11() || GetParam() == ES3_D3D11() || GetParam() == ES2_D3D11_FL9_3())
    {
        std::cout << "Test skipped because the D3D backends cannot support simultaneous queries on "
                     "multiple contexts yet."
                  << std::endl;
        return;
    }

    glDepthMask(GL_TRUE);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    // draw a quad at depth 0.5
    glEnable(GL_DEPTH_TEST);
    drawQuad(mProgram, "position", 0.5f);

    EGLWindow *window = getEGLWindow();

    EGLDisplay display = window->getDisplay();
    EGLConfig config   = window->getConfig();
    EGLSurface surface = window->getSurface();

    EGLint contextAttributes[] = {
        EGL_CONTEXT_MAJOR_VERSION_KHR,
        GetParam().majorVersion,
        EGL_CONTEXT_MINOR_VERSION_KHR,
        GetParam().minorVersion,
        EGL_NONE,
    };

    const size_t passCount = 5;
    struct ContextInfo
    {
        EGLContext context;
        GLuint program;
        GLuint query;
        bool visiblePasses[passCount];
        bool shouldPass;
    };

    ContextInfo contexts[] = {
        {
            EGL_NO_CONTEXT, 0, 0, {false, false, false, false, false}, false,
        },
        {
            EGL_NO_CONTEXT, 0, 0, {false, true, false, true, false}, true,
        },
        {
            EGL_NO_CONTEXT, 0, 0, {false, false, false, false, false}, false,
        },
        {
            EGL_NO_CONTEXT, 0, 0, {true, true, false, true, true}, true,
        },
        {
            EGL_NO_CONTEXT, 0, 0, {false, true, true, true, true}, true,
        },
        {
            EGL_NO_CONTEXT, 0, 0, {true, false, false, true, false}, true,
        },
        {
            EGL_NO_CONTEXT, 0, 0, {false, false, false, false, false}, false,
        },
        {
            EGL_NO_CONTEXT, 0, 0, {false, false, false, false, false}, false,
        },
    };

    for (auto &context : contexts)
    {
        context.context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes);
        ASSERT_NE(context.context, EGL_NO_CONTEXT);

        eglMakeCurrent(display, surface, surface, context.context);

        const std::string passthroughVS = SHADER_SOURCE
        (
            attribute highp vec4 position;
            void main(void)
            {
                gl_Position = position;
            }
        );

        const std::string passthroughPS = SHADER_SOURCE
        (
            precision highp float;
            void main(void)
            {
               gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
            }
        );

        context.program = CompileProgram(passthroughVS, passthroughPS);
        ASSERT_NE(context.program, 0u);

        glDepthMask(GL_FALSE);
        glEnable(GL_DEPTH_TEST);

        glGenQueriesEXT(1, &context.query);
        glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_EXT, context.query);

        ASSERT_GL_NO_ERROR();
    }

    for (size_t pass = 0; pass < passCount; pass++)
    {
        for (const auto &context : contexts)
        {
            eglMakeCurrent(display, surface, surface, context.context);

            float depth = context.visiblePasses[pass] ? mRNG.randomFloatBetween(0.0f, 0.4f)
                                                      : mRNG.randomFloatBetween(0.6f, 1.0f);
            drawQuad(context.program, "position", depth);

            EXPECT_GL_NO_ERROR();
        }
    }

    for (const auto &context : contexts)
    {
        eglMakeCurrent(display, surface, surface, context.context);
        glEndQueryEXT(GL_ANY_SAMPLES_PASSED_EXT);

        GLuint result = GL_TRUE;
        glGetQueryObjectuivEXT(context.query, GL_QUERY_RESULT_EXT, &result);

        EXPECT_GL_NO_ERROR();

        GLuint expectation = context.shouldPass ? GL_TRUE : GL_FALSE;
        EXPECT_EQ(expectation, result);
    }

    eglMakeCurrent(display, surface, surface, window->getContext());

    for (auto &context : contexts)
    {
        eglDestroyContext(display, context.context);
        context.context = EGL_NO_CONTEXT;
    }
}

// Use this to select which configurations (e.g. which renderer, which GLES major version) these tests should be run against.
ANGLE_INSTANTIATE_TEST(OcclusionQueriesTest,
                       ES2_D3D9(),
                       ES2_D3D11(),
                       ES2_D3D11_FL9_3(),
                       ES3_D3D11(),
                       ES2_OPENGL(),
                       ES3_OPENGL(),
                       ES2_OPENGLES(),
                       ES3_OPENGLES());


text:
module Hanami
  # @since 0.9.0
  # @api private
  module Components
    # @since 0.9.0
    # @api private
    module App
      # hanami-assets configuration for a sigle Hanami application in the project.
      #
      # @since 0.9.0
      # @api private
      class Assets
        # Configure hanami-assets for a single Hanami application in the project.
        #
        # @param app [Hanami::Configuration::App] a Hanami application
        #
        # @since 0.9.0
        # @api private
        #
        # rubocop:disable Metrics/AbcSize
        # rubocop:disable Metrics/MethodLength
        def self.resolve(app)
          config    = app.configuration
          namespace = app.namespace

          unless namespace.const_defined?('Assets', false)
            assets = Hanami::Assets.duplicate(namespace) do
              root             config.root

              scheme           config.scheme
              host             config.host
              port             config.port

              public_directory Hanami.public_directory
              prefix           Utils::PathPrefix.new('/assets').join(config.path_prefix)

              manifest         Hanami.public_directory.join('assets.json')
              compile          true

              config.assets.__apply(self)
            end

            assets.configure do
              cdn host != config.host
            end

            namespace.const_set('Assets', assets)
          end

          name = "#{app.app_name}.assets"
          Components.resolved(name, namespace.const_get('Assets').configuration)
          Components[name]
        end
      end
      # rubocop:enable Metrics/MethodLength
      # rubocop:enable Metrics/AbcSize
    end
  end
end


text:
package com.doodeec.filemanager.UIComponents;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.RelativeLayout;

/**
 * Created by Dusan Doodeec Bartos on 4.10.2014.
 *
 * Component used to allow selecting gridView items
 */
@SuppressWarnings("unused")
public class CheckableItem extends RelativeLayout implements Checkable {
    private boolean mChecked = false;
    private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };

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

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

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

    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (isChecked())
            mergeDrawableStates(drawableState, CHECKED_STATE_SET);
        return drawableState;
    }

    @Override
    public boolean isChecked() {
        return mChecked;
    }

    @Override
    public void setChecked(boolean isChecked) {
        mChecked = isChecked;
        refreshDrawableState();
    }

    @Override
    public void toggle() {
        setChecked(!mChecked);
    }
}


text:
<?php

namespace Log210\CommonBundle\Controller;

use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller as SymfonyController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Serializer;

abstract class BaseController extends SymfonyController
{

    /**
     * @return ObjectManager
     */
	protected function getEntityManager()
	{
		return $this->getDoctrine()->getManager();
	}

	protected function toJson($content)
	{
        $encoders = [new JsonEncoder()];
        $normalizer = new GetSetMethodNormalizer();
        $serializer = new Serializer([$normalizer], $encoders);

        return $serializer->serialize($content, 'json');
	}

    protected function fromJson($json, $returnClass) {
        $encoders = array(new JsonEncoder());
        $normalizers = array(new GetSetMethodNormalizer());
        $serializer = new Serializer($normalizers, $encoders);

        return $serializer->deserialize($json, $returnClass, 'json');
    }

	protected function jsonResponse(Response $response)
	{
		$response->headers->set('Content-Type', 'application/json');
		return $response;
	}

    public function getUser() {
        return $this->get('security.context')->getToken()->getUser();
    }
}


text: define({other:"Inne",minToMax:"do"});


text:
layout: publication
title: "Model-plant mismatch detection with support vector machine for cross-directional process behavior monitoring"
order: 2
year: 2018
type: "patent"
authors: "Qiugang Lu, R. Bhushan Gopaluni, Michael Forbes, Philip Loewen, Johan Backstrom, Guy A. Dumont"
journal: "US Patent App. 15"
---


text:
<?php
/**
 * Classe responsável por trabalhar com as TAGS referentes as classes WMI da coleta do agente
 * Essas classes WMI definem o tipo do dado coletado.
 * referencia WMI: http://msdn.microsoft.com/en-us/library/windows/desktop/aa394573(v=vs.85).aspx
 */

namespace Cacic\WSBundle\Helper;

class TagValueHelper
{
    //Contrutor privado para evitar instanciação da classe.
    private function  __construct(){}

    // Metódo para recuperar valores das Classes
    public static function getClassValue($pStrTagLabel, $pStrSource, $pStrTags = '[]')
    {
        //Tratar as tags depois!
        preg_match_all("/Win32_" . $pStrTagLabel . "=(.*)/i",$pStrSource, $arrResult);
        return $arrResult[1][0];
    }

    // Metódo para recuperar array com nomes das Classes
    public static function getClassNames($pStrSource, $pStrTags = '[]')
    {
        preg_match_all("/Win32_(.*?)=/",$pStrSource,$arrResult);
        return $arrResult[1];
    }

    // Metódo para recuperar valores delimitados por tags definidas em  $pStrTags
    public static function getValueFromTags($pStrTagLabel, $pStrSource, $pStrTags = '[]')
    {
        //Tratar as tags depois!
        preg_match_all("(\[" . $pStrTagLabel . "\](.+)\[\/" . $pStrTagLabel . "\])i",$pStrSource, $arrResult);

        // Garantir que o resultado contenha somente UTF-8 valido
        $resultado = TagValueHelper::UTF8Sanitize(@$arrResult[1][0]);

        return $resultado;
    }

    // Metódo para recuperar array com nomes das tags delimitadas por "<" e ">"
    public static function getTagsFromValues($pStrSource, $pStrTags = '[]')
    {
        preg_match_all("/\[\/(.*?)\]/",$pStrSource,$arrResult);
        $teste = print_r($arrResult[1], true);
        //error_log("01010101011010101010101010101010101011010101: $teste");
        //error_log("20202020202020220202020202020220202020202020: $pStrSource");
        return empty($arrResult[1]) ? null : $arrResult[1] ;
    }

    // Metódo para excluir uma tag
    public static function delTags($pStrTagLabel, $pStrSource, $pStrTags = '[]')
    {
        $strBeginTag = substr($pStrTags,0,1) 		. $pStrTagLabel . substr($pStrTags,1,1);
        $strEndTag   = substr($pStrTags,0,1) . '/' 	. $pStrTagLabel . substr($pStrTags,1,1);
        $strSource	 = $pStrSource;

        $strSource = str_replace($strBeginTag . $strEndTag,'',$strSource);

        while ($strActualValue = getValueFromTags($pStrTagLabel,$strSource))
            $strSource = str_replace($strBeginTag . $strActualValue . $strEndTag,'',$strSource);

        return $strSource;
    }
    // Metódo para atribuir valor a tags
    public static function setValueToTags($pStrTagLabel, $pStrValue, $pStrSource, $pStrTags = '[]')
    {
        $strBeginTag = substr($pStrTags,0,1) 		. $pStrTagLabel . substr($pStrTags,1,1);
        $strEndTag   = substr($pStrTags,0,1) . '/' 	. $pStrTagLabel . substr($pStrTags,1,1);
        $strSource	 = $pStrSource;

        $strActualValue = getValueFromTags($pStrTagLabel,$pStrSource);
        if (stripos2($strSource,$strBeginTag,false))
            $strSource = str_replace($strBeginTag . $strActualValue . $strEndTag,$strBeginTag . $pStrValue . $strEndTag,$pStrSource);
        else
            $strSource .= $strBeginTag . $pStrValue . $strEndTag;

        return $strSource;
    }

    /*
     * Faz o parse da tag software, retornando uma sequência de registros que possui a tag software
     */

    public static function getSoftwareTags($pStrSource, $pStrTags = '[]')
    {
        preg_match_all("/\[Software\](.*?)\[\/Software\]/",$pStrSource,$arrResult);
        $teste = print_r($arrResult[1], true);
        //error_log("2222222222222222222222222222222222222222222222222222222222: $teste");
        //error_log("20202020202020220202020202020220202020202020: $pStrSource");
        return empty($arrResult[1]) ? null : $arrResult[1] ;
    }

    /*
     * Limpa caracteres que não são UTF-8
     * Extraído de http://stackoverflow.com/questions/1401317/remove-non-utf8-characters-from-string
     */

    public static function UTF8Sanitize($text) {
        return iconv('WINDOWS-1252', 'UTF-8//TRANSLIT', $text);
    }

    /*
     * Trata o caso de retornar os registros multivalorados para mostrar em uma tabela
     */

    public static function getTableValues($source) {
        preg_match_all("/(.*)\[\[REG\]\](.*)/", $source, $arrResult);

        // Se não houver match, retorna a fonte
        if (empty($arrResult[0])) {
            return $source;
        }

        //Caso contrário retorna os elementos prontos para serem inseridos em uma tabela
        $saida = '';
        $i = 0;
        foreach ($arrResult as $linha) {
            if ($i != 0) {
                // Ignora a primeira linha
                //continue;
                $saida = $saida . '
';
                $saida = $saida . "#$i	";
                $saida = $saida . "$linha[0]	";
                $saida = $saida . '
';
            }
            $i = $i + 1;
        }

        return $saida;

    }

}


text:
package pl.dzielins42.dmtools.calculator.building.model;

public enum Style {
    ROUGH,
    FUNCTIONAL,
    UTILITARIAN,
    BASIC,
    NORMAL,
    TASTEFUL,
    ORNATE,
    ARTISTIC,
    LUXURIOUS,
    ROYAL,
    IMPERIAL;
}


text:
<!doctype html>

      <meta charset="utf-8">
      <title>Affichage digital</title>
    <link class="module" rel="stylesheet" href="../../../_common/modules/pemFioi/taskStyles-0.1.css" id="http://www.france-ioi.org/modules/pemFioi/taskStyles-0.1.css">

    <link class="stdAnswerTypes module" rel="stylesheet" type="text/css" href="../../../_common/modules/integrationAPI.01/installationAPI.01/pemFioi/answerTypes.css" id="http://www.france-ioi.org/modules/integrationAPI.01/installationAPI.01/pemFioi/stdAnsTypes.css" />

Affichage digital

Un affichage digital est formé de 7 segments lumineux, chacun d'entre eux pouvant être soit allumé, soit éteint. Ainsi, on peut représenter tous les chiffres de 0 à 9, comme illustré ci-dessous.

On peut effectuer deux opérations sur un affichage.

 L'opération « Inverse »
L'opération « Combine »

Allume les segments qui étaient éteints et éteint les segments qui étaient allumés.

 Par exemple :

Inverse(

) donne

S'applique à deux affichages et produit un nouvel affichage où tous les segments allumés sur au moins un de ces deux affichages se retrouvent allumés, et seulement ceux-ci.

Par exemple :

Combine(

,

) donne

Laquelle des opérations suivantes ne donne pas  ?

La solution

La réponse 3 :

Combine( Inverse(		), 		) laisse le segment en bas à droite éteint.

En effet, le calcul effectué passe par les étapes suivantes :

	-> Inverse ->

	-> Combine ->

C'est de l'informatique

Cet exercice nécessite de manipuler deux concepts très importants en informatique :

Le principe des opérations sur des valeurs binaires : chaque segment, éteint ou allumé, peut être vu comme un chiffre binaire 0 ou 1. Les opérations effectuées sont des opérations classiques en binaire : "Inverser" est en fait un "NON" binaire, et "Combiner" est en fait un "OU" binaire.

Le principe des fonctions, qui prennent un ou plusieurs paramètres, et retournent une valeur issue d'un calcul. "Inverser" prend un paramètre et retourne une valeur, et "Combiner" prend deux paramètres et retourne une valeur. Ici il fallait comprendre soi-même ce que signifiait le fait de passer en paramètre d'une fonction le résultat d'une autre fonction, en s'aidant du fait que 3 des 4 propositions avaient pour résultat 8.

Culture informatique

L'opération "inverse" est problablement l'opération la plus fondamentale parmi celles qu'un ordinateur sait effectuer.
En effet, un ordinateur représente toutes les données par des bits, qui ne peuvent prendre que deux valeurs possibles : soit 0, soit 1.
L'opération "inverse", appliquée à 0 donne 1, et appliquée à 1 donne 0.

On peut appliquer une inversion à un ensemble de bits d'un seul coup. Par exemple, si l'on inverse "1010110",
on obtient "0101001". Ce type d'opération peut par exemple servir à décrire le complémentaire d'un ensemble :
si "1010110" décrit les jours "Lundi, Mercredi, Vendredi et Samedi", alors l'ensemble décrit par l'inverse,
à savoir "0101001" décrit les jours "Mardi, Jeudi et Dimanche".

Un ordinateur construit en 2012 est capable d'inverser de la sorte un paquet de 64 bits en un seul cycle
de calcul, et il peut exécuter plusieurs milliards de tels cycles chaque seconde !


text:
namespace MassTransit.TestFramework.ForkJoint.Contracts
{
    public interface ComboCompleted :
        OrderLineCompleted
    {
    }
}


text:
package com.stulsoft.pjava.function;

import java.util.function.Consumer;

/**
 * Demonstrates the usage of function as return value.
 *
 * @author Yuriy Stul
 */
public class FunctionFactory {

    public static void main(String[] args) {
        System.out.println("==>main");
        Consumer<Integer> f;

        FunctionFactory ff = new FunctionFactory();
        f = ff.getFunction(3);
        f.accept(10);

        f = ff.getFunction(30);
        f.accept(10);

        System.out.println("<==main");
    }

    /**
     * Returns a function depending on input argument
     *
     * @param i input argument
     * @return the function depending on input argument
     */
    private Consumer<Integer> getFunction(int i) {
        Consumer<Integer> f;
        if (i < 5) {
            f = x -> System.out.println("Result is " + (x * 15));
        } else {
            f = x -> System.out.println("Result is " + (x + 15));
        }

        return f;
    }
}


text:
/*
 This file is for compatibility compatibility with older versions of GUIReader and SceneReader
 todo: deprecated all
 */

(function(){

    ccs.uiReader = {

        _fileDesignSizes: {},

        //@deprecated This function will be deprecated sooner or later please use ccs.load
        /**
         * Create CCUI Node
         * @param file
         * @returns {*}
         */
        widgetFromJsonFile: function(file){
            var json = cc.loader.getRes(file);
            if(json)
                this._fileDesignSizes[file] = cc.size(json["designWidth"]||0, json["designHeight"]||0);

            var version = json["Version"] || json["version"];
            var versionNum = ccs.uiReader.getVersionInteger(version);
            if(!version || versionNum >= 1700){
                cc.warn("Not supported file types, Please try use the ccs.load");
                return null;
            }
            return ccs._load(file, "ccui");
        },

        //@deprecated This function will be deprecated sooner or later please use parser.registerParser
        /**
         * Register a custom Widget reader
         * @param classType
         * @param ins
         * @param object
         * @param callback
         * @deprecated This function will be deprecated sooner or later please use parser.registerParser
         */
        registerTypeAndCallBack: function(classType, ins, object, callback){
            var parser = ccs._load.getParser("ccui")["*"];
            var func = callback.bind(object);
            parser.registerParser(classType, function(options, resourcePath){
                var widget = new ins();
                var uiOptions = options["options"];
                object.setPropsFromJsonDictionary && object.setPropsFromJsonDictionary(widget, uiOptions);
                this.generalAttributes(widget, uiOptions);
                var customProperty = uiOptions["customProperty"];
                if(customProperty)
                    customProperty = JSON.parse(customProperty);
                else
                    customProperty = {};
                func(classType, widget, customProperty);
                this.colorAttributes(widget, uiOptions);
                this.anchorPointAttributes(widget, uiOptions);
                this.parseChild.call(this, widget, options, resourcePath);
                return widget;
            });
        },

        //@deprecated This function will be deprecated sooner or later
        /**
         * Gets the version number by version string.
         * @param {String} version version string.
         * @returns {Number}
         */
        getVersionInteger: function(version){
            if(!version || typeof version != "string") return 0;
            var arr = version.split(".");
            if (arr.length != 4)
                return 0;
            var num = 0;
            arr.forEach(function(n, i){
                num += n * Math.pow(10, 3 - i);
            });
            return num;
        },

        //@deprecated This function will be deprecated sooner or later
        /**
         * stores the designSize of UI file.
         * @param {String} fileName
         * @param {cc.Size} size
         */
        storeFileDesignSize: function (fileName, size) {
            this._fileDesignSizes[fileName] = size;
        },

        //@deprecated This function will be deprecated sooner or later
        /**
         * Gets the design size by filename.
         * @param {String} fileName
         * @returns {cc.Size}
         */
        getFileDesignSize: function (fileName) {
            return this._fileDesignSizes[fileName];
        },

        //@deprecated This function will be deprecated sooner or later
        /**
         * Returns the file path
         * @returns {string}
         */
        getFilePath: function(){
            return this._filePath;
        },

        //@deprecated This function will be deprecated sooner or later
        setFilePath: function(path){
            this._filePath = path;
        },

        //@deprecated This function will be deprecated sooner or later
        /**
         * Returns the parsed object map. (analytic function)
         * @returns {Object}
         */
        getParseObjectMap: function(){
            return ccs._load.getParser("ccui")["*"]["parsers"];
        },

        //@deprecated This function will be deprecated sooner or later
        /**
         * Returns the parsed callback map. (analytic function)
         * @returns {*}
         */
        getParseCallBackMap: function(){
            return ccs._load.getParser("ccui")["*"]["parsers"];
        },

        //@deprecated This function will be deprecated sooner or later
        clear: function(){}
    };

    var parser = ccs._load.getParser("ccui")["*"];
    ccs.imageViewReader  = {setPropsFromJsonDictionary: parser.ImageViewAttributes};
    ccs.buttonReader     = {setPropsFromJsonDictionary: parser.ButtonAttributes};
    ccs.checkBoxReader   = {setPropsFromJsonDictionary: parser.CheckBoxAttributes};
    ccs.labelAtlasReader = {setPropsFromJsonDictionary: parser.TextAtlasAttributes};
    ccs.labelBMFontReader= {setPropsFromJsonDictionary: parser.TextBMFontAttributes};
    ccs.labelReader      = {setPropsFromJsonDictionary: parser.TextAttributes};
    ccs.layoutReader     = {setPropsFromJsonDictionary: parser.LayoutAttributes};
    ccs.listViewReader   = {setPropsFromJsonDictionary: parser.ListViewAttributes};
    ccs.loadingBarReader = {setPropsFromJsonDictionary: parser.LoadingBarAttributes};
    ccs.pageViewReader   = {setPropsFromJsonDictionary: parser.PageViewAttributes};
    ccs.scrollViewReader = {setPropsFromJsonDictionary: parser.ScrollViewAttributes};
    ccs.sliderReader     = {setPropsFromJsonDictionary: parser.SliderAttributes};
    ccs.textFieldReader  = {setPropsFromJsonDictionary: parser.TextFieldAttributes};
})();

(function(){
    ccs.sceneReader = {

        _node: null,

        //@deprecated This function will be deprecated sooner or later please use ccs.load
        /**
         * Create Scene Node
         * @param file
         * @returns {*}
         */
        createNodeWithSceneFile: function(file){
            var node = ccs._load(file, "scene");
            this._node = node;
            return node;
        },

        /**
         * Get a node by tag.
         * @param {Number} tag
         * @returns {cc.Node|null}
         */
        getNodeByTag: function(tag){
            if (this._node == null)
                return null;
            if (this._node.getTag() == tag)
                return this._node;
            return this._nodeByTag(this._node, tag);
        },

        _nodeByTag: function (parent, tag) {
            if (parent == null)
                return null;
            var retNode = null;
            var children = parent.getChildren();
            for (var i = 0; i < children.length; i++) {
                var child = children[i];
                if (child && child.getTag() == tag) {
                    retNode = child;
                    break;
                } else {
                    retNode = this._nodeByTag(child, tag);
                    if (retNode)
                        break;
                }
            }
            return retNode;
        },

        //@deprecated This function will be deprecated sooner or later
        /**
         * Returns the version of ccs.SceneReader.
         * @returns {string}
         */
        version: function(){
            return "*";
        },

        //@deprecated This function will be deprecated sooner or later
        /**
         * Sets the listener to reader.
         * Cannot use
         */
        setTarget: function(){},

        //@deprecated This function will be deprecated sooner or later
        /**
         * Clear all triggers and stops all sounds.
         */
        clear: function(){
            ccs.triggerManager.removeAll();
            cc.audioEngine.end();
        }
    };
})();


text:
package com.android.tools.build.bundletool.device;

import static com.android.bundle.Targeting.TextureCompressionFormat.TextureCompressionFormatAlias.ASTC;
import static com.android.bundle.Targeting.TextureCompressionFormat.TextureCompressionFormatAlias.ATC;
import static com.android.bundle.Targeting.TextureCompressionFormat.TextureCompressionFormatAlias.ETC1_RGB8;
import static com.android.bundle.Targeting.TextureCompressionFormat.TextureCompressionFormatAlias.ETC2;
import static com.android.bundle.Targeting.TextureCompressionFormat.TextureCompressionFormatAlias.PVRTC;
import static com.android.tools.build.bundletool.testing.DeviceFactory.deviceFeatures;
import static com.android.tools.build.bundletool.testing.DeviceFactory.lDeviceWithGlExtensions;
import static com.android.tools.build.bundletool.testing.DeviceFactory.mergeSpecs;
import static com.android.tools.build.bundletool.testing.TargetingUtils.textureCompressionTargeting;
import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.ImmutableSet;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class TextureCompressionFormatMatcherTest {

  @Test
  public void simpleMatch_glExtensions() {
    TextureCompressionFormatMatcher textureCompressionFormatMatcher =
        new TextureCompressionFormatMatcher(
            lDeviceWithGlExtensions("GL_OES_compressed_ETC1_RGB8_texture"));

    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ETC1_RGB8, ImmutableSet.of())))
        .isTrue();
    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ATC, ImmutableSet.of())))
        .isFalse();
    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ETC1_RGB8, ImmutableSet.of(ATC))))
        .isTrue();
  }

  @Test
  public void worseAlternatives_glExtensions() {
    TextureCompressionFormatMatcher textureCompressionFormatMatcher =
        new TextureCompressionFormatMatcher(
            lDeviceWithGlExtensions(
                "GL_OES_compressed_ETC1_RGB8_texture", "GL_IMG_texture_compression_pvrtc"));

    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(PVRTC, ImmutableSet.of(ATC))))
        .isTrue();
    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(PVRTC, ImmutableSet.of(ETC1_RGB8))))
        .isTrue();
    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(PVRTC, ImmutableSet.of(ATC, ETC1_RGB8))))
        .isTrue();
    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ETC1_RGB8, ImmutableSet.of(ATC))))
        .isTrue();
  }

  @Test
  public void betterAlternatives_glExtensions() {
    TextureCompressionFormatMatcher textureCompressionFormatMatcher =
        new TextureCompressionFormatMatcher(
            lDeviceWithGlExtensions(
                "GL_OES_compressed_ETC1_RGB8_texture", "GL_IMG_texture_compression_pvrtc"));

    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ATC, ImmutableSet.of(PVRTC))))
        .isFalse();
    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ETC1_RGB8, ImmutableSet.of(PVRTC))))
        .isFalse();
    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ETC1_RGB8, ImmutableSet.of(ATC, PVRTC))))
        .isFalse();
  }

  @Test
  public void simpleMatch_openglVersion() {
    TextureCompressionFormatMatcher textureCompressionFormatMatcher =
        new TextureCompressionFormatMatcher(deviceFeatures("reqGlEsVersion=0x30000"));

    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ETC2, ImmutableSet.of())))
        .isTrue();
    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ATC, ImmutableSet.of())))
        .isFalse();
    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ETC2, ImmutableSet.of(ATC))))
        .isTrue();
  }

  @Test
  public void noMatch_invalidOpenglVersion() {
    TextureCompressionFormatMatcher textureCompressionFormatMatcher =
        new TextureCompressionFormatMatcher(deviceFeatures("reqGlEsVersion=bad_result"));

    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ETC2, ImmutableSet.of())))
        .isFalse();
  }

  @Test
  public void betterAlternatives_mix_inOpenglVersion() {
    TextureCompressionFormatMatcher textureCompressionFormatMatcher =
        new TextureCompressionFormatMatcher(
            mergeSpecs(
                lDeviceWithGlExtensions("GL_OES_compressed_ETC1_RGB8_texture"),
                deviceFeatures("reqGlEsVersion=0x30020")));

    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ATC, ImmutableSet.of(PVRTC))))
        .isFalse();
    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ETC1_RGB8, ImmutableSet.of(ETC2, PVRTC))))
        .isFalse();
    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ETC2, ImmutableSet.of(ETC1_RGB8, PVRTC))))
        .isTrue();
  }

  @Test
  public void betterAlternatives_mix_inGlExtensions() {
    TextureCompressionFormatMatcher textureCompressionFormatMatcher =
        new TextureCompressionFormatMatcher(
            mergeSpecs(
                lDeviceWithGlExtensions(
                    "GL_OES_compressed_ETC1_RGB8_texture", "GL_KHR_texture_compression_astc_ldr"),
                deviceFeatures("reqGlEsVersion=0x30020")));

    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ATC, ImmutableSet.of(ASTC))))
        .isFalse();
    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ETC1_RGB8, ImmutableSet.of(ETC2, ASTC))))
        .isFalse();
    assertThat(
            textureCompressionFormatMatcher.matchesTargeting(
                textureCompressionTargeting(ASTC, ImmutableSet.of(ETC1_RGB8, ETC2))))
        .isTrue();
  }
}


text:
namespace asio {
namespace detail {

class task_io_service;

// Base class for all operations. A function pointer is used instead of virtual
// functions to avoid the associated overhead.
class task_io_service_operation ASIO_INHERIT_TRACKED_HANDLER
{
public:
  void complete(task_io_service& owner,
      const asio::error_code& ec, std::size_t bytes_transferred)
  {
    func_(&owner, this, ec, bytes_transferred);
  }

  void destroy()
  {
    func_(0, this, asio::error_code(), 0);
  }

protected:
  typedef void (*func_type)(task_io_service*,
      task_io_service_operation*,
      const asio::error_code&, std::size_t);

  task_io_service_operation(func_type func)
    : next_(0),
      func_(func),
      task_result_(0)
  {
  }

  // Prevents deletion through this type.
  ~task_io_service_operation()
  {
  }

private:
  friend class op_queue_access;
  task_io_service_operation* next_;
  func_type func_;
protected:
  friend class task_io_service;
  unsigned int task_result_; // Passed into bytes transferred.
};

} // namespace detail
} // namespace asio

#include "asio/detail/pop_options.hpp"

#endif // ASIO_DETAIL_TASK_IO_SERVICE_OPERATION_HPP


text:
package org.openecard.addons.cg.ex;

/**
 *
 * @author Tobias Wich
 */
public class ParameterInvalid extends Exception {

    public ParameterInvalid(String msg) {
	super(msg);
    }

    public ParameterInvalid(String msg, Throwable cause) {
	super(msg, cause);
    }

}


text:
**[GitLab Flavored Markdown](#gitlab-flavored-markdown-gfm)**

* [Newlines](#newlines)
* [Multiple underscores in words](#multiple-underscores-in-words)
* [URL auto-linking](#url-autolinking)
* [Code and Syntax Highlighting](#code-and-syntax-highlighting)
* [Emoji](#emoji)
* [Special GitLab references](#special-gitlab-references)
* [Task lists](#task-lists)

**[Standard Markdown](#standard-markdown)**

* [Headers](#headers)
* [Emphasis](#emphasis)
* [Lists](#lists)
* [Links](#links)
* [Images](#images)
* [Blockquotes](#blockquotes)
* [Inline HTML](#inline-html)
* [Horizontal Rule](#horizontal-rule)
* [Line Breaks](#line-breaks)
* [Tables](#tables)

**[References](#references)**

## GitLab Flavored Markdown (GFM)

For GitLab we developed something we call "GitLab Flavored Markdown" (GFM). It extends the standard Markdown in a few significant ways to add some useful functionality.

You can use GFM in

- commit messages
- comments
- issues
- merge requests
- milestones
- wiki pages

You can also use other rich text files in GitLab. You might have to install a dependency to do so. Please see the [github-markup gem readme](https://github.com/gitlabhq/markup#markups) for more information.

## Newlines

GFM honors the markdown specification in how [paragraphs and line breaks are handled](http://daringfireball.net/projects/markdown/syntax#p).

A paragraph is simply one or more consecutive lines of text, separated by one or more blank lines.:

    Roses are red
    Violets are blue

    Sugar is sweet

Roses are red
Violets are blue

Sugar is sweet

## Multiple underscores in words

It is not reasonable to italicize just _part_ of a word, especially when you're dealing with code and names that often appear with multiple underscores. Therefore, GFM ignores multiple underscores in words.

    perform_complicated_task
    do_this_and_do_that_and_another_thing

perform_complicated_task
do_this_and_do_that_and_another_thing

## URL auto-linking

GFM will autolink standard URLs you copy and paste into your text. So if you want to link to a URL (instead of a textural link), you can simply put the URL in verbatim and it will be turned into a link to that URL.

    http://www.google.com

http://www.google.com

## Code and Syntax Highlighting

Blocks of code are either fenced by lines with three back-ticks ```</code>, or are indented with four spaces. Only the fenced code blocks support syntax highlighting.

```no-highlight
Inline `code` has `back-ticks around` it.
```

Inline `code` has `back-ticks around` it.

Example:

    ```javascript
    var s = "JavaScript syntax highlighting";
    alert(s);
    ```

    ```python
    def function():
        #indenting works just fine in the fenced code block
        s = "Python syntax highlighting"
        print s
    ```

    ```ruby
    require 'redcarpet'
    markdown = Redcarpet.new("Hello World!")
    puts markdown.to_html
    ```

    ```
    No language indicated, so no syntax highlighting.
    s = "There is no highlighting for this."
    But let's throw in a tag.
    ```

becomes:

```javascript
var s = "JavaScript syntax highlighting";
alert(s);
```

```python
def function():
    #indenting works just fine in the fenced code block
    s = "Python syntax highlighting"
    print s
```

```ruby
require 'redcarpet'
markdown = Redcarpet.new("Hello World!")
puts markdown.to_html
```

```
No language indicated, so no syntax highlighting.
s = "There is no highlighting for this."
But let's throw in a tag.
```

## Emoji

	Sometimes you want to be a :ninja: and add some :glowing_star: to your :speech_balloon:. Well we have a gift for you:

	:high_voltage_sign: You can use emoji anywhere GFM is supported. :victory_hand:

	You can use it to point out a :bug: or warn about :speak_no_evil_monkey: patches. And if someone improves your really :snail: code, send them some :cake:. People will :heart: you for that.

	If you are new to this, don't be :fearful_face:. You can easily join the emoji :family:. All you need to do is to look up on the supported codes.

	Consult the [Emoji Cheat Sheet](https://s3.amazonaws.com/emoji-cheatsheet/cheat_sheet.pdf) for a list of all supported emoji codes. :thumbsup:

Sometimes you want to be a :ninja: and add some :glowing_star: to your :speech_balloon:. Well we have a gift for you:

:high_voltage_sign: You can use emoji anywhere GFM is supported. :victory_hand:

You can use it to point out a :bug: or warn about :speak_no_evil_monkey: patches. And if someone improves your really :snail: code, send them some :cake:. People will :heart: you for that.

If you are new to this, don't be :fearful_face:. You can easily join the emoji :family:. All you need to do is to look up on the supported codes.

Consult the [Emoji Cheat Sheet](https://s3.amazonaws.com/emoji-cheatsheet/cheat_sheet.pdf) for a list of all supported emoji codes. :thumbsup:

## Special GitLab References

GFM recognized special references.

You can easily reference e.g. an issue, a commit, a team member or even the whole team within a project.

GFM will turn that reference into a link so you can navigate between them easily.

GFM will recognize the following:

- @foo : for specific team members or groups
- @all : for the whole team
- #123 : for issues
- !123 : for merge requests
- $123 : for snippets
- 1234567 : for commits
- \[file\](path/to/file) : for file references

GFM also recognizes references to commits, issues, and merge requests in other projects:

- namespace/project#123 : for issues
- namespace/project!123 : for merge requests
- namespace/project@1234567 : for commits

## Task Lists

You can add task lists to merge request and issue descriptions to keep track of to-do items.  To create a task, add an unordered list to the description in an issue or merge request, formatted like so:

```no-highlight
* [x] Completed task
* [ ] Unfinished task
    * [x] Nested task
```

Task lists can only be created in descriptions, not in titles or comments.  Task item state can be managed by editing the description's Markdown or by clicking the rendered checkboxes.

# Standard Markdown

## Headers

```no-highlight
# H1
## H2
### H3
#### H4
##### H5
###### H6

Alternatively, for H1 and H2, an underline-ish style:

Alt-H1
======

Alt-H2
------
```

# H1
## H2
### H3
#### H4
##### H5
###### H6

Alternatively, for H1 and H2, an underline-ish style:

Alt-H1
======

Alt-H2
------

### Header IDs and links

All markdown rendered headers automatically get IDs, except for comments.

On hover a link to those IDs becomes visible to make it easier to copy the link to the header to give it to someone else.

The IDs are generated from the content of the header according to the following rules:

1. remove the heading hashes `#` and process the rest of the line as it would be processed if it were not a header
2. from the result, remove all HTML tags, but keep their inner content
3. convert all characters to lowercase
4. convert all characters except `[a-z0-9_-]` into hyphens `-`
5. transform multiple adjacent hyphens into a single hyphen
6. remove trailing and heading hyphens

For example:

```
###### ..Ab_c-d. e [anchor](URL) ![alt text](URL)..
```

which renders as:

###### ..Ab_c-d. e [anchor](URL) ![alt text](URL)..

will first be converted by step 1) into a string like:

```
..Ab_c-d. e <a href="URL">anchor</a> <img src="URL" alt="alt text"/>..
```

After removing the tags in step 2) we get:

```
..Ab_c-d. e anchor ..
```

And applying all the other steps gives the id:

```
ab_c-d-e-anchor
```

Note in particular how:

- for markdown anchors `[text](URL)`, only the `text` is used
- markdown images `![alt](URL)` are completely ignored

## Emphasis

```no-highlight
Emphasis, aka italics, with *asterisks* or _underscores_.

Strong emphasis, aka bold, with **asterisks** or __underscores__.

Combined emphasis with **asterisks and _underscores_**.

Strikethrough uses two tildes. ~~Scratch this.~~
```

Emphasis, aka italics, with *asterisks* or _underscores_.

Strong emphasis, aka bold, with **asterisks** or __underscores__.

Combined emphasis with **asterisks and _underscores_**.

Strikethrough uses two tildes. ~~Scratch this.~~

## Lists

```no-highlight
1. First ordered list item
2. Another item
  * Unordered sub-list.
1. Actual numbers don't matter, just that it's a number
  1. Ordered sub-list
4. And another item.

   Some text that should be aligned with the above item.

* Unordered list can use asterisks
- Or minuses
+ Or pluses
```

1. First ordered list item
2. Another item
  * Unordered sub-list.
1. Actual numbers don't matter, just that it's a number
  1. Ordered sub-list
4. And another item.

   Some text that should be aligned with the above item.

* Unordered list can use asterisks
- Or minuses
+ Or pluses

## Links

There are two ways to create links, inline-style and reference-style.

    [I'm an inline-style link](https://www.google.com)

    [I'm a reference-style link][Arbitrary case-insensitive reference text]

    [I'm a relative reference to a repository file](LICENSE)

    [You can use numbers for reference-style link definitions][1]

    Or leave it empty and use the [link text itself][]

    Some text to show that the reference links can follow later.

    [arbitrary case-insensitive reference text]: https://www.mozilla.org
    [1]: http://slashdot.org
    [link text itself]: http://www.reddit.com

[I'm an inline-style link](https://www.google.com)

[I'm a reference-style link][Arbitrary case-insensitive reference text]

[I'm a relative reference to a repository file](LICENSE)

[You can use numbers for reference-style link definitions][1]

Or leave it empty and use the [link text itself][]

Some text to show that the reference links can follow later.

[arbitrary case-insensitive reference text]: https://www.mozilla.org
[1]: http://slashdot.org
[link text itself]: http://www.reddit.com

**Note**

Relative links do not allow referencing project files in a wiki page or wiki page in a project file. The reason for this is that, in GitLab, wiki is always a separate git repository. For example:

`[I'm a reference-style link][style]`

will point the link to `wikis/style` when the link is inside of a wiki markdown file.

## Images

    Here's our logo (hover to see the title text):

    Inline-style:
    ![alt text](assets/logo-white.png)

    Reference-style:
    ![alt text1][logo]

    [logo]: assets/logo-white.png

Here's our logo:

Inline-style:

![alt text](/assets/logo-white.png)

Reference-style:

![alt text][logo]

[logo]: /assets/logo-white.png

## Blockquotes

```no-highlight
> Blockquotes are very handy in email to emulate reply text.
> This line is part of the same quote.

Quote break.

> This is a very long line that will still be quoted properly when it wraps. Oh boy let's keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can *put* **Markdown** into a blockquote.
```

> Blockquotes are very handy in email to emulate reply text.
> This line is part of the same quote.

Quote break.

> This is a very long line that will still be quoted properly when it wraps. Oh boy let's keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can *put* **Markdown** into a blockquote.

## Inline HTML

You can also use raw HTML in your Markdown, and it'll mostly work pretty well.

Note that inline HTML is disabled in the default Gitlab configuration, although it is [possible](https://github.com/gitlabhq/gitlabhq/pull/8007/commits) for the system administrator to enable it.

```no-highlight

Definition list

Is something people use sometimes.

Markdown in HTML

Does *not* work **very** well. Use HTML tags.

```

<dl>
  <dt>Definition list</dt>
  <dd>Is something people use sometimes.</dd>

  <dt>Markdown in HTML</dt>
  <dd>Does *not* work **very** well. Use HTML <em>tags</em>.</dd>
</dl>

## Horizontal Rule

```
Three or more...

---

Hyphens

***

Asterisks

___

Underscores
```

Three or more...

---

Hyphens

***

Asterisks

___

Underscores

## Line Breaks

My basic recommendation for learning how line breaks work is to experiment and discover -- hit <Enter> once (i.e., insert one newline), then hit it twice (i.e., insert two newlines), see what happens. You'll soon learn to get what you want. "Markdown Toggle" is your friend.

Here are some things to try out:

```
Here's a line for us to start with.

This line is separated from the one above by two newlines, so it will be a *separate paragraph*.

This line is also a separate paragraph, but...
This line is only separated by a single newline, so it's a separate line in the *same paragraph*.
```

Here's a line for us to start with.

This line is separated from the one above by two newlines, so it will be a *separate paragraph*.

This line is also begins a separate paragraph, but...
This line is only separated by a single newline, so it's a separate line in the *same paragraph*.

## Tables

Tables aren't part of the core Markdown spec, but they are part of GFM and Markdown Here supports them.

```
| header 1 | header 2 |
| -------- | -------- |
| cell 1   | cell 2   |
| cell 3   | cell 4   |
```

Code above produces next output:

| header 1 | header 2 |
| -------- | -------- |
| cell 1   | cell 2   |
| cell 3   | cell 4   |

**Note**

The row of dashes between the table header and body must have at least three dashes in each column.

## References

- This document leveraged heavily from the [Markdown-Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
- The [Markdown Syntax Guide](http://daringfireball.net/projects/markdown/syntax) at Daring Fireball is an excellent resource for a detailed explanation of standard markdown.
- [Dillinger.io](http://dillinger.io) is a handy tool for testing standard markdown.


text:
<?php

namespace PHPFastCGI\Test\FastCGIDaemon;

use PHPFastCGI\FastCGIDaemon\DaemonOptions;
use PHPFastCGI\FastCGIDaemon\Driver\Userland\Connection\StreamSocketConnectionPool;
use PHPFastCGI\FastCGIDaemon\Driver\Userland\ConnectionHandler\ConnectionHandlerFactory;
use PHPFastCGI\FastCGIDaemon\Driver\Userland\Exception\UserlandDaemonException;
use PHPFastCGI\FastCGIDaemon\Driver\Userland\UserlandDaemon;
use PHPFastCGI\FastCGIDaemon\Http\RequestInterface;
use PHPFastCGI\Test\FastCGIDaemon\Helper\Client\ConnectionWrapper;
use PHPFastCGI\Test\FastCGIDaemon\Helper\Logger\InMemoryLogger;
use PHPFastCGI\Test\FastCGIDaemon\Helper\Mocker\MockKernel;
use PHPUnit\Framework\TestCase;
use Zend\Diactoros\Response;

/**
 * Tests the daemon.
 */
class UserlandDaemonTest extends TestCase
{
    /**
     * Tests that the daemon shuts down after being flagged for shutdown.
     */
    public function testFlagShutdown()
    {
        // Set a memory limit to make sure that it isn't breached (added 10MB on top of peak usage)
        $context = $this->createTestingContext(1, memory_get_peak_usage() + (10 * 1024 * 1024));

        $context['daemon']->flagShutdown();
        $context['daemon']->run();

        $this->assertEquals('Daemon flagged for shutdown', $context['logger']->getMessages()[1]['message']);
    }

    /**
     * Tests that the daemon shuts down after reaching its request.
     */
    public function testRequestLimit()
    {
        // Set a memory limit to make sure that it isn't breached (added 10MB on top of peak usage)
        $context = $this->createTestingContext(1, memory_get_peak_usage() + (10 * 1024 * 1024));

        $socket            = stream_socket_client($context['address']);
        $connectionWrapper = new ConnectionWrapper($socket);

        $connectionWrapper->writeRequest(1, [], '');

        $context['daemon']->run();

        fclose($socket);

        $this->assertEquals('Daemon request limit reached (1 of 1)', $context['logger']->getMessages()[1]['message']);
    }

    /**
     * Tests that the daemon shuts down after reaching its memory limit.
     */
    public function testMemoryLimit()
    {
        $context = $this->createTestingContext(DaemonOptions::NO_LIMIT, 1);

        $socket            = stream_socket_client($context['address']);
        $connectionWrapper = new ConnectionWrapper($socket);

        $connectionWrapper->writeRequest(1, [], '');

        $context['daemon']->run();

        fclose($socket);

        $this->assertContains('Daemon memory limit reached', $context['logger']->getMessages()[1]['message']);
    }

    /**
     * Tests that the daemon shuts down after reaching its time limit.
     */
    public function testTimeLimit()
    {
        $context = $this->createTestingContext(DaemonOptions::NO_LIMIT, DaemonOptions::NO_LIMIT, 1);

        $context['daemon']->run();

        $this->assertContains('Daemon time limit reached', $context['logger']->getMessages()[1]['message']);
    }

    /**
     * Tests that the daemon shuts down after reaching its time limit.
     */
    public function testException()
    {
        $context = $this->createTestingContext();

        $socket            = stream_socket_client($context['address']);
        $connectionWrapper = new ConnectionWrapper($socket);

        $connectionWrapper->writeRequest(1, ['EXCEPTION' => 'boo'], '');

        try {
            $context['daemon']->run();
        } catch (\Exception $exception) {
            $this->assertEquals('boo', $exception->getMessage());
        }

        $this->assertContains('boo', $context['logger']->getMessages()[1]['message']);
    }

    /**
     * Tests that the daemon cleanly handles internal exceptions (such as
     * protocol and connection exceptions).
     */
    public function testDaemonException()
    {
        $context = $this->createTestingContext();

        $socket1            = stream_socket_client($context['address']);
        $connectionWrapper1 = new ConnectionWrapper($socket1);
        $connectionWrapper1->writeRequest(1, ['DAEMON_EXCEPTION' => 'boo'], '');

        $socket2            = stream_socket_client($context['address']);
        $connectionWrapper2 = new ConnectionWrapper($socket2);
        $connectionWrapper2->writeRequest(2, ['SHUTDOWN' => true], '');

        $context['daemon']->run();

        $this->assertContains('boo',  $context['logger']->getMessages()[1]['message']);
    }

    /**
     * Tests that the daemon shuts down after receiving a SIGINT.
     */
    public function testShutdown()
    {
        $context = $this->createTestingContext();

        $socket            = stream_socket_client($context['address']);
        $connectionWrapper = new ConnectionWrapper($socket);

        $connectionWrapper->writeRequest(1, ['SHUTDOWN' => ''], '');

        $context['daemon']->run();

        $this->assertEquals('Daemon shutdown requested (received SIGINT)', $context['logger']->getMessages()[1]['message']);
    }

    /**
     * Tests that daemon auto-shutdown
     */
    public function testAutoShutdown()
    {
        $context = $this->createTestingContext(
            DaemonOptions::NO_LIMIT, DaemonOptions::NO_LIMIT,
            DaemonOptions::NO_LIMIT, true
        );

        $socket            = stream_socket_client($context['address']);
        $connectionWrapper = new ConnectionWrapper($socket);

        $connectionWrapper->writeRequest(1, ['TEST_AUTO_SHUTDOWN' => ''], '');

        $context['daemon']->run();

        $this->assertEquals('Automatic shutdown following status code: 500', $context['logger']->getMessages()[1]['message']);
    }

    private function createTestingContext($requestLimit = DaemonOptions::NO_LIMIT, $memoryLimit = DaemonOptions::NO_LIMIT, $timeLimit = DaemonOptions::NO_LIMIT, $autoShutdown = false)
    {
        $context = [
            'kernel' => new MockKernel([
                'handleRequest' => function (RequestInterface $request) {
                    $params = $request->getParams();

                    if (isset($params['EXCEPTION'])) {
                        throw new \Exception($params['EXCEPTION']);
                    } elseif (isset($params['DAEMON_EXCEPTION'])) {
                        throw new UserlandDaemonException($params['DAEMON_EXCEPTION']);
                    } elseif (isset($params['SHUTDOWN'])) {
                        posix_kill(posix_getpid(), SIGINT);
                    } elseif (isset($params['TEST_AUTO_SHUTDOWN'])) {
                        return new Response('php://memory', 500);
                    }

                    return new Response();
                },
            ]),
            'logger'  => new InMemoryLogger(),
            'address' => 'tcp://localhost:7000',
        ];

        $context['options'] = new DaemonOptions([
            DaemonOptions::LOGGER        => $context['logger'],
            DaemonOptions::REQUEST_LIMIT => $requestLimit,
            DaemonOptions::MEMORY_LIMIT  => $memoryLimit,
            DaemonOptions::TIME_LIMIT    => $timeLimit,
            DaemonOptions::AUTO_SHUTDOWN => $autoShutdown,
        ]);

        $context['serverSocket']   = stream_socket_server($context['address']);
        $context['connectionPool'] = new StreamSocketConnectionPool($context['serverSocket']);
        $context['daemon']         = new UserlandDaemon($context['kernel'], $context['options'], $context['connectionPool'], new ConnectionHandlerFactory());

        return $context;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated 9-February-2009 15:26:35.6406250 -->
<!-- Generated by MathSBML 2.7.5 [2-May-2008] -->
<!-- Generated using Mathematica Version 5.2 for Microsoft Windows (June 20, 2005) -->
<sbml xmlns="http://www.sbml.org/sbml/level2/version3"
    level="2"
    version="3">
 <model id="case00663"
     name="case00663"
     metaid="_case00663">
  <!-- <listOfFunctionDefinitions/> -->
  <!-- <listOfUnitDefinitions/> -->
  <!-- <listOfCompartmentTypes/> -->
  <!-- <listOfSpeciesTypes/> -->
  <listOfCompartments>
   <compartment id="C"
       name="C"
       spatialDimensions="3"
       units="volume"
       size="1."/>
  </listOfCompartments>
  <listOfSpecies>
   <species id="S1"
       name="S1"
       compartment="C"
       boundaryCondition="false"
       constant="false"
       initialAmount="0.002"
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
   <species id="S2"
       name="S2"
       compartment="C"
       boundaryCondition="false"
       constant="false"
       initialAmount="0.002"
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
   <species id="S3"
       name="S3"
       compartment="C"
       boundaryCondition="false"
       constant="false"
       initialAmount="0"
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
   <species id="S4"
       name="S4"
       compartment="C"
       boundaryCondition="false"
       constant="false"
       initialAmount="0"
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
  </listOfSpecies>
  <listOfParameters>
   <parameter id="k1"
       name="k1"
       value="1000."/>
   <parameter id="k2"
       name="k2"
       constant="false"/>
   <parameter id="k3"
       name="k3"
       value="0.7"/>
  </listOfParameters>
  <!-- <listOfInitialAssignments/> -->
  <listOfRules>
   <algebraicRule metaid="rule1">
    <math xmlns="http://www.w3.org/1998/Math/MathML">
     <apply>
      <plus/>
      <ci>k2</ci>
      <cn type="real">-0.9</cn>
     </apply>
    </math>
   </algebraicRule>
  </listOfRules>
  <!-- <listOfConstraints/> -->
  <listOfReactions>
   <reaction id="reaction1"
       name="reaction1"
       reversible="false"
       fast="false">
    <listOfReactants>
     <speciesReference species="S1"/>
     <speciesReference species="S2"/>
    </listOfReactants>
    <listOfProducts>
     <speciesReference species="S3"/>
    </listOfProducts>
    <!-- <listOfModifiers/> -->
    <kineticLaw>
     <math xmlns="http://www.w3.org/1998/Math/MathML">
      <apply>
       <times/>
       <ci>C</ci>
       <ci>k1</ci>
       <ci>S1</ci>
       <ci>S2</ci>
      </apply>
     </math>
     <!-- <listOfParameters/> -->
    </kineticLaw>
   </reaction>
   <reaction id="reaction2"
       name="reaction2"
       reversible="false"
       fast="false">
    <listOfReactants>
     <speciesReference species="S3"/>
    </listOfReactants>
    <listOfProducts>
     <speciesReference species="S1"/>
     <speciesReference species="S2"/>
    </listOfProducts>
    <!-- <listOfModifiers/> -->
    <kineticLaw>
     <math xmlns="http://www.w3.org/1998/Math/MathML">
      <apply>
       <times/>
       <ci>C</ci>
       <ci>k2</ci>
       <ci>S3</ci>
      </apply>
     </math>
     <!-- <listOfParameters/> -->
    </kineticLaw>
   </reaction>
   <reaction id="reaction3"
       name="reaction3"
       reversible="false"
       fast="false">
    <listOfReactants>
     <speciesReference species="S3"/>
    </listOfReactants>
    <listOfProducts>
     <speciesReference species="S1"/>
     <speciesReference species="S4"/>
    </listOfProducts>
    <!-- <listOfModifiers/> -->
    <kineticLaw>
     <math xmlns="http://www.w3.org/1998/Math/MathML">
      <apply>
       <times/>
       <ci>C</ci>
       <ci>k3</ci>
       <ci>S3</ci>
      </apply>
     </math>
     <!-- <listOfParameters/> -->
    </kineticLaw>
   </reaction>
  </listOfReactions>
  <listOfEvents>
   <event id="event1"
       name="event1">
    <trigger>
     <math xmlns="http://www.w3.org/1998/Math/MathML">
      <apply>
       <gt/>
       <ci>S4</ci>
       <ci>S3</ci>
      </apply>
     </math>
    </trigger>
    <listOfEventAssignments>
     <eventAssignment variable="S4">
      <math xmlns="http://www.w3.org/1998/Math/MathML">
       <apply>
        <times/>
        <cn type="integer">2</cn>
        <ci>S4</ci>
       </apply>
      </math>
     </eventAssignment>
    </listOfEventAssignments>
   </event>
  </listOfEvents>
 </model>
</sbml>


text:
using System.IO;
using HttpServer.Helpers;
using Xunit;

namespace HttpServer.Test.Helpers
{
	/// <summary>
	/// Tester for the <see cref="ResourceManager"/>
	/// </summary>
	public class ResourceManagerTest : ResourceManager
	{
		private readonly ResourceManager _resouceManager = new ResourceManager();

		/// <summary>Tests mapping of resources</summary>
		[Fact]
		public void Test()
		{
			// Make sure the three resources in the project can be loaded properly
			Assert.Equal(3, _resouceManager.LoadResources("/testUri/tests/", GetType().Assembly, "HttpServer.Test.Helpers.ResourceFiles"));
			Assert.Equal(3, _resouceManager.LoadResources("/", GetType().Assembly, "HttpServer.Test.Helpers.ResourceFiles"));

			Assert.True(_resouceManager.ContainsResource("/test.test.xml"));
			Assert.True(_resouceManager.ContainsResource("teSt.test.txt"));
			Assert.True(_resouceManager.ContainsResource("\\test-Test.xml"));

			Assert.True(_resouceManager.ContainsResource("/testUri/tests/test.test.xml"));
			Assert.True(_resouceManager.ContainsResource("testUri\\tests\\teSt.test.txt"));
			Assert.True(_resouceManager.ContainsResource("/testUri/tests/test-Test.xml"));
			Assert.True(_resouceManager.ContainsResource("/teStUri/Tests/TeSt.teSt.xml"));
			Assert.True(_resouceManager.ContainsResource("/teStUri/Tests/TeSt.teSt.*"));

			using(Stream test = _resouceManager.GetResourceStream("/testUri/tests/test.test.xml"))
				Assert.NotNull(test);

			string[] files = _resouceManager.GetFiles("\\testUri\\tests\\test.test.*");
			Assert.NotNull(files);
			Assert.Equal(2, files.Length);

			files = _resouceManager.GetFiles("\\testUri\\tests\\test.test.xml");
			Assert.NotNull(files);
			Assert.Equal(1, files.Length);

			files = _resouceManager.GetFiles("/testUri/tests/test-test.*");
			Assert.NotNull(files);
			Assert.Equal(1, files.Length);
			Assert.True(files[0] == "/testUri/tests/test-test.xml");
		}
	}
}


text:
require 'spec_helper'
module Alf
  describe Relation, "equality" do

    let(:rel)   { Relation[id: Integer].coerce(id: 12) }
    let(:subrel){ Relation[id:  Fixnum].coerce(id: 12) }
    let(:suprel){ Relation[id: Numeric].coerce(id: 12) }

    context '==' do

      it 'returns true for all pairs above' do
        rel.should eq(subrel)
        subrel.should eq(rel)
        rel.should eq(suprel)
        suprel.should eq(rel)
        subrel.should eq(suprel)
        suprel.should eq(subrel)
      end

      it 'returns true on empty relations' do
        Relation([]).should eq(Relation([]))
      end

      it 'returns true on empty factored relations' do
        type = Relation[id: Integer]
        type.new(Set.new).should eq(type.new(Set.new))
      end

      it 'returns true on empty recursively defined relations' do
        type = Relation.type(id: Integer){|r| {children: r} }

        type.new(Set.new).should eq(type.new(Set.new))

        tuple = {id: 1, children: []}
        type.coerce(tuple).should eq(type.coerce(tuple))
      end
    end

    context 'eql?' do

      it 'returns true for all pairs' do
        rel.should eql(subrel)
        subrel.should eql(rel)
        rel.should eql(suprel)
        suprel.should eql(rel)
        subrel.should eql(suprel)
        suprel.should eql(subrel)
      end
    end

  end
end


text:
<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class FeedbackType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('whereFrom')->add('content')        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Feedback'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'appbundle_feedback';
    }

}


text:
Pattern: Malformed newline after `,` in selector list

Issue: -

## Description

Require a newline or disallow whitespace after the commas of selector lists. End-of-line comments are allowed one space after the comma.

```css
a, /* comment */
b { color: pink; }
```

## Examples

### `"always"`

There *must always* be a newline after the commas.

The following patterns are considered violations:

```css
a, b { color: pink; }
```

```css
a
, b { color: pink; }
```

The following patterns are *not* considered violations:

```css
a,
b { color: pink; }
```

```css
a
,
b { color: pink; }
```

### `"always-multi-line"`

There *must always* be a newline after the commas in multi-line selector lists.

The following patterns are considered violations:

```css
a
, b { color: pink; }
```

The following patterns are *not* considered violations:

```css
a, b { color: pink; }
```

```css
a,
b { color: pink; }
```

```css
a
,
b { color: pink; }
```

### `"never-multi-line"`

There *must never* be whitespace after the commas in multi-line selector lists.

The following patterns are considered violations:

```css
a
, b { color: pink; }
```

```css
a,
b { color: pink; }
```

The following patterns are *not* considered violations:

```css
a,b { color: pink; }
```

```css
a
,b { color: pink; }
```

## Further Reading

* [stylelint - selector-list-comma-newline-after](https://stylelint.io/user-guide/rules/selector-list-comma-newline-after)


text:
//
//  ViewController.m
//  YJFavorEmitter
//
//  Created by splashz on 15/11/2.
//  Copyright © 2015年 splashz. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface YJFavorEmitterCell : CALayer

///左右飘动的周期
@property (nonatomic, assign) CGFloat shiftCycle;
///到达顶部的时间
@property (nonatomic, assign) CGFloat risingDuration;
///元素上升的最小速度
@property (nonatomic, assign) CGFloat minRisingVelocity;
///到达顶部的时间差量
@property (nonatomic, assign) CGFloat risingShiftDuration;
///完全消失的时间
@property (nonatomic, assign) CGFloat fadeOutDuration;
///完全消失的时间差量
@property (nonatomic, assign) CGFloat fadeOutShiftDuration;

/**
 初始化发射元素

 @param frame     元素frame
 @param floatArea 飘浮范围
 @param image     元素图片

 @return 发射元素
 */
+ (instancetype)emitterCellWithFrame:(CGRect)frame
                           floatArea:(CGRect)floatArea
                               image:(UIImage *)image;

- (void)startAnimation;

@end


text:
package ch.ethz.inf.vs.californium.observe;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * This class represents an observing endpoint. It holds all observe relations
 * that the endpoint has to this server. If a confirmable notification timeouts
 * for the maximum times allowed the server assumes the client is no longer
 * reachable and cancels all relations that it has established to resources.
 */
public class ObservingEndpoint {

	/** The endpoint's address */
	private final InetSocketAddress address;

	/** The list of relations the endpoint has established with this server */
	private final List<ObserveRelation> relations;

	/**
	 * Constructs a new ObservingEndpoint.
	 * @param address the endpoint's address
	 */
	public ObservingEndpoint(InetSocketAddress address) {
		this.address = address;
		this.relations = new CopyOnWriteArrayList<ObserveRelation>();
	}

	/**
	 * Adds the specified observe relation.
	 * @param relation the relation
	 */
	public void addObserveRelation(ObserveRelation relation) {
		relations.add(relation);
	}

	/**
	 * Removes the specified observe relations.
	 * @param relation the relation
	 */
	public void removeObserveRelation(ObserveRelation relation) {
		relations.remove(relation);
	}

	/**
	 * Cancels all observe relations that this endpoint has established with
	 * resources from this server.
	 */
	public void cancelAll() {
		for (ObserveRelation relation:relations)
			relation.cancel();
	}

	/**
	 * Returns the address of this endpoint-
	 * @return the address
	 */
	public InetSocketAddress getAddress() {
		return address;
	}

	/*
	 * This class is obsolete now since observe-09 where a client can have
	 * multiple observe relations with the same resource. Furthermore, the
	 * methods above have become much simpler since there is close to no
	 * bookkeeping required.
	 */
//	private static class ResourcePath {
//
//		private final List<String> path;
//
//		private ResourcePath(List<String> path) {
//			if (path == null)
//				throw new NullPointerException();
//			this.path = path;
//		}
//
//		@Override
//		public boolean equals(Object o) {
//			if (! (o instanceof ResourcePath))
//				return false;
//			ResourcePath rp = (ResourcePath) o;
//			return path.equals(rp.path);
//		}
//
//		@Override
//		public int hashCode() {
//			return path.hashCode();
//		}
//	}
}


text:
namespace LightShell.Plugin.Diagnostics.Controls
{
   public partial class PluginView
   {
      public PluginView()
      {
         InitializeComponent();
      }
   }
}


text:
import Products from '../components/Products';
import Footer from '../components/Footer';
import { products } from '../data';

const Shop = () => (
  <>

        Find your favorite clothes!

    <Products products={products} />

  </>
);

export default Shop;


text:
'use strict';

const models = require('./index');

/**
 * Resource properties including location and tags for track resources.
 *
 * @extends models['ProxyResource']
 */
class TrackedResource extends models['ProxyResource'] {
  /**
   * Create a TrackedResource.
   * @member {string} location The location the resource resides in.
   * @member {object} [tags] Application-specific metadata in the form of
   * key-value pairs.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of TrackedResource
   *
   * @returns {object} metadata of TrackedResource
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'TrackedResource',
      type: {
        name: 'Composite',
        className: 'TrackedResource',
        modelProperties: {
          id: {
            required: false,
            readOnly: true,
            serializedName: 'id',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            readOnly: true,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          },
          type: {
            required: false,
            readOnly: true,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          },
          location: {
            required: true,
            serializedName: 'location',
            type: {
              name: 'String'
            }
          },
          tags: {
            required: false,
            serializedName: 'tags',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          }
        }
      }
    };
  }
}

module.exports = TrackedResource;


text:
class CreateSidebars < ActiveRecord::Migration[5.0]
  def change
    create_table :sidebars do |t|
      t.boolean :active, default: false, null: false, index: true
      t.string  :name,                   null: false
      t.string  :heading
      t.text    :text

      t.timestamps                       null: false
    end
  end
end


text:
"""
Canary code that dies if the underlying hardware / drivers aren't working right.
"""
import time

import numpy as np
import tensorflow as tf
from cleverhans.utils_tf import infer_devices

last_run = None

def run_canary():
    """
    Runs some code that will crash if the GPUs / GPU driver are suffering from
    a common bug. This helps to prevent contaminating results in the rest of
    the library with incorrect calculations.
    """

    # Note: please do not edit this function unless you have access to a machine
    # with GPUs suffering from the bug and can verify that the canary still
    # crashes after your edits. Due to the transient nature of the GPU bug it is
    # not possible to unit test the canary in our continuous integration system.

    global last_run
    current = time.time()
    if last_run is None or current - last_run > 3600:
        last_run = current
    else:
        # Run the canary at most once per hour
        return

    # Try very hard not to let the canary affect the graph for the rest of the
    # python process
    canary_graph = tf.Graph()
    with canary_graph.as_default():
        devices = infer_devices()
        num_devices = len(devices)
        if num_devices < 3:
            # We have never observed GPU failure when less than 3 GPUs were used
            return

        v = np.random.RandomState([2018, 10, 16]).randn(2, 2)
        # Try very hard not to let this Variable end up in any collections used
        # by the rest of the python process
        w = tf.Variable(v, trainable=False, collections=[])
        loss = tf.reduce_sum(tf.square(w))

        grads = []
        for device in devices:
            with tf.device(device):
                (grad,) = tf.gradients(loss, w)
                grads.append(grad)

        sess = tf.Session()
        sess.run(tf.variables_initializer([w]))
        grads = sess.run(grads)
        first = grads[0]
        for grad in grads[1:]:
            if not np.allclose(first, grad):
                first_string = str(first)
                grad_string = str(grad)
                raise RuntimeError(
                    "Something is wrong with your GPUs or GPU driver."
                    "%(num_devices)d different GPUS were asked to "
                    "calculate the same 2x2 gradient. One returned "
                    "%(first_string)s and another returned "
                    "%(grad_string)s. This can usually be fixed by "
                    "rebooting the machine."
                    % {
                        "num_devices": num_devices,
                        "first_string": first_string,
                        "grad_string": grad_string,
                    }
                )
        sess.close()

if __name__ == "__main__":
    run_canary()


text:
pytest-2.5.1: fixes and new home page styling
===========================================================================

pytest is a mature Python testing tool with more than a 1000 tests
against itself, passing on many different interpreters and platforms.

The 2.5.1 release maintains the "zero-reported-bugs" promise by fixing
the three bugs reported since the last release a few days ago.  It also
features a new home page styling implemented by Tobias Bieniek, based on
the flask theme from Armin Ronacher:

    http://pytest.org

If you have anything more to improve styling and docs,
we'd be very happy to merge further pull requests.

On the coding side, the release also contains a little enhancement to
fixture decorators allowing to directly influence generation of test
ids, thanks to Floris Bruynooghe.  Other thanks for helping with
this release go to Anatoly Bubenkoff and Ronny Pfannschmidt.

As usual, you can upgrade from pypi via::

    pip install -U pytest

have fun and a nice remaining "bug-free" time of the year :)
holger krekel

2.5.1
-----------------------------------

- merge new documentation styling PR from Tobias Bieniek.

- fix issue403: allow parametrize of multiple same-name functions within
  a collection node.  Thanks Andreas Kloeckner and Alex Gaynor for reporting
  and analysis.

- Allow parameterized fixtures to specify the ID of the parameters by
  adding an ids argument to pytest.fixture() and pytest.yield_fixture().
  Thanks Floris Bruynooghe.

- fix issue404 by always using the binary xml escape in the junitxml
  plugin.  Thanks Ronny Pfannschmidt.

- fix issue407: fix addoption docstring to point to argparse instead of
  optparse. Thanks Daniel D. Wright.