text:
package org.apache.camel.component.jms.issues;

import javax.jms.ConnectionFactory;
import javax.jms.Destination;

import org.apache.camel.Body;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Header;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jms.CamelJmsTestHelper;
import org.apache.camel.component.jms.JmsConstants;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge;

/**
 * @version $Revision$
 */
public class TempReplyToIssueTest extends CamelTestSupport {

    @Test
    public void testReplyToIssue() throws Exception {
        String out = template.requestBody("activemq:queue:test.queue", "World", String.class);
        // we should receive that fixed reply
        assertEquals("Hello Moon", out);
    }

    public String handleMessage(@Header("JMSReplyTo") final Destination jmsReplyTo,
                                @Header("JMSCorrelationID") final String id,
                                @Body String body, Exchange exchange) throws Exception {
        assertNotNull(jmsReplyTo);
        assertTrue("Should be a temp queue", jmsReplyTo.toString().startsWith("temp-queue"));

        // we send the reply manually (notice we just use a bogus endpoint uri)
        ProducerTemplate producer = exchange.getContext().createProducerTemplate();
        producer.send("activemq:queue:xxx", new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setBody("Hello Moon");
                // remember to set correlation id
                exchange.getIn().setHeader("JMSCorrelationID", id);
                // this is the real destination we send the reply to
                exchange.getIn().setHeader(JmsConstants.JMS_DESTINATION, jmsReplyTo);
            }
        });
        // stop it after use
        producer.stop();

        // sleep a bit so Camel will send the reply a bit later
        Thread.sleep(1000);

        // this will later cause a problem as the temp queue has been deleted
        // and exceptions will be logged etc
        return "Hello " + body;
    }

    protected CamelContext createCamelContext() throws Exception {
        CamelContext camelContext = super.createCamelContext();
        ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory();
        camelContext.addComponent("activemq", jmsComponentAutoAcknowledge(connectionFactory));
        return camelContext;
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("activemq:queue:test.queue").bean(TempReplyToIssueTest.class, "handleMessage");
            }
        };
    }
}


text:
namespace test {
    // Just move along if source-map-support is not available
    try {
        require('source-map-support/register');
    } catch (e) { }

    const startTime = Date.now();

    process.on('exit', (code: number) => {
        if (code != 0) {
            process.stdout.write("\t\x1b[31mFAILED\x1b[0m\n");
        } else {
            process.stdout.write(`\tCompleted in ${Date.now() - startTime} ms\n`);
        }
    });

    export const assert: {
        fail<T>(actual?: T, expected?: T, message?: string, operator?: string): void;
        ok<T>(value: T, message?: string): void;
        equal<T>(actual: T, expected: T, message?: string): void;
        notEqual<T>(actual: T, expected: T, message?: string): void;
        deepEqual<T>(actual: T, expected: T, message?: string): void;
        notDeepEqual<T>(acutal: T, expected: T, message?: string): void;
        strictEqual<T>(actual: T, expected: T, message?: string): void;
        notStrictEqual<T>(actual: T, expected: T, message?: string): void;
        deepStrictEqual<T>(actual: T, expected: T, message?: string): void;
        notDeepStrictEqual<T>(actual: T, expected: T, message?: string): void;
        throws: {
            (block: Function, message?: string): void;
            (block: Function, error: Function, message?: string): void;
            (block: Function, error: RegExp, message?: string): void;
            (block: Function, error: (err: any) => boolean, message?: string): void;
        };
        doesNotThrow: {
            (block: Function, message?: string): void;
            (block: Function, error: Function, message?: string): void;
            (block: Function, error: RegExp, message?: string): void;
            (block: Function, error: (err: any) => boolean, message?: string): void;
        }
        ifError<T>(value: T): void;
    } = require('assert');
}

redpajama_set_name: RedPajamaGithub


text:
from setuptools import setup

setup_requires = [
    'nose',
    'coverage',
]
install_requires = [
    'h5py',
    'numpy',
    'scipy',
    'six',
]
tests_require = []

description = "Scipy sparse matrix in HDF5."

long_description = """\
Please visit  the `Github repository <https://github.com/appier/h5sparse>`_
for more information.\n
"""
with open('README.rst') as fp:
    long_description += fp.read()

setup(
    name='h5sparse',
    version="0.1.0",
    description=description,
    long_description=long_description,
    author='Appier Inc.',
    url='https://github.com/appier/h5sparse',
    setup_requires=setup_requires,
    install_requires=install_requires,
    tests_require=tests_require,
    license="MIT",
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'Intended Audience :: Information Technology',
        'Intended Audience :: Science/Research',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Topic :: Scientific/Engineering',
        'Topic :: Database',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'License :: OSI Approved :: MIT License',
    ],
    test_suite='nose.collector',
    packages=[
        'h5sparse',
    ],
)


text:
package org.apache.tomcat.util.net;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.FileChannel;
import java.nio.channels.NetworkChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.collections.SynchronizedQueue;
import org.apache.tomcat.util.collections.SynchronizedStack;
import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
import org.apache.tomcat.util.net.jsse.JSSESupport;

/**
 * NIO tailored thread pool, providing the following services:
 *

 *
Socket acceptor thread

 *
Socket poller thread

 *
Worker threads pool

 *

 *
 * When switching to Java 5, there's an opportunity to use the virtual
 * machine's thread pool.
 *
 * @author Mladen Turk
 * @author Remy Maucherat
 */
public class NioEndpoint extends AbstractJsseEndpoint<NioChannel,SocketChannel> {

    // -------------------------------------------------------------- Constants

    private static final Log log = LogFactory.getLog(NioEndpoint.class);

    public static final int OP_REGISTER = 0x100; //register interest op

    // ----------------------------------------------------------------- Fields

    private NioSelectorPool selectorPool = new NioSelectorPool();

    /**
     * Server socket "pointer".
     */
    private ServerSocketChannel serverSock = null;

    /**
     *
     */
    private volatile CountDownLatch stopLatch = null;

    /**
     * Cache for poller events
     */
    private SynchronizedStack<PollerEvent> eventCache;

    /**
     * Bytebuffer cache, each channel holds a set of buffers (two, except for SSL holds four)
     */
    private SynchronizedStack<NioChannel> nioChannels;

    // ------------------------------------------------------------- Properties

    /**
     * Generic properties, introspected
     */
    @Override
    public boolean setProperty(String name, String value) {
        final String selectorPoolName = "selectorPool.";
        try {
            if (name.startsWith(selectorPoolName)) {
                return IntrospectionUtils.setProperty(selectorPool, name.substring(selectorPoolName.length()), value);
            } else {
                return super.setProperty(name, value);
            }
        }catch ( Exception x ) {
            log.error("Unable to set attribute \""+name+"\" to \""+value+"\"",x);
            return false;
        }
    }

    /**
     * Priority of the poller threads.
     */
    private int pollerThreadPriority = Thread.NORM_PRIORITY;
    public void setPollerThreadPriority(int pollerThreadPriority) { this.pollerThreadPriority = pollerThreadPriority; }
    public int getPollerThreadPriority() { return pollerThreadPriority; }

    /**
     * Poller thread count.
     */
    private int pollerThreadCount = Math.min(2,Runtime.getRuntime().availableProcessors());
    public void setPollerThreadCount(int pollerThreadCount) { this.pollerThreadCount = pollerThreadCount; }
    public int getPollerThreadCount() { return pollerThreadCount; }

    private long selectorTimeout = 1000;
    public void setSelectorTimeout(long timeout){ this.selectorTimeout = timeout;}
    public long getSelectorTimeout(){ return this.selectorTimeout; }
    /**
     * The socket poller.
     */
    private Poller[] pollers = null;
    private AtomicInteger pollerRotater = new AtomicInteger(0);
    /**
     * Return an available poller in true round robin fashion.
     *
     * @return The next poller in sequence
     */
    public Poller getPoller0() {
        int idx = Math.abs(pollerRotater.incrementAndGet()) % pollers.length;
        return pollers[idx];
    }

    public void setSelectorPool(NioSelectorPool selectorPool) {
        this.selectorPool = selectorPool;
    }

    /**
     * Is deferAccept supported?
     */
    @Override
    public boolean getDeferAccept() {
        // Not supported
        return false;
    }

    // --------------------------------------------------------- Public Methods
    /**
     * Number of keep-alive sockets.
     *
     * @return The number of sockets currently in the keep-alive state waiting
     *         for the next request to be received on the socket
     */
    public int getKeepAliveCount() {
        if (pollers == null) {
            return 0;
        } else {
            int sum = 0;
            for (int i=0; i<pollers.length; i++) {
                sum += pollers[i].getKeyCount();
            }
            return sum;
        }
    }

    // ----------------------------------------------- Public Lifecycle Methods

    /**
     * Initialize the endpoint.
     */
    @Override
    public void bind() throws Exception {

        serverSock = ServerSocketChannel.open();
        socketProperties.setProperties(serverSock.socket());
        InetSocketAddress addr = (getAddress()!=null?new InetSocketAddress(getAddress(),getPort()):new InetSocketAddress(getPort()));
        serverSock.socket().bind(addr,getAcceptCount());
        serverSock.configureBlocking(true); //mimic APR behavior

        // Initialize thread count defaults for acceptor, poller
        if (acceptorThreadCount == 0) {
            // FIXME: Doesn't seem to work that well with multiple accept threads
            acceptorThreadCount = 1;
        }
        if (pollerThreadCount <= 0) {
            //minimum one poller thread
            pollerThreadCount = 1;
        }
        setStopLatch(new CountDownLatch(pollerThreadCount));

        // Initialize SSL if needed
        initialiseSsl();

        selectorPool.open();
    }

    /**
     * Start the NIO endpoint, creating acceptor, poller threads.
     */
    @Override
    public void startInternal() throws Exception {

        if (!running) {
            running = true;
            paused = false;

            processorCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
                    socketProperties.getProcessorCache());
            eventCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
                            socketProperties.getEventCache());
            nioChannels = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
                    socketProperties.getBufferPool());

            // Create worker collection
            if ( getExecutor() == null ) {
                createExecutor();
            }

            initializeConnectionLatch();

            // Start poller threads
            pollers = new Poller[getPollerThreadCount()];
            for (int i=0; i<pollers.length; i++) {
                pollers[i] = new Poller();
                Thread pollerThread = new Thread(pollers[i], getName() + "-ClientPoller-"+i);
                pollerThread.setPriority(threadPriority);
                pollerThread.setDaemon(true);
                pollerThread.start();
            }

            startAcceptorThreads();
        }
    }

    /**
     * Stop the endpoint. This will cause all processing threads to stop.
     */
    @Override
    public void stopInternal() {
        releaseConnectionLatch();
        if (!paused) {
            pause();
        }
        if (running) {
            running = false;
            unlockAccept();
            for (int i=0; pollers!=null && i<pollers.length; i++) {
                if (pollers[i]==null) continue;
                pollers[i].destroy();
                pollers[i] = null;
            }
            try {
                getStopLatch().await(selectorTimeout + 100, TimeUnit.MILLISECONDS);
            } catch (InterruptedException ignore) {
            }
            shutdownExecutor();
            eventCache.clear();
            nioChannels.clear();
            processorCache.clear();
        }

    }

    /**
     * Deallocate NIO memory pools, and close server socket.
     */
    @Override
    public void unbind() throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Destroy initiated for "+new InetSocketAddress(getAddress(),getPort()));
        }
        if (running) {
            stop();
        }
        // Close server socket
        serverSock.socket().close();
        serverSock.close();
        serverSock = null;
        destroySsl();
        super.unbind();
        if (getHandler() != null ) {
            getHandler().recycle();
        }
        selectorPool.close();
        if (log.isDebugEnabled()) {
            log.debug("Destroy completed for "+new InetSocketAddress(getAddress(),getPort()));
        }
    }

    // ------------------------------------------------------ Protected Methods

    public NioSelectorPool getSelectorPool() {
        return selectorPool;
    }

    protected CountDownLatch getStopLatch() {
        return stopLatch;
    }

    protected void setStopLatch(CountDownLatch stopLatch) {
        this.stopLatch = stopLatch;
    }

    /**
     * Process the specified connection.
     * @param socket The socket channel
     * @return true if the socket was correctly configured
     *  and processing may continue, false if the socket needs to be
     *  close immediately
     */
    @Override
    protected boolean setSocketOptions(SocketChannel socket) {
        // Process the connection
        try {
            //disable blocking, APR style, we are gonna be polling it
            socket.configureBlocking(false);
            Socket sock = socket.socket();
            socketProperties.setProperties(sock);

            NioChannel channel = nioChannels.pop();
            if (channel == null) {
                SocketBufferHandler bufhandler = new SocketBufferHandler(
                        socketProperties.getAppReadBufSize(),
                        socketProperties.getAppWriteBufSize(),
                        socketProperties.getDirectBuffer());
                if (isSSLEnabled()) {
                    channel = new SecureNioChannel(socket, bufhandler, selectorPool, this);
                } else {
                    channel = new NioChannel(socket, bufhandler);
                }
            } else {
                channel.setIOChannel(socket);
                channel.reset();
            }
            getPoller0().register(channel);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            try {
                log.error("",t);
            } catch (Throwable tt) {
                ExceptionUtils.handleThrowable(tt);
            }
            // Tell to close the socket
            return false;
        }
        return true;
    }

    @Override
    protected void closeSocket(SocketChannel socket) {
        countDownConnection();
        try {
            socket.socket().close();
        } catch (IOException ioe)  {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("endpoint.err.close"), ioe);
            }
        }
        try {
            socket.close();
        } catch (IOException ioe) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("endpoint.err.close"), ioe);
            }
        }
    }

    @Override
    protected NetworkChannel getServerSocket() {
        return serverSock;
    }

    @Override
    protected SocketChannel serverSocketAccept() throws Exception {
        return serverSock.accept();
    }

    @Override
    protected Log getLog() {
        return log;
    }

    @Override
    protected SocketProcessorBase<NioChannel> createSocketProcessor(
            SocketWrapperBase<NioChannel> socketWrapper, SocketEvent event) {
        return new SocketProcessor(socketWrapper, event);
    }

    private void close(NioChannel socket, SelectionKey key) {
        try {
            if (socket.getPoller().cancelledKey(key) != null) {
                // SocketWrapper (attachment) was removed from the
                // key - recycle the key. This can only happen once
                // per attempted closure so it is used to determine
                // whether or not to return the key to the cache.
                // We do NOT want to do this more than once - see BZ
                // 57340 / 57943.
                if (running && !paused) {
                    if (!nioChannels.push(socket)) {
                        socket.free();
                    }
                }
            }
        } catch (Exception x) {
            log.error("",x);
        }
    }

    // ----------------------------------------------------- Poller Inner Classes

    /**
     *
     * PollerEvent, cacheable object for poller events to avoid GC
     */
    public static class PollerEvent implements Runnable {

        private NioChannel socket;
        private int interestOps;
        private NioSocketWrapper socketWrapper;

        public PollerEvent(NioChannel ch, NioSocketWrapper w, int intOps) {
            reset(ch, w, intOps);
        }

        public void reset(NioChannel ch, NioSocketWrapper w, int intOps) {
            socket = ch;
            interestOps = intOps;
            socketWrapper = w;
        }

        public void reset() {
            reset(null, null, 0);
        }

        @Override
        public void run() {
            if (interestOps == OP_REGISTER) {
                try {
                    socket.getIOChannel().register(
                            socket.getPoller().getSelector(), SelectionKey.OP_READ, socketWrapper);
                } catch (Exception x) {
                    log.error(sm.getString("endpoint.nio.registerFail"), x);
                }
            } else {
                final SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector());
                try {
                    if (key == null) {
                        // The key was cancelled (e.g. due to socket closure)
                        // and removed from the selector while it was being
                        // processed. Count down the connections at this point
                        // since it won't have been counted down when the socket
                        // closed.
                        socket.socketWrapper.getEndpoint().countDownConnection();
                    } else {
                        final NioSocketWrapper socketWrapper = (NioSocketWrapper) key.attachment();
                        if (socketWrapper != null) {
                            //we are registering the key to start with, reset the fairness counter.
                            int ops = key.interestOps() | interestOps;
                            socketWrapper.interestOps(ops);
                            key.interestOps(ops);
                        } else {
                            socket.getPoller().cancelledKey(key);
                        }
                    }
                } catch (CancelledKeyException ckx) {
                    try {
                        socket.getPoller().cancelledKey(key);
                    } catch (Exception ignore) {}
                }
            }
        }

        @Override
        public String toString() {
            return "Poller event: socket [" + socket + "], socketWrapper [" + socketWrapper +
                    "], interestOps [" + interestOps + "]";
        }
    }

    /**
     * Poller class.
     */
    public class Poller implements Runnable {

        private Selector selector;
        private final SynchronizedQueue<PollerEvent> events =
                new SynchronizedQueue<>();

        private volatile boolean close = false;
        private long nextExpiration = 0;//optimize expiration handling

        private AtomicLong wakeupCounter = new AtomicLong(0);

        private volatile int keyCount = 0;

        public Poller() throws IOException {
            this.selector = Selector.open();
        }

        public int getKeyCount() { return keyCount; }

        public Selector getSelector() { return selector;}

        /**
         * Destroy the poller.
         */
        protected void destroy() {
            // Wait for polltime before doing anything, so that the poller threads
            // exit, otherwise parallel closure of sockets which are still
            // in the poller can cause problems
            close = true;
            selector.wakeup();
        }

        private void addEvent(PollerEvent event) {
            events.offer(event);
            if ( wakeupCounter.incrementAndGet() == 0 ) selector.wakeup();
        }

        /**
         * Add specified socket and associated pool to the poller. The socket will
         * be added to a temporary array, and polled first after a maximum amount
         * of time equal to pollTime (in most cases, latency will be much lower,
         * however).
         *
         * @param socket to add to the poller
         * @param interestOps Operations for which to register this socket with
         *                    the Poller
         */
        public void add(final NioChannel socket, final int interestOps) {
            PollerEvent r = eventCache.pop();
            if ( r==null) r = new PollerEvent(socket,null,interestOps);
            else r.reset(socket,null,interestOps);
            addEvent(r);
            if (close) {
                NioEndpoint.NioSocketWrapper ka = (NioEndpoint.NioSocketWrapper)socket.getAttachment();
                processSocket(ka, SocketEvent.STOP, false);
            }
        }

        /**
         * Processes events in the event queue of the Poller.
         *
         * @return true if some events were processed,
         *   false if queue was empty
         */
        public boolean events() {
            boolean result = false;

            PollerEvent pe = null;
            while ( (pe = events.poll()) != null ) {
                result = true;
                try {
                    pe.run();
                    pe.reset();
                    if (running && !paused) {
                        eventCache.push(pe);
                    }
                } catch ( Throwable x ) {
                    log.error("",x);
                }
            }

            return result;
        }

        /**
         * Registers a newly created socket with the poller.
         *
         * @param socket    The newly created socket
         */
        public void register(final NioChannel socket) {
            socket.setPoller(this);
            NioSocketWrapper ka = new NioSocketWrapper(socket, NioEndpoint.this);
            socket.setSocketWrapper(ka);
            ka.setPoller(this);
            ka.setReadTimeout(getConnectionTimeout());
            ka.setWriteTimeout(getConnectionTimeout());
            ka.setKeepAliveLeft(NioEndpoint.this.getMaxKeepAliveRequests());
            ka.setSecure(isSSLEnabled());
            PollerEvent r = eventCache.pop();
            ka.interestOps(SelectionKey.OP_READ);//this is what OP_REGISTER turns into.
            if ( r==null) r = new PollerEvent(socket,ka,OP_REGISTER);
            else r.reset(socket,ka,OP_REGISTER);
            addEvent(r);
        }

        public NioSocketWrapper cancelledKey(SelectionKey key) {
            NioSocketWrapper ka = null;
            try {
                if ( key == null ) return null;//nothing to do
                ka = (NioSocketWrapper) key.attach(null);
                if (ka != null) {
                    // If attachment is non-null then there may be a current
                    // connection with an associated processor.
                    getHandler().release(ka);
                }
                if (key.isValid()) key.cancel();
                if (key.channel().isOpen()) {
                    try {
                        key.channel().close();
                    } catch (Exception e) {
                        if (log.isDebugEnabled()) {
                            log.debug(sm.getString(
                                    "endpoint.debug.channelCloseFail"), e);
                        }
                    }
                }
                try {
                    if (ka!=null) {
                        ka.getSocket().close(true);
                    }
                } catch (Exception e){
                    if (log.isDebugEnabled()) {
                        log.debug(sm.getString(
                                "endpoint.debug.socketCloseFail"), e);
                    }
                }
                try {
                    if (ka != null && ka.getSendfileData() != null
                            && ka.getSendfileData().fchannel != null
                            && ka.getSendfileData().fchannel.isOpen()) {
                        ka.getSendfileData().fchannel.close();
                    }
                } catch (Exception ignore) {
                }
                if (ka != null) {
                    countDownConnection();
                }
            } catch (Throwable e) {
                ExceptionUtils.handleThrowable(e);
                if (log.isDebugEnabled()) log.error("",e);
            }
            return ka;
        }

        /**
         * The background thread that adds sockets to the Poller, checks the
         * poller for triggered events and hands the associated socket off to an
         * appropriate processor as events occur.
         */
        @Override
        public void run() {
            // Loop until destroy() is called
            while (true) {

                boolean hasEvents = false;

                try {
                    if (!close) {
                        hasEvents = events();
                        if (wakeupCounter.getAndSet(-1) > 0) {
                            //if we are here, means we have other stuff to do
                            //do a non blocking select
                            keyCount = selector.selectNow();
                        } else {
                            keyCount = selector.select(selectorTimeout);
                        }
                        wakeupCounter.set(0);
                    }
                    if (close) {
                        events();
                        timeout(0, false);
                        try {
                            selector.close();
                        } catch (IOException ioe) {
                            log.error(sm.getString("endpoint.nio.selectorCloseFail"), ioe);
                        }
                        break;
                    }
                } catch (Throwable x) {
                    ExceptionUtils.handleThrowable(x);
                    log.error("",x);
                    continue;
                }
                //either we timed out or we woke up, process events first
                if ( keyCount == 0 ) hasEvents = (hasEvents | events());

                Iterator<SelectionKey> iterator =
                    keyCount > 0 ? selector.selectedKeys().iterator() : null;
                // Walk through the collection of ready keys and dispatch
                // any active event.
                while (iterator != null && iterator.hasNext()) {
                    SelectionKey sk = iterator.next();
                    NioSocketWrapper attachment = (NioSocketWrapper)sk.attachment();
                    // Attachment may be null if another thread has called
                    // cancelledKey()
                    if (attachment == null) {
                        iterator.remove();
                    } else {
                        iterator.remove();
                        processKey(sk, attachment);
                    }
                }//while

                //process timeouts
                timeout(keyCount,hasEvents);
            }//while

            getStopLatch().countDown();
        }

        protected void processKey(SelectionKey sk, NioSocketWrapper attachment) {
            try {
                if ( close ) {
                    cancelledKey(sk);
                } else if ( sk.isValid() && attachment != null ) {
                    if (sk.isReadable() || sk.isWritable() ) {
                        if ( attachment.getSendfileData() != null ) {
                            processSendfile(sk,attachment, false);
                        } else {
                            unreg(sk, attachment, sk.readyOps());
                            boolean closeSocket = false;
                            // Read goes before write
                            if (sk.isReadable()) {
                                if (!processSocket(attachment, SocketEvent.OPEN_READ, true)) {
                                    closeSocket = true;
                                }
                            }
                            if (!closeSocket && sk.isWritable()) {
                                if (!processSocket(attachment, SocketEvent.OPEN_WRITE, true)) {
                                    closeSocket = true;
                                }
                            }
                            if (closeSocket) {
                                cancelledKey(sk);
                            }
                        }
                    }
                } else {
                    //invalid key
                    cancelledKey(sk);
                }
            } catch ( CancelledKeyException ckx ) {
                cancelledKey(sk);
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                log.error("",t);
            }
        }

        public SendfileState processSendfile(SelectionKey sk, NioSocketWrapper socketWrapper,
                boolean calledByProcessor) {
            NioChannel sc = null;
            try {
                unreg(sk, socketWrapper, sk.readyOps());
                SendfileData sd = socketWrapper.getSendfileData();

                if (log.isTraceEnabled()) {
                    log.trace("Processing send file for: " + sd.fileName);
                }

                if (sd.fchannel == null) {
                    // Setup the file channel
                    File f = new File(sd.fileName);
                    @SuppressWarnings("resource") // Closed when channel is closed
                    FileInputStream fis = new FileInputStream(f);
                    sd.fchannel = fis.getChannel();
                }

                // Configure output channel
                sc = socketWrapper.getSocket();
                // TLS/SSL channel is slightly different
                WritableByteChannel wc = ((sc instanceof SecureNioChannel)?sc:sc.getIOChannel());

                // We still have data in the buffer
                if (sc.getOutboundRemaining()>0) {
                    if (sc.flushOutbound()) {
                        socketWrapper.updateLastWrite();
                    }
                } else {
                    long written = sd.fchannel.transferTo(sd.pos,sd.length,wc);
                    if (written > 0) {
                        sd.pos += written;
                        sd.length -= written;
                        socketWrapper.updateLastWrite();
                    } else {
                        // Unusual not to be able to transfer any bytes
                        // Check the length was set correctly
                        if (sd.fchannel.size() <= sd.pos) {
                            throw new IOException("Sendfile configured to " +
                                    "send more data than was available");
                        }
                    }
                }
                if (sd.length <= 0 && sc.getOutboundRemaining()<=0) {
                    if (log.isDebugEnabled()) {
                        log.debug("Send file complete for: "+sd.fileName);
                    }
                    socketWrapper.setSendfileData(null);
                    try {
                        sd.fchannel.close();
                    } catch (Exception ignore) {
                    }
                    // For calls from outside the Poller, the caller is
                    // responsible for registering the socket for the
                    // appropriate event(s) if sendfile completes.
                    if (!calledByProcessor) {
                        switch (sd.keepAliveState) {
                        case NONE: {
                            if (log.isDebugEnabled()) {
                                log.debug("Send file connection is being closed");
                            }
                            close(sc, sk);
                            break;
                        }
                        case PIPELINED: {
                            if (log.isDebugEnabled()) {
                                log.debug("Connection is keep alive, processing pipe-lined data");
                            }
                            if (!processSocket(socketWrapper, SocketEvent.OPEN_READ, true)) {
                                close(sc, sk);
                            }
                            break;
                        }
                        case OPEN: {
                            if (log.isDebugEnabled()) {
                                log.debug("Connection is keep alive, registering back for OP_READ");
                            }
                            reg(sk,socketWrapper,SelectionKey.OP_READ);
                            break;
                        }
                        }
                    }
                    return SendfileState.DONE;
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("OP_WRITE for sendfile: " + sd.fileName);
                    }
                    if (calledByProcessor) {
                        add(socketWrapper.getSocket(),SelectionKey.OP_WRITE);
                    } else {
                        reg(sk,socketWrapper,SelectionKey.OP_WRITE);
                    }
                    return SendfileState.PENDING;
                }
            } catch (IOException x) {
                if (log.isDebugEnabled()) log.debug("Unable to complete sendfile request:", x);
                if (!calledByProcessor && sc != null) {
                    close(sc, sk);
                }
                return SendfileState.ERROR;
            } catch (Throwable t) {
                log.error("", t);
                if (!calledByProcessor && sc != null) {
                    close(sc, sk);
                }
                return SendfileState.ERROR;
            }
        }

        protected void unreg(SelectionKey sk, NioSocketWrapper attachment, int readyOps) {
            //this is a must, so that we don't have multiple threads messing with the socket
            reg(sk,attachment,sk.interestOps()& (~readyOps));
        }

        protected void reg(SelectionKey sk, NioSocketWrapper attachment, int intops) {
            sk.interestOps(intops);
            attachment.interestOps(intops);
        }

        protected void timeout(int keyCount, boolean hasEvents) {
            long now = System.currentTimeMillis();
            // This method is called on every loop of the Poller. Don't process
            // timeouts on every loop of the Poller since that would create too
            // much load and timeouts can afford to wait a few seconds.
            // However, do process timeouts if any of the following are true:
            // - the selector simply timed out (suggests there isn't much load)
            // - the nextExpiration time has passed
            // - the server socket is being closed
            if (nextExpiration > 0 && (keyCount > 0 || hasEvents) && (now < nextExpiration) && !close) {
                return;
            }
            //timeout
            int keycount = 0;
            try {
                for (SelectionKey key : selector.keys()) {
                    keycount++;
                    try {
                        NioSocketWrapper ka = (NioSocketWrapper) key.attachment();
                        if ( ka == null ) {
                            cancelledKey(key); //we don't support any keys without attachments
                        } else if (close) {
                            key.interestOps(0);
                            ka.interestOps(0); //avoid duplicate stop calls
                            processKey(key,ka);
                        } else if ((ka.interestOps()&SelectionKey.OP_READ) == SelectionKey.OP_READ ||
                                  (ka.interestOps()&SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
                            boolean isTimedOut = false;
                            // Check for read timeout
                            if ((ka.interestOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                                long delta = now - ka.getLastRead();
                                long timeout = ka.getReadTimeout();
                                isTimedOut = timeout > 0 && delta > timeout;
                            }
                            // Check for write timeout
                            if (!isTimedOut && (ka.interestOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
                                long delta = now - ka.getLastWrite();
                                long timeout = ka.getWriteTimeout();
                                isTimedOut = timeout > 0 && delta > timeout;
                            }
                            if (isTimedOut) {
                                key.interestOps(0);
                                ka.interestOps(0); //avoid duplicate timeout calls
                                ka.setError(new SocketTimeoutException());
                                if (!processSocket(ka, SocketEvent.ERROR, true)) {
                                    cancelledKey(key);
                                }
                            }
                        }
                    }catch ( CancelledKeyException ckx ) {
                        cancelledKey(key);
                    }
                }//for
            } catch (ConcurrentModificationException cme) {
                // See https://bz.apache.org/bugzilla/show_bug.cgi?id=57943
                log.warn(sm.getString("endpoint.nio.timeoutCme"), cme);
            }
            long prevExp = nextExpiration; //for logging purposes only
            nextExpiration = System.currentTimeMillis() +
                    socketProperties.getTimeoutInterval();
            if (log.isTraceEnabled()) {
                log.trace("timeout completed: keys processed=" + keycount +
                        "; now=" + now + "; nextExpiration=" + prevExp +
                        "; keyCount=" + keyCount + "; hasEvents=" + hasEvents +
                        "; eval=" + ((now < prevExp) && (keyCount>0 || hasEvents) && (!close) ));
            }

        }
    }

    // ---------------------------------------------------- Key Attachment Class
    public static class NioSocketWrapper extends SocketWrapperBase<NioChannel> {

        private final NioSelectorPool pool;

        private Poller poller = null;
        private int interestOps = 0;
        private CountDownLatch readLatch = null;
        private CountDownLatch writeLatch = null;
        private volatile SendfileData sendfileData = null;
        private volatile long lastRead = System.currentTimeMillis();
        private volatile long lastWrite = lastRead;

        public NioSocketWrapper(NioChannel channel, NioEndpoint endpoint) {
            super(channel, endpoint);
            pool = endpoint.getSelectorPool();
            socketBufferHandler = channel.getBufHandler();
        }

        public Poller getPoller() { return poller;}
        public void setPoller(Poller poller){this.poller = poller;}
        public int interestOps() { return interestOps;}
        public int interestOps(int ops) { this.interestOps  = ops; return ops; }
        public CountDownLatch getReadLatch() { return readLatch; }
        public CountDownLatch getWriteLatch() { return writeLatch; }
        protected CountDownLatch resetLatch(CountDownLatch latch) {
            if ( latch==null || latch.getCount() == 0 ) return null;
            else throw new IllegalStateException("Latch must be at count 0");
        }
        public void resetReadLatch() { readLatch = resetLatch(readLatch); }
        public void resetWriteLatch() { writeLatch = resetLatch(writeLatch); }

        protected CountDownLatch startLatch(CountDownLatch latch, int cnt) {
            if ( latch == null || latch.getCount() == 0 ) {
                return new CountDownLatch(cnt);
            }
            else throw new IllegalStateException("Latch must be at count 0 or null.");
        }
        public void startReadLatch(int cnt) { readLatch = startLatch(readLatch,cnt);}
        public void startWriteLatch(int cnt) { writeLatch = startLatch(writeLatch,cnt);}

        protected void awaitLatch(CountDownLatch latch, long timeout, TimeUnit unit) throws InterruptedException {
            if ( latch == null ) throw new IllegalStateException("Latch cannot be null");
            // Note: While the return value is ignored if the latch does time
            //       out, logic further up the call stack will trigger a
            //       SocketTimeoutException
            latch.await(timeout,unit);
        }
        public void awaitReadLatch(long timeout, TimeUnit unit) throws InterruptedException { awaitLatch(readLatch,timeout,unit);}
        public void awaitWriteLatch(long timeout, TimeUnit unit) throws InterruptedException { awaitLatch(writeLatch,timeout,unit);}

        public void setSendfileData(SendfileData sf) { this.sendfileData = sf;}
        public SendfileData getSendfileData() { return this.sendfileData;}

        public void updateLastWrite() { lastWrite = System.currentTimeMillis(); }
        public long getLastWrite() { return lastWrite; }
        public void updateLastRead() { lastRead = System.currentTimeMillis(); }
        public long getLastRead() { return lastRead; }

        @Override
        public boolean isReadyForRead() throws IOException {
            socketBufferHandler.configureReadBufferForRead();

            if (socketBufferHandler.getReadBuffer().remaining() > 0) {
                return true;
            }

            fillReadBuffer(false);

            boolean isReady = socketBufferHandler.getReadBuffer().position() > 0;
            return isReady;
        }

        @Override
        public int read(boolean block, byte[] b, int off, int len) throws IOException {
            int nRead = populateReadBuffer(b, off, len);
            if (nRead > 0) {
                return nRead;
                /*
                 * Since more bytes may have arrived since the buffer was last
                 * filled, it is an option at this point to perform a
                 * non-blocking read. However correctly handling the case if
                 * that read returns end of stream adds complexity. Therefore,
                 * at the moment, the preference is for simplicity.
                 */
            }

            // Fill the read buffer as best we can.
            nRead = fillReadBuffer(block);
            updateLastRead();

            // Fill as much of the remaining byte array as possible with the
            // data that was just read
            if (nRead > 0) {
                socketBufferHandler.configureReadBufferForRead();
                nRead = Math.min(nRead, len);
                socketBufferHandler.getReadBuffer().get(b, off, nRead);
            }
            return nRead;
        }

        @Override
        public int read(boolean block, ByteBuffer to) throws IOException {
            int nRead = populateReadBuffer(to);
            if (nRead > 0) {
                return nRead;
                /*
                 * Since more bytes may have arrived since the buffer was last
                 * filled, it is an option at this point to perform a
                 * non-blocking read. However correctly handling the case if
                 * that read returns end of stream adds complexity. Therefore,
                 * at the moment, the preference is for simplicity.
                 */
            }

            // The socket read buffer capacity is socket.appReadBufSize
            int limit = socketBufferHandler.getReadBuffer().capacity();
            if (to.remaining() >= limit) {
                to.limit(to.position() + limit);
                nRead = fillReadBuffer(block, to);
                updateLastRead();
            } else {
                // Fill the read buffer as best we can.
                nRead = fillReadBuffer(block);
                updateLastRead();

                // Fill as much of the remaining byte array as possible with the
                // data that was just read
                if (nRead > 0) {
                    nRead = populateReadBuffer(to);
                }
            }
            return nRead;
        }

        @Override
        public void close() throws IOException {
            getSocket().close();
        }

        @Override
        public boolean isClosed() {
            return !getSocket().isOpen();
        }

        private int fillReadBuffer(boolean block) throws IOException {
            socketBufferHandler.configureReadBufferForWrite();
            return fillReadBuffer(block, socketBufferHandler.getReadBuffer());
        }

        private int fillReadBuffer(boolean block, ByteBuffer to) throws IOException {
            int nRead;
            NioChannel channel = getSocket();
            if (block) {
                Selector selector = null;
                try {
                    selector = pool.get();
                } catch (IOException x) {
                    // Ignore
                }
                try {
                    NioEndpoint.NioSocketWrapper att = (NioEndpoint.NioSocketWrapper) channel
                            .getAttachment();
                    if (att == null) {
                        throw new IOException("Key must be cancelled.");
                    }
                    nRead = pool.read(to, channel, selector, att.getReadTimeout());
                } finally {
                    if (selector != null) {
                        pool.put(selector);
                    }
                }
            } else {
                nRead = channel.read(to);
                if (nRead == -1) {
                    throw new EOFException();
                }
            }
            return nRead;
        }

        @Override
        protected void doWrite(boolean block, ByteBuffer from) throws IOException {
            long writeTimeout = getWriteTimeout();
            Selector selector = null;
            try {
                selector = pool.get();
            } catch (IOException x) {
                // Ignore
            }
            try {
                pool.write(from, getSocket(), selector, writeTimeout, block);
                if (block) {
                    // Make sure we are flushed
                    do {
                        if (getSocket().flush(true, selector, writeTimeout)) {
                            break;
                        }
                    } while (true);
                }
                updateLastWrite();
            } finally {
                if (selector != null) {
                    pool.put(selector);
                }
            }
            // If there is data left in the buffer the socket will be registered for
            // write further up the stack. This is to ensure the socket is only
            // registered for write once as both container and user code can trigger
            // write registration.
        }

        @Override
        public void registerReadInterest() {
            getPoller().add(getSocket(), SelectionKey.OP_READ);
        }

        @Override
        public void registerWriteInterest() {
            getPoller().add(getSocket(), SelectionKey.OP_WRITE);
        }

        @Override
        public SendfileDataBase createSendfileData(String filename, long pos, long length) {
            return new SendfileData(filename, pos, length);
        }

        @Override
        public SendfileState processSendfile(SendfileDataBase sendfileData) {
            setSendfileData((SendfileData) sendfileData);
            SelectionKey key = getSocket().getIOChannel().keyFor(
                    getSocket().getPoller().getSelector());
            // Might as well do the first write on this thread
            return getSocket().getPoller().processSendfile(key, this, true);
        }

        @Override
        protected void populateRemoteAddr() {
            InetAddress inetAddr = getSocket().getIOChannel().socket().getInetAddress();
            if (inetAddr != null) {
                remoteAddr = inetAddr.getHostAddress();
            }
        }

        @Override
        protected void populateRemoteHost() {
            InetAddress inetAddr = getSocket().getIOChannel().socket().getInetAddress();
            if (inetAddr != null) {
                remoteHost = inetAddr.getHostName();
                if (remoteAddr == null) {
                    remoteAddr = inetAddr.getHostAddress();
                }
            }
        }

        @Override
        protected void populateRemotePort() {
            remotePort = getSocket().getIOChannel().socket().getPort();
        }

        @Override
        protected void populateLocalName() {
            InetAddress inetAddr = getSocket().getIOChannel().socket().getLocalAddress();
            if (inetAddr != null) {
                localName = inetAddr.getHostName();
            }
        }

        @Override
        protected void populateLocalAddr() {
            InetAddress inetAddr = getSocket().getIOChannel().socket().getLocalAddress();
            if (inetAddr != null) {
                localAddr = inetAddr.getHostAddress();
            }
        }

        @Override
        protected void populateLocalPort() {
            localPort = getSocket().getIOChannel().socket().getLocalPort();
        }

        /**
         * {@inheritDoc}
         * @param clientCertProvider Ignored for this implementation
         */
        @Override
        public SSLSupport getSslSupport(String clientCertProvider) {
            if (getSocket() instanceof SecureNioChannel) {
                SecureNioChannel ch = (SecureNioChannel) getSocket();
                SSLSession session = ch.getSslEngine().getSession();
                return ((NioEndpoint) getEndpoint()).getSslImplementation().getSSLSupport(session);
            } else {
                return null;
            }
        }

        @Override
        public void doClientAuth(SSLSupport sslSupport) {
            SecureNioChannel sslChannel = (SecureNioChannel) getSocket();
            SSLEngine engine = sslChannel.getSslEngine();
            if (!engine.getNeedClientAuth()) {
                // Need to re-negotiate SSL connection
                engine.setNeedClientAuth(true);
                try {
                    sslChannel.rehandshake(getEndpoint().getConnectionTimeout());
                    ((JSSESupport) sslSupport).setSession(engine.getSession());
                } catch (IOException ioe) {
                    log.warn(sm.getString("socket.sslreneg",ioe));
                }
            }
        }

        @Override
        public void setAppReadBufHandler(ApplicationBufferHandler handler) {
            getSocket().setAppReadBufHandler(handler);
        }
    }

    // ---------------------------------------------- SocketProcessor Inner Class

    /**
     * This class is the equivalent of the Worker, but will simply use in an
     * external Executor thread pool.
     */
    protected class SocketProcessor extends SocketProcessorBase<NioChannel> {

        public SocketProcessor(SocketWrapperBase<NioChannel> socketWrapper, SocketEvent event) {
            super(socketWrapper, event);
        }

        @Override
        protected void doRun() {
            NioChannel socket = socketWrapper.getSocket();
            SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector());

            try {
                int handshake = -1;

                try {
                    if (key != null) {
                        if (socket.isHandshakeComplete()) {
                            // No TLS handshaking required. Let the handler
                            // process this socket / event combination.
                            handshake = 0;
                        } else if (event == SocketEvent.STOP || event == SocketEvent.DISCONNECT ||
                                event == SocketEvent.ERROR) {
                            // Unable to complete the TLS handshake. Treat it as
                            // if the handshake failed.
                            handshake = -1;
                        } else {
                            handshake = socket.handshake(key.isReadable(), key.isWritable());
                            // The handshake process reads/writes from/to the
                            // socket. status may therefore be OPEN_WRITE once
                            // the handshake completes. However, the handshake
                            // happens when the socket is opened so the status
                            // must always be OPEN_READ after it completes. It
                            // is OK to always set this as it is only used if
                            // the handshake completes.
                            event = SocketEvent.OPEN_READ;
                        }
                    }
                } catch (IOException x) {
                    handshake = -1;
                    if (log.isDebugEnabled()) log.debug("Error during SSL handshake",x);
                } catch (CancelledKeyException ckx) {
                    handshake = -1;
                }
                if (handshake == 0) {
                    SocketState state = SocketState.OPEN;
                    // Process the request from this socket
                    if (event == null) {
                        state = getHandler().process(socketWrapper, SocketEvent.OPEN_READ);
                    } else {
                        state = getHandler().process(socketWrapper, event);
                    }
                    if (state == SocketState.CLOSED) {
                        close(socket, key);
                    }
                } else if (handshake == -1 ) {
                    close(socket, key);
                } else if (handshake == SelectionKey.OP_READ){
                    socketWrapper.registerReadInterest();
                } else if (handshake == SelectionKey.OP_WRITE){
                    socketWrapper.registerWriteInterest();
                }
            } catch (CancelledKeyException cx) {
                socket.getPoller().cancelledKey(key);
            } catch (VirtualMachineError vme) {
                ExceptionUtils.handleThrowable(vme);
            } catch (Throwable t) {
                log.error("", t);
                socket.getPoller().cancelledKey(key);
            } finally {
                socketWrapper = null;
                event = null;
                //return to cache
                if (running && !paused) {
                    processorCache.push(this);
                }
            }
        }
    }

    // ----------------------------------------------- SendfileData Inner Class
    /**
     * SendfileData class.
     */
    public static class SendfileData extends SendfileDataBase {

        public SendfileData(String filename, long pos, long length) {
            super(filename, pos, length);
        }

        protected volatile FileChannel fchannel;
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace StackUsageAnalyzer
{
    class ParserHandler
    {
        public ParserHandler(string rootFolder)
        {
            Folder = rootFolder;
        }

        public StackAnalysisViewModel Model { get; internal set; }

        public IEnumerable<FunctionStackInfo> Parse()
        {
            var files = ListFiles();
            var info = SuFileParser.Parse(files.SelectMany(f => File.ReadLines(f).Select(l => new LineInstance() { Line = l, FileName = f })));

            Model?.Items.Clear();
            foreach (var functionInfo in info.OrderBy(f => f.Bytes))
                Model?.Items.Add(functionInfo);

            return info;
        }

        public string Folder { get; internal set; }

        private IEnumerable<string> ListFiles()
        {
            return Directory.EnumerateFiles(Folder, @"*.su", SearchOption.AllDirectories);
        }
    }
}


text:
<?php

use app\modules\user\models\Country;
use app\modules\user\models\User;
use yii\bootstrap\ActiveForm;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;

/**
 * @var $model User
 * @var Country[] $countries
 */

$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Profile')];

$this->title = Yii::t('app', 'Profile');
?>

<?= $this->title ?>

    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>

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

    <?= $form->field($model, 'country_id')->dropDownList(ArrayHelper::map($countries, 'id', 'name')) ?>

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

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

    <?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-primary']) ?>
    <?= Html::a(Yii::t('app', 'Cancel'), ['details']) ?>

    <?php ActiveForm::end() ?>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FaxClientSpiProxy (fax4j 0.45.0 API)</title>
<meta name="date" content="2020-05-15">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.fax4j.spi

Interface FaxClientSpiProxy

All Superinterfaces:

InvocationHandler

All Known Implementing Classes:

AbstractFaxClientSpiProxy, FaxClientSpiProxyImpl

public interface FaxClientSpiProxy
extends InvocationHandler

This interface defines the fax client SPI proxy which enables to invoke interceptors before and after the fax client
 SPI method invocations.

 With this proxy, it is possible to intercept all calls to the fax client SPIs and perform custom logic such as
 logging.

 The configuration of the fax4j framework is made up of 3 layers.

 The configuration is based on simple properties.

 Each layer overrides the lower layers by adding/changing the property values.

 The first layer is the internal fax4j.properties file located in the fax4j jar.

 This layer contains the preconfigured values for the fax4j framework and can be changed by updating these properties
 in the higher layers.

 The second layer is the external fax4j.properties file that is located on the classpath.

 This file is optional and provides the ability to override the internal configuration for the entire fax4j
 framework.

 The top most layer is the optional java.util.Properties object provided by the external classes when creating a new
 fax client.

 These properties enable to override the configuration of the lower 2 layers.

 Below table describes the configuration values relevant for this class.

 Configuration:

 Name
 Description
 Preconfigured Value
 Default Value
 Mandatory

 org.fax4j.proxy.enabled
 True to enable the fax client SPI proxy.
 true
 true
 false

 org.fax4j.proxy.class.name
 Defines the fax client SPI proxy class name.
 org.fax4j.spi.FaxClientSpiProxyImpl
 org.fax4j.spi.FaxClientSpiProxyImpl
 false

 org.fax4j.proxy.interceptor.list
 A list of interceptor types, separated by a ';' character.

 Each type must have a matching org.fax4j.proxy.interceptor.type.xxx property.
 log
 none
 false

 org.fax4j.proxy.interceptor.type.xxx
 The interceptor type to class name mapping.
 org.fax4j.proxy.interceptor.type.log=org.fax4j.spi.LogFaxClientSpiInterceptor
 none
 false

Since:

0.17

Version:

1.0

Author:

Sagie Gur-Ari

Nested Class Summary

Nested Classes

Modifier and Type
Interface and Description

static class
FaxClientSpiProxy.FaxClientSpiProxyEventType

This is the fax client SPI proxy event type.

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

void
initialize(FaxClientSpi faxClientSpi,
          FaxClientSpiInterceptor[] interceptors)

This function initializes the fax client SPI proxy.

 This method is called by the FaxClientSpiFactory.

Methods inherited from interface java.lang.reflect.InvocationHandler

invoke

Method Detail

initialize

void initialize(FaxClientSpi faxClientSpi,
                FaxClientSpiInterceptor[] interceptors)

This function initializes the fax client SPI proxy.

 This method is called by the FaxClientSpiFactory.

Parameters:

faxClientSpi - The fax client SPI

interceptors - The interceptors (may be null)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2009–2020 fax4j. All rights reserved.


text:
package org.apache.kafka.common.utils;

import java.util.StringTokenizer;

public final class Java {

    private Java() {
    }

    public static final String JVM_SPEC_VERSION = System.getProperty("java.specification.version");

    private static final int JVM_MAJOR_VERSION;
    private static final int JVM_MINOR_VERSION;

    static {
        final StringTokenizer st = new StringTokenizer(JVM_SPEC_VERSION, ".");
        JVM_MAJOR_VERSION = Integer.parseInt(st.nextToken());
        if (st.hasMoreTokens()) {
            JVM_MINOR_VERSION = Integer.parseInt(st.nextToken());
        } else {
            JVM_MINOR_VERSION = 0;
        }
    }

    public static final boolean IS_JAVA9_COMPATIBLE = JVM_MAJOR_VERSION > 1 ||
            (JVM_MAJOR_VERSION == 1 && JVM_MINOR_VERSION >= 9);

    public static final boolean IS_JAVA8_COMPATIBLE = JVM_MAJOR_VERSION > 1 ||
            (JVM_MAJOR_VERSION == 1 && JVM_MINOR_VERSION >= 8);

    public static boolean isIBMJdk() {
        return System.getProperty("java.vendor").contains("IBM");
    }

}


text:
roscore & # If core is already running, this will fail silently
pidcore=$!
sleep 1
# Launch SCS.
$DRC_BASE/software/ipab/config/runscs.bash &
# Get the bash pid.
pidscs=$!
while true; do
	# If SCS crashes and bash script stops, return FAILURE
	if ! kill -0 $pidscs > /dev/null 2>&1; then
		echo "FAILURE - SCS crashed or didn't start."
	        kill $pidcore
		exit 1
	fi
	if [ "$(rostopic info /ihmc_ros/valkyrie/api_command | grep Subscribers)" == "Subscribers: " ] ; then
		# SCS is running now, send commands.
		echo "Shutting down SCS"
                rostopic pub /ihmc_ros/valkyrie/api_command std_msgs/String stop -1 > /dev/null 2>&1
		break
	else
		echo "Waiting for SCS to start ..."
	fi
	sleep 1
done
# Get the java process pid (this is required for shutting down SCS when it becomes unresponsive).
pid="$(ps --ppid $pidscs | grep java | awk '{print $1;}')"
# If SCS closes within 5s, succeeed, fail otherwise.
sleep 5
if ! kill -0 $pid > /dev/null 2>&1; then
	echo "SUCCESS"
        kill $pidcore
	exit 0
else
	kill $pid
	wait $pidscs
        kill $pidcore
	echo "FAILURE - SCS did not shut down! Killing process now."
	exit 1
fi


text:
#pragma once

#include "CodeBlock.h"
#include "CodeBlockHash.h"
#include "CodeOrigin.h"
#include "ValueRecovery.h"
#include "WriteBarrier.h"
#include <wtf/HashMap.h>
#include <wtf/PrintStream.h>
#include <wtf/StdLibExtras.h>
#include <wtf/Vector.h>

namespace JSC {

struct InlineCallFrame;
class ExecState;
class JSFunction;

struct InlineCallFrame {
    enum Kind {
        Call,
        Construct,
        TailCall,
        CallVarargs,
        ConstructVarargs,
        TailCallVarargs,

        // For these, the stackOffset incorporates the argument count plus the true return PC
        // slot.
        GetterCall,
        SetterCall
    };

    static CallMode callModeFor(Kind kind)
    {
        switch (kind) {
        case Call:
        case CallVarargs:
        case GetterCall:
        case SetterCall:
            return CallMode::Regular;
        case TailCall:
        case TailCallVarargs:
            return CallMode::Tail;
        case Construct:
        case ConstructVarargs:
            return CallMode::Construct;
        }
        RELEASE_ASSERT_NOT_REACHED();
    }

    static Kind kindFor(CallMode callMode)
    {
        switch (callMode) {
        case CallMode::Regular:
            return Call;
        case CallMode::Construct:
            return Construct;
        case CallMode::Tail:
            return TailCall;
        }
        RELEASE_ASSERT_NOT_REACHED();
    }

    static Kind varargsKindFor(CallMode callMode)
    {
        switch (callMode) {
        case CallMode::Regular:
            return CallVarargs;
        case CallMode::Construct:
            return ConstructVarargs;
        case CallMode::Tail:
            return TailCallVarargs;
        }
        RELEASE_ASSERT_NOT_REACHED();
    }

    static CodeSpecializationKind specializationKindFor(Kind kind)
    {
        switch (kind) {
        case Call:
        case CallVarargs:
        case TailCall:
        case TailCallVarargs:
        case GetterCall:
        case SetterCall:
            return CodeForCall;
        case Construct:
        case ConstructVarargs:
            return CodeForConstruct;
        }
        RELEASE_ASSERT_NOT_REACHED();
    }

    static bool isVarargs(Kind kind)
    {
        switch (kind) {
        case CallVarargs:
        case TailCallVarargs:
        case ConstructVarargs:
            return true;
        default:
            return false;
        }
    }

    static bool isTail(Kind kind)
    {
        switch (kind) {
        case TailCall:
        case TailCallVarargs:
            return true;
        default:
            return false;
        }
    }
    bool isTail() const
    {
        return isTail(static_cast<Kind>(kind));
    }

    static CodeOrigin* computeCallerSkippingTailCalls(InlineCallFrame* inlineCallFrame, Kind* callerCallKind = nullptr)
    {
        CodeOrigin* codeOrigin;
        bool tailCallee;
        int callKind;
        do {
            tailCallee = inlineCallFrame->isTail();
            callKind = inlineCallFrame->kind;
            codeOrigin = &inlineCallFrame->directCaller;
            inlineCallFrame = codeOrigin->inlineCallFrame;
        } while (inlineCallFrame && tailCallee);

        if (tailCallee)
            return nullptr;

        if (callerCallKind)
            *callerCallKind = static_cast<Kind>(callKind);

        return codeOrigin;
    }

    CodeOrigin* getCallerSkippingTailCalls(Kind* callerCallKind = nullptr)
    {
        return computeCallerSkippingTailCalls(this, callerCallKind);
    }

    InlineCallFrame* getCallerInlineFrameSkippingTailCalls()
    {
        CodeOrigin* caller = getCallerSkippingTailCalls();
        return caller ? caller->inlineCallFrame : nullptr;
    }

    Vector<ValueRecovery> arguments; // Includes 'this'.
    WriteBarrier<CodeBlock> baselineCodeBlock;
    ValueRecovery calleeRecovery;
    CodeOrigin directCaller;

    signed stackOffset : 28;
    unsigned kind : 3; // real type is Kind
    bool isClosureCall : 1; // If false then we know that callee/scope are constants and the DFG won't treat them as variables, i.e. they have to be recovered manually.
    VirtualRegister argumentCountRegister; // Only set when we inline a varargs call.

    // There is really no good notion of a "default" set of values for
    // InlineCallFrame's fields. This constructor is here just to reduce confusion if
    // we forgot to initialize explicitly.
    InlineCallFrame()
        : stackOffset(0)
        , kind(Call)
        , isClosureCall(false)
    {
    }

    bool isVarargs() const
    {
        return isVarargs(static_cast<Kind>(kind));
    }

    CodeSpecializationKind specializationKind() const { return specializationKindFor(static_cast<Kind>(kind)); }

    JSFunction* calleeConstant() const;

    // Get the callee given a machine call frame to which this InlineCallFrame belongs.
    JSFunction* calleeForCallFrame(ExecState*) const;

    CString inferredName() const;
    CodeBlockHash hash() const;
    CString hashAsStringIfPossible() const;

    void setStackOffset(signed offset)
    {
        stackOffset = offset;
        RELEASE_ASSERT(static_cast<signed>(stackOffset) == offset);
    }

    ptrdiff_t callerFrameOffset() const { return stackOffset * sizeof(Register) + CallFrame::callerFrameOffset(); }
    ptrdiff_t returnPCOffset() const { return stackOffset * sizeof(Register) + CallFrame::returnPCOffset(); }

    bool isStrictMode() const { return baselineCodeBlock->isStrictMode(); }

    void dumpBriefFunctionInformation(PrintStream&) const;
    void dump(PrintStream&) const;
    void dumpInContext(PrintStream&, DumpContext*) const;

    MAKE_PRINT_METHOD(InlineCallFrame, dumpBriefFunctionInformation, briefFunctionInformation);

};

inline CodeBlock* baselineCodeBlockForInlineCallFrame(InlineCallFrame* inlineCallFrame)
{
    RELEASE_ASSERT(inlineCallFrame);
    return inlineCallFrame->baselineCodeBlock.get();
}

inline CodeBlock* baselineCodeBlockForOriginAndBaselineCodeBlock(const CodeOrigin& codeOrigin, CodeBlock* baselineCodeBlock)
{
    if (codeOrigin.inlineCallFrame)
        return baselineCodeBlockForInlineCallFrame(codeOrigin.inlineCallFrame);
    return baselineCodeBlock;
}

template <typename Function>
inline void CodeOrigin::walkUpInlineStack(const Function& function)
{
    CodeOrigin codeOrigin = *this;
    while (true) {
        function(codeOrigin);
        if (!codeOrigin.inlineCallFrame)
            break;
        codeOrigin = codeOrigin.inlineCallFrame->directCaller;
    }
}

} // namespace JSC

namespace WTF {

void printInternal(PrintStream&, JSC::InlineCallFrame::Kind);

} // namespace WTF


text:
module DatabaseAnonymizer
  VERSION = "0.0.1"
end


text: {% include nav.html %}


text:
"""Auto-generated file, do not edit by hand. NC metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata

PHONE_METADATA_NC = PhoneMetadata(id='NC', country_code=None, international_prefix=None,
    general_desc=PhoneNumberDesc(national_number_pattern='1\\d{1,3}|3\\d{3}|5\\d{2}', possible_number_pattern='\\d{2,4}', possible_length=(2, 3, 4)),
    toll_free=PhoneNumberDesc(national_number_pattern='10(?:00|1[23]|3[0-2]|88)|3631|577', possible_number_pattern='\\d{3,4}', example_number='1000', possible_length=(3, 4)),
    premium_rate=PhoneNumberDesc(),
    emergency=PhoneNumberDesc(national_number_pattern='1[5-8]', possible_number_pattern='\\d{2}', example_number='15', possible_length=(2,)),
    short_code=PhoneNumberDesc(national_number_pattern='1(?:0(?:0[06]|1[02-46]|20|3[0125]|42|5[058]|77|88)|[5-8])|3631|5[6-8]\\d', possible_number_pattern='\\d{2,4}', example_number='1000', possible_length=(2, 3, 4)),
    standard_rate=PhoneNumberDesc(national_number_pattern='5(?:67|88)', possible_number_pattern='\\d{3}', example_number='567', possible_length=(3,)),
    carrier_specific=PhoneNumberDesc(),
    short_data=True)


text:
@interface OWNoticeDetailVC ()<UIWebViewDelegate>

@property (nonatomic, weak) UIWebView *noticeView;
@property (nonatomic, weak) OWInputFuncView *funcView;

@end

@implementation OWNoticeDetailVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"详情";
    [self.noticeView loadHTMLString:[OWTool filtrationHtml:self.notice.newsContent] baseURL:nil];

    [self setupFuncView];
    [self dataRequest];
}

- (void)setupFuncView
{
    [self.funcView showAccessoryViewAnimation];
    [self.funcView hiddenAccessoryViewAnimation];
    wh_weakSelf(self);
    self.funcView.block = ^(NSInteger tag){
        if (tag == 10) {
            [weakself submitComment];
        }else if (tag == 11) {
            [weakself submitThumbup];
        }else if (tag == 12){
            [weakself submitCollection];
        }else{
            OWHomeCommentVC *commentVC = [[OWHomeCommentVC alloc] init];
            commentVC.notice = self.notice;
            [weakself.navigationController pushViewController:commentVC animated:YES];
        }
    };
}

- (void)dataRequest
{
    [SVProgressHUD showWithStatus:@"正在加载..."];
    NSDictionary *par = @{
                          @"id":@(self.notice.id),
                          @"type":@(2)
                          };
    [OWNetworking HPOST:wh_appendingStr(wh_host, @"mobile/reply/replyLikeAndMark") parameters:par success:^(id  _Nullable responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            self.funcView.infoDic = responseObject[@"data"];
            [SVProgressHUD dismiss];
        }else{
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
        }
    } failure:^(NSError * _Nonnull error) {
        [SVProgressHUD showInfoWithStatus:@"请检查网络!"];
    }];
}

- (void)submitComment
{
    [SVProgressHUD showWithStatus:@"正在提交..."];
    NSDictionary *par = @{
                          @"content":self.funcView.commentStr,
                          @"articleId":@(self.notice.id),
                          @"articleType":@(2)
                          };
    [OWNetworking HPOST:wh_appendingStr(wh_host, @"mobile/reply/reply") parameters:par success:^(id  _Nullable responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            wh_Log(@"---%@",responseObject);
            self.funcView.inputView.text = @"";
            [self dataRequest];
            [SVProgressHUD showSuccessWithStatus:@"评论成功!"];
        }else{
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
        }
    } failure:^(NSError * _Nonnull error) {
        [SVProgressHUD showInfoWithStatus:@"请检查网络!"];
    }];

}

- (void)submitThumbup
{
    if (self.funcView.thumbupBtn.selected) { // 取消点赞
        NSDictionary *par = @{
                              @"praisedId":@(self.notice.id),
                              @"type":@(2)
                              };
        wh_Log(@"--%@",par);
        [OWNetworking HPOST:wh_appendingStr(wh_host, @"mobile/like/unlike") parameters:par success:^(id  _Nullable responseObject) {
            if ([responseObject[@"code"] intValue] == 200) {
                wh_Log(@"---%@",responseObject);
                self.funcView.thumbupBtn.selected = NO;
            }else{
                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            }
        } failure:^(NSError * _Nonnull error) {
            [SVProgressHUD showInfoWithStatus:@"请检查网络!"];
//            wh_Log(@"---%@",error);
        }];
    }else{ // 点赞
        NSDictionary *par = @{
                              @"praisedId":@(self.notice.id),
                              @"type":@(2),
                              @"title":self.notice.title,
                              @"cover":@""
                              };
        wh_Log(@"--%@",par);
        [OWNetworking HPOST:wh_appendingStr(wh_host, @"mobile/like/like") parameters:par success:^(id  _Nullable responseObject) {
            if ([responseObject[@"code"] intValue] == 200) {
                wh_Log(@"---%@",responseObject);
                self.funcView.thumbupBtn.selected = YES;
            }else{
                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            }
        } failure:^(NSError * _Nonnull error) {
            [SVProgressHUD showInfoWithStatus:@"请检查网络!"];
//            wh_Log(@"---%@",error);
        }];
    }
}

- (void)submitCollection
{
    if (self.funcView.collectionBtn.selected) { // 取消收藏
        NSDictionary *par = @{
                              @"markedId":@(self.notice.id),
                              @"type":@(2)
                              };
        [OWNetworking HPOST:wh_appendingStr(wh_host, @"mobile/mark/unmark") parameters:par success:^(id  _Nullable responseObject) {
            if ([responseObject[@"code"] intValue] == 200) {
                wh_Log(@"---%@",responseObject);
                self.funcView.collectionBtn.selected = NO;
            }else{
                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            }
        } failure:^(NSError * _Nonnull error) {
            [SVProgressHUD showInfoWithStatus:@"请检查网络!"];
        }];
    }else{// 收藏
        NSDictionary *par = @{
                              @"markedId":@(self.notice.id),
                              @"type":@(2),
                              @"title":self.notice.title,
                              @"cover":@""
                              };
        [OWNetworking HPOST:wh_appendingStr(wh_host, @"mobile/mark/mark") parameters:par success:^(id  _Nullable responseObject) {
            if ([responseObject[@"code"] intValue] == 200) {
                wh_Log(@"---%@",responseObject);
                self.funcView.collectionBtn.selected = YES;
            }else{
                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            }
        } failure:^(NSError * _Nonnull error) {
            [SVProgressHUD showInfoWithStatus:@"请检查网络!"];
        }];
    }
}

#pragma mark - ---------- Lazy ----------

- (UIWebView *)noticeView
{
    if (!_noticeView) {
        UIWebView *view = [[UIWebView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        view.delegate = self;
        [self.view addSubview:view];

        [view makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        _noticeView = view;
    }
    return _noticeView;
}

- (OWInputFuncView *)funcView
{
    if (!_funcView) {
        OWInputFuncView *view = [[OWInputFuncView alloc] init];
        [self.view addSubview:view];

        [view makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self.view);
            make.height.equalTo(50);
        }];
        _funcView = view;
    }
    return _funcView;
}

@end


text:
gets.to_i.times do
  puts gets.chomp.gsub(/Hoshino/, 'Hoshina')
end


text:
require 'spec_helper'

RSpec.describe SomervilleHighLevelsDefinitions do
  let!(:pals) { TestPals.create! }
  let!(:time_now) { pals.time_now }

  describe '#decide_level' do
    def decide_level_output(levels_inputs_data)
      input = SomervilleHighLevelsDefinitions.levels_input(levels_inputs_data)
      level = SomervilleHighLevelsDefinitions.new.decide_level(input)
      [level.level_number, level.triggers]
    end

    it 'Level 0' do
      level = 0
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 0,
        recent_discipline_actions: 0,
        recent_absence_rate: 1.0
      })).to eq [level, []]
      expect(decide_level_output({
        course_ds: 1,
        course_failures: 0,
        recent_discipline_actions: 0,
        recent_absence_rate: 1.0
      })).to eq [level, []]
      expect(decide_level_output({
        course_ds: 1,
        course_failures: 0,
        recent_discipline_actions: 0,
        recent_absence_rate: 0.95
      })).to eq [level, []]
      expect(decide_level_output({
        course_ds: 1,
        course_failures: 0,
        recent_discipline_actions: 4,
        recent_absence_rate: 1.0
      })).to eq [level, []]
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 1,
        recent_discipline_actions: 0,
        recent_absence_rate: 1.0
      })).to eq [level, []]
      expect(decide_level_output({
        course_ds: 4,
        course_failures: 0,
        recent_discipline_actions: 0,
        recent_absence_rate: 1.0
      })).to eq [level, []]
    end

    it 'Level 1: 1 F and 2 Ds OR less than 95 attendance over last 45 days' do
      expect(decide_level_output({
        course_ds: 2,
        course_failures: 1,
        recent_discipline_actions: 0,
        recent_absence_rate: 1.00
      })).to eq [1, [:academic]]
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 0,
        recent_discipline_actions: 0,
        recent_absence_rate: 0.94
      })).to eq [1, [:absence]]
      expect(decide_level_output({
        course_ds: 2,
        course_failures: 1,
        recent_discipline_actions: 0,
        recent_absence_rate: 0.90
      })).to eq [1, [:academic, :absence]]
    end

    it "Level 2: 2 F's OR less than 90 attendance over last 45" do
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 2,
        recent_discipline_actions: 0,
        recent_absence_rate: 0.90
      })).to eq [2, [:academic]]
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 0,
        recent_discipline_actions: 0,
        recent_absence_rate: 0.89
      })).to eq [2, [:absence]]
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 2,
        recent_discipline_actions: 0,
        recent_absence_rate: 0.85
      })).to eq [2, [:academic, :absence]]
    end

    it "Level 3: 3 F's OR less than 85 attendance over last 45 OR 5-6 discipline actions over the last 45 school days" do
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 3,
        recent_discipline_actions: 0,
        recent_absence_rate: 1.0
      })).to eq [3, [:academic]]
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 0,
        recent_discipline_actions: 0,
        recent_absence_rate: 0.84
      })).to eq [3, [:absence]]
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 0,
        recent_discipline_actions: 5,
        recent_absence_rate: 1.0
      })).to eq [3, [:discipline]]
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 3,
        recent_discipline_actions: 5,
        recent_absence_rate: 0.80
      })).to eq [3, [:academic, :absence, :discipline]]
    end

    it "Level 4: At least 4 F's OR less than 80% attendance over last 45 school days OR 7 or more discipline actions over the last 45 school days" do
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 4,
        recent_discipline_actions: 0,
        recent_absence_rate: 1.0
      })).to eq [4, [:academic]]
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 0,
        recent_discipline_actions: 0,
        recent_absence_rate: 0.79
      })).to eq [4, [:absence]]
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 0,
        recent_discipline_actions: 7,
        recent_absence_rate: 1.0
      })).to eq [4, [:discipline]]
      expect(decide_level_output({
        course_ds: 0,
        course_failures: 4,
        recent_discipline_actions: 7,
        recent_absence_rate: 0.79
      })).to eq [4, [:academic, :absence, :discipline]]
    end
  end
end


text:
namespace mx
{
    namespace core
    {

        MX_FORWARD_DECLARE_ATTRIBUTES( MidiDeviceAttributes )

        struct MidiDeviceAttributes : public AttributesInterface
        {
        public:
            MidiDeviceAttributes();
            virtual bool hasValues() const;
            virtual std::ostream& toStream( std::ostream& os ) const;
            Midi16 port;
            XsIDREF id;
            bool hasPort;
            bool hasId;

            private:
            virtual bool fromXElementImpl( std::ostream& message, ::ezxml::XElement& xelement );
        };
    }
}


text:
// IMPORTING
var  b2Vec2, b2World, b2DebugDraw, b2Body, b2BodyDef, b2FixtureDef, b2PolygonShape, b2CircleShape, b2AABB, b2RevoluteJointDef;

function importBox2D() {
	b2Vec2  			= Box2D.Common.Math.b2Vec2;
	b2World	        	= Box2D.Dynamics.b2World;
	b2DebugDraw     	= Box2D.Dynamics.b2DebugDraw;
	b2Body  			= Box2D.Dynamics.b2Body;
	b2BodyDef   		= Box2D.Dynamics.b2BodyDef;
	b2FixtureDef    	= Box2D.Dynamics.b2FixtureDef;
	b2PolygonShape  	= Box2D.Collision.Shapes.b2PolygonShape;
	b2CircleShape   	= Box2D.Collision.Shapes.b2CircleShape;
	b2AABB		    	= Box2D.Collision.b2AABB;
	b2RevoluteJointDef	= Box2D.Dynamics.Joints.b2RevoluteJointDef;
}

import Engine from './Engine.js';
import { extend } from './utilities/utility.js';

/* *********************************************************************************************** *
 * Physics engine
 * =============================================================================================== *
 * REQUIRE: Box2D, Engine
 * *********************************************************************************************** */

class Physics extends Engine {

	constructor(settings) {
		importBox2D();
		settings = extend({}, Physics.default, settings);
		super(settings);

		this.CANVAS_WIDTH;
		this.CANVAS_HEIGHT;
		this.SCALE;
		this._isRun = false;
		this._world;
		this._boundaries;
	//	this._canvas;
	//	this._sprite;
		this._debugDraw;
		this._control;
	}

	/* ***************************** *
	 * INITIALIZE AND CREATE SECTION *
	 * ***************************** */

	// Initialize
	init() {
		super.init();
		let canvas, gravity, sprite;
		let settings = this._settings;

		// canvas = typeof settings.canvas === 'string' ? document.querySelector(settings.canvas) : settings.canvas;
		// sprite = canvas.getContext('2d');

		gravity = settings.gravity;
		gravity = typeof gravity === 'object' ? gravity : {x:0, y:gravity};
		gravity = new b2Vec2(gravity.x, gravity.y);

		// this.CANVAS_WIDTH = canvas.width;
		// this.CANVAS_HEIGHT = canvas.height;
		this.SCALE = settings.scale;

		this._settings = settings;
		// this._canvas = canvas;
		// this._sprite = sprite;
		this._gravity = gravity;
		this._isRun = false;
		this._debugDrawEnabled = !!settings.debugDraw;

		this._control = this.setDirectControl();
		this._control[ settings.directControl ? 'turnOn' : 'turnOff' ]();
	}

	// Create Box2D world
	createWorld() {
		var self = this;
		this._world = new b2World(this._gravity, true);
		if(this._debugDrawEnabled) {
			this._debugDraw = this.createDebugDraw({
				sprite: self._sprite,
				scale: self.SCALE,
				alpha: .5,
				lineThickness: 1
			});
			this._world.SetDebugDraw(this._debugDraw);
		}
	}

	// World boundaries
	createWorldBoundaries(width, height) {
		width = (width || this._canvas.width) / this.SCALE;
		height = (height || this._canvas.height) / this.SCALE;

		this._boundaries = this.createBody(
			{ x: - width / 2, y: - height / 2, type:'s' },
			[
				{ friction: 1, shape: { type: 'edge', x1: 0,     y1: 0,      x2: width, y2: 0       } },
				{ friction: 1, shape: { type: 'edge', x1: 0,     y1: height, x2: width, y2: height  } },
				{ friction: 1, shape: { type: 'edge', x1: 0,     y1: 0,      x2: 0,     y2: height  } },
				{ friction: 1, shape: { type: 'edge', x1: width, y1: 0,      x2: width, y2: height  } }
			]
		);
	}

	//
	createDebugDraw(options) {
		var dd = new b2DebugDraw();
		dd.SetSprite(options.sprite);
		dd.SetDrawScale(options.scale);
		dd.SetFillAlpha(options.alpha);
		dd.SetLineThickness(options.lineThickness);
		dd.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
		this._debugDrawEnabled = true;
		return dd;
	}

	//
	// start() {
	// 	if(this._isRun) { return; }
	// 	else {
	// 		this._isRun = true;
	// 		this.update();
	// 	}
	// }

	//
	// stop() {
	// 	this._isRun = false;
	// }

	refresh(dt) {
		Engine.prototype.refresh.call(this, dt);
		this.update(dt/1000);
	}

	//
	update(dt) {
		var self = this;

		/*		if(this._isRun) {
					// fix bug for Chrome
					window.requestAnimationFrame(function(){ self.update.call(self) });
				}*/

		this._control.update();

		dt = dt || 1/60;
		this._world.Step(dt, 4, 3); // deltaTime, velocityIterations, positionIterations
		if(this._debugDrawEnabled) { this._world.DrawDebugData(); }
		this._world.ClearForces();
	}

	/* ******************* *
	 * CONTROL SECTION     *
	 * =================== *
	 * Working in progress *
	 * ******************* */
	setDirectControl() {
		var mouseX, mouseY, mousePVec, isMouseDown, selectedBody, mouseJoint;
		var canvasPosition = this._canvas.getBoundingClientRect();
		var self = this;

		return {
			turnOn:turnOn,
			turnOff:turnOff,
			update:update
		};

		function turnOn() {
			document.addEventListener('mousedown', handleMouseDown, true);
			document.addEventListener('touchstart', handleMouseDown, true);
			document.addEventListener('mouseup', handleMouseUp, true);
			document.addEventListener('touchend', handleMouseUp, true);
		}

		function turnOff() {
			isMouseDown = false;
			document.removeEventListener('mousedown', handleMouseDown, true);
			document.removeEventListener('touchstart', handleMouseDown, true);
			document.removeEventListener('mouseup', handleMouseUp, true);
			document.removeEventListener('touchend', handleMouseUp, true);
		}

		function handleMouseDown(e) {
			canvasPosition = self._canvas.getBoundingClientRect();
			isMouseDown = true;
			handleMouseMove(e);
			document.addEventListener('mousemove', handleMouseMove, true);
			document.addEventListener('touchmove', handleMouseMove, true);
		}

		function handleMouseUp() {
			document.removeEventListener('mousemove', handleMouseMove, true);
			document.removeEventListener('touchmove', handleMouseMove, true);
			isMouseDown = false;
			mouseX = undefined;
			mouseY = undefined;
		}

		function handleMouseMove(e) {
			var clientX, clientY, rp;
			if(e.clientX) {
				clientX = e.clientX;
				clientY = e.clientY;
			}
			else if(e.changedTouches && e.changedTouches.length > 0) {
				var touch = e.changedTouches[e.changedTouches.length - 1];
				clientX = touch.clientX;
				clientY = touch.clientY;
			}
			else {
				return;
			}
			rp = self.getCoordinateFrom(clientX - canvasPosition.left, clientY - canvasPosition.top);
			mouseX = rp.x / self.SCALE;
			mouseY = rp.y / self.SCALE;
			// mouseX = (clientX - canvasPosition.left) / self.SCALE;
			// mouseY = (clientY - canvasPosition.top) / self.SCALE;
			e.preventDefault();
		}

		function update() {
			if(isMouseDown && (!mouseJoint)) {
				var body = self.getBodyAt(mouseX, mouseY); //getBodyAtMouse();
				if(body) {
					var md = new Box2D.Dynamics.Joints.b2MouseJointDef();
					md.bodyA = self._world.GetGroundBody();
					md.bodyB = body;
					md.target.Set(mouseX, mouseY);
					md.collideConnected = true;
					md.maxForce = 300.0 * body.GetMass();
					mouseJoint = self._world.CreateJoint(md);
					body.SetAwake(true);
				}
			}

			if(mouseJoint) {
				if(isMouseDown) {
					mouseJoint.SetTarget(new b2Vec2(mouseX, mouseY));
				} else {
					self._world.DestroyJoint(mouseJoint);
					mouseJoint = null;
				}
			}
		}
	}

	/* ************ *
	 * BODY SECTION *
	 * ************ */

	// Get list of all bodies
	getBodyList() {
		var list = [];

		getBody( this._world.GetBodyList() );
		return list;

		function getBody(body) {
			if(body) {
				list.push(body);
				getBody(body.GetNext());
			}
		}
	}

	// Get details of body
	getBodyDetails(body) {
		var type = ['static', 'kinematic', 'dynamic'][ body.GetType() ],
			position = body.GetPosition(),
			fixtures = [];

		getFixtures( body.GetFixtureList() );
		return {
			x: position.x,
			y: position.y,
			a: body.GetAngle(),
			type: type,
			data: body.GetUserData(),
			fixtures: fixtures
		};

		function getFixtures(fix) {
			if(fix) {
				var shape = fix.GetShape();
				fixtures.push({
					type: fix.GetType(),
					density: fix.GetDensity(),
					friction: fix.GetFriction(),
					shape: shape.GetType() === 0 ? {
						type:'circle',
						radius:shape.GetRadius()
					} : {
						type:'polygon',
						points:(function(vec){
							return vec.map(function(v){ return {x:v.x, y:v.y}; });
						})(shape.GetVertices())
					}
				});
				getFixtures(fix.GetNext());
			}
		}
	}

	//
	getBodyAt(x, y) {
		var mousePVec = new b2Vec2(x, y);
		var aabb = new b2AABB();
		aabb.lowerBound.Set(x - 0.001, y - 0.001);
		aabb.upperBound.Set(x + 0.001, y + 0.001);

		// Query the world for overlapping shapes
		var selectedBody = null;
		this._world.QueryAABB(getBodyCB, aabb);
		return selectedBody;

		function getBodyCB(fixture) {
			if(fixture.GetBody().GetType() !== b2Body.b2_staticBody) {
				if(fixture.GetShape().TestPoint(fixture.GetBody().GetTransform(), mousePVec)) {
					selectedBody = fixture.GetBody();
					return false;
				}
			}
			return true;
		}
	}

	// Create body
	createBody(options, fixtures, data) {
		var self = this,
			TYPE = {
				s:b2Body.b2_staticBody,
				static:b2Body.b2_staticBody,
				k:b2Body.b2_kinematicBody,
				kinematic:b2Body.b2_kinematicBody,
				d:b2Body.b2_dynamicBody,
				dynamic:b2Body.b2_dynamicBody
			};
		fixtures = fixtures || [];

		var bodyDef = new b2BodyDef();
		bodyDef.type = TYPE[ options.type ]; //b2Body.b2_dynamicBody;
		bodyDef.position.x = options.x;
		bodyDef.position.y = options.y;
		if(data !== undefined) { bodyDef.userData = data; }

		if(typeof fixtures === 'object' && !(fixtures instanceof Array)) { fixtures = [fixtures]; }

		var b = this._world.CreateBody(bodyDef);
		fixtures.forEach(addFixtures);
		return b;

		function addFixtures(f) {
			b.CreateFixture( self.createFixture(f) );
		}
	}

	// Create fixture
	createFixture(options) {
		var fixture = new b2FixtureDef();
		fixture.density = options.density;
		fixture.friction = options.friction;
		fixture.restitution = options.restitution;
		fixture.shape = this.createShape(options.shape);
		return fixture;
	}

	// Create shape
	createShape(options) {
		var shape = new b2PolygonShape();

		switch(options.type) {
			case 'box':
				shape.SetAsBox(options.w/2, options.h/2);
				break;
			case 'edge':
				shape.SetAsEdge(new b2Vec2(options.x1, options.y1), new b2Vec2(options.x2, options.y2));
				break;
			case 'circle':
				shape = new b2CircleShape(options.r);
				break;
			default:
				var vectors = [];
				options.forEach(function(v) { vectors.push( new b2Vec2(v.x, v.y) ) });
				shape.SetAsArray(vectors, vectors.length);
		}
		return shape;
	}

	//
	addRevoluteJoint(body1, body2, params) {
		var joint = new b2RevoluteJointDef();
		joint.Initialize(body1, body2, body1.GetWorldCenter());
		if (params && params.motorSpeed) {
			joint.motorSpeed = params.motorSpeed;
			joint.maxMotorTorque = params.maxMotorTorque;
			joint.enableMotor = params.enableMotor;
		}

		return this._world.CreateJoint(joint);
	}

	// Apply impulse to body
	applyImpulse(body, degrees, power) {
		body.ApplyImpulse(
			new b2Vec2(
				Math.cos(degrees * (Math.PI / 180)) * power,
				Math.sin(degrees * (Math.PI / 180)) * power
			),
			body.GetWorldCenter()
		);
	}
}

//--------------------------------------------------------------------------------------------------

// Default settings
Physics.default = {
	scale: 30,		// 30px = 1 meter
	gravity: 9.8	// Earth gravity
};

export default Physics;


text:
import { FEMALE, MALE } from 'emojibase';
import { FEMALE_SIGN, MALE_SIGN } from '../constants';
import { Gender, Hexcode } from '../types';

export function extractGender(hexcode: Hexcode): Gender | null {
	if (hexcode.includes(FEMALE_SIGN)) {
		return FEMALE;
	}

	if (hexcode.includes(MALE_SIGN)) {
		return MALE;
	}

	return null;
}