text:
from flatland import Array, Boolean, Integer
from flatland.out import generic
from flatland.out.generic import Context
import six

Unspecified = object()
Unique = object()
schema = Integer.named(u'number')
boolean_schema = Boolean.named(u'bool')
partial_anon_schema = Array.named(u'array').of(Integer)
full_anon_schema = Array.of(Integer)

def assert_bound_transform(fn, tagname, given, expected, **kw):
    return assert_transform(fn, tagname, given, expected, **kw)

def assert_unbound_transform(fn, tagname, given, expected, **kw):
    kw['bind'] = None
    return assert_transform(fn, tagname, given, expected, **kw)

def assert_transform(fn, tagname, given, expected,
                     context=Unspecified,
                     bind=Unspecified,
                     contents=Unspecified,
                     expected_contents=Unspecified):
    if context is Unspecified:
        context = Context()
    if bind is Unspecified:
        bind = schema(123)

    got = given.copy()
    got_contents = fn(tagname, got, contents, context, bind)
    assert got == expected
    assert got_contents == expected_contents

    types = zip(sorted(got.keys()), sorted(expected.keys()))
    for got_key, expected_key in types:
        assert type(got_key) is type(expected_key)

class _TestAttributeTransform(object):
    attribute = NotImplemented
    applied_value = NotImplemented
    control_attribute = NotImplemented
    tagname = NotImplemented
    skip_tags = ()
    operates_on_unbound = False

    bind_factory = lambda: schema(123)
    transform = NotImplemented
    base_context = ()

    def assert_transform(self, given, expected,
                         context=None,
                         tagname=None,
                         bind=Unspecified):
        if hasattr(self.transform, '__func__'):
            transform = self.transform.__func__
        else:
            transform = self.transform
        if context is None:
            context = self._context()
        if tagname is None:
            tagname = self.tagname
        if bind is Unspecified:
            if hasattr(self.bind_factory, '__func__'):
                bind = self.bind_factory.__func__()
            else:
                bind = self.bind_factory()

        assert_transform(transform, tagname, given, expected, context, bind)

    def _context(self, overrides=()):
        context = Context()
        context.push()
        context.update(self.base_context)
        context.update(overrides)
        return context

    def test_known_tag(self):
        given = {}
        if generic._default_context[self.control_attribute] is True:
            expected = {self.attribute: self.applied_value}
        elif generic._default_context[self.control_attribute] is False:
            expected = {}
        else:
            raise AssertionError

        for tagname in generic._auto_tags[self.attribute]:
            if tagname in self.skip_tags:
                continue
            yield self.assert_transform, given, expected, None, tagname

    def test_unknown_tag(self):
        given = {}
        expected = {}
        self.assert_transform(given, expected, tagname=u'xyzzy')

    def test_unknown_tag_existing_value_unchanged(self):
        given = {self.attribute: u'existing'}
        expected = {self.attribute: u'existing'}
        self.assert_transform(given, expected, tagname=u'xyzzy')

    def test_existing_value_unchanged(self):
        given = {self.attribute: u'local'}
        expected = {self.attribute: u'local'}
        self.assert_transform(given, expected)

    def test_existing_value_force_changed(self):
        given = {self.attribute: u'local', self.control_attribute: u'on'}
        expected = {self.attribute: self.applied_value}
        self.assert_transform(given, expected)

    def test_context_off(self):
        given = {}
        expected = {}
        context = self._context({self.control_attribute: False})
        self.assert_transform(given, expected, context=context)

    def test_context_on(self):
        given = {}
        expected = {self.attribute: self.applied_value}
        context = self._context({self.control_attribute: True})
        self.assert_transform(given, expected, context=context)

    def test_context_on_unknown_tag(self):
        given = {}
        expected = {}
        context = self._context({self.control_attribute: True})
        self.assert_transform(given, expected,
                              context=context, tagname=u'xyzzy')

    def test_context_auto(self):
        given = {}
        default = generic._default_context[self.control_attribute]
        if default is True:
            expected = {self.attribute: self.applied_value}
        elif default is False:
            expected = {}
        else:
            raise AssertionError()
        context = self._context({self.control_attribute: u'auto'})
        self.assert_transform(given, expected, context=context)

    def test_local_off(self):
        given = {self.control_attribute: False}
        expected = {}
        self.assert_transform(given, expected)

    def test_local_on(self):
        given = {self.control_attribute: True}
        expected = {self.attribute: self.applied_value}
        context = self._context({self.control_attribute: False})
        self.assert_transform(given, expected, context=context)

    def test_local_auto(self):
        given = {self.control_attribute: u'auto'}
        expected = {self.attribute: self.applied_value}
        context = self._context({self.control_attribute: True})
        self.assert_transform(given, expected, context=context)

        expected = {}
        context = self._context({self.control_attribute: False})
        self.assert_transform(given, expected, context=context)

    def test_local_on_unbound(self):
        # some can't be forced unless a bind is also present
        given = {self.control_attribute: True}
        if self.operates_on_unbound:
            expected = {self.attribute: self.applied_value}
        else:
            expected = {}
        self.assert_transform(given, expected, bind=None)

class TestName(_TestAttributeTransform):
    attribute = u'name'
    control_attribute = u'auto_name'
    applied_value = u'number'
    transform = generic.transform_name
    tagname = u'input'

# basic smoke test for context issues only
class TestTextboxValue(_TestAttributeTransform):
    attribute = u'value'
    control_attribute = u'auto_value'
    applied_value = u'123'
    transform = generic.transform_value
    tagname = u'input'
    skip_tags = ['textarea', 'option']

class TestButtonValue(_TestAttributeTransform):
    attribute = u'value'
    control_attribute = u'auto_value'
    applied_value = u'123'
    transform = generic.transform_value
    tagname = u'button'
    skip_tags = ['textarea', 'option']

class TestDomID(_TestAttributeTransform):
    attribute = u'id'
    control_attribute = u'auto_domid'
    applied_value = u'f_number'
    transform = generic.transform_domid
    tagname = u'input'

class TestFor(_TestAttributeTransform):
    attribute = u'for'
    control_attribute = u'auto_for'
    applied_value = u'f_number'
    transform = generic.transform_for
    tagname = u'label'

class TestTabindex(_TestAttributeTransform):
    attribute = u'tabindex'
    control_attribute = u'auto_tabindex'
    applied_value = u'5'
    operates_on_unbound = True
    transform = generic.transform_tabindex
    tagname = u'input'
    base_context = {u'tabindex': 5}

def test_name_anonymous_bind():
    bind = partial_anon_schema([123])[0]
    given = {}
    expected = {u'name': u'array'}
    assert_transform(generic.transform_name,
                     u'input', given, expected, bind=bind)

    bind = full_anon_schema([123])[0]
    given = {}
    expected = {}
    assert_transform(generic.transform_name,
                     u'input', given, expected, bind=bind)

def test_contents_textarea():
    given = None
    expected = u'123'
    assert_bound_transform(generic.transform_value,
                           u'textarea', {}, {},
                           contents=given, expected_contents=expected)

    for given in u'existing_value', u'', generic.Markup('xyzzy'), []:
        expected = given
        assert_bound_transform(generic.transform_value,
                               u'textarea', {}, {},
                               contents=given, expected_contents=expected)

def test_value_checkable():
    # check Scalar(..) and Array.of(..)
    for bind in schema(123), partial_anon_schema([123, 456]):
        for type in u'checkbox', u'radio':
            given = {
                u'type': type,
                u'value': u'123',
                }
            expected = {
                u'type': type,
                u'value': u'123',
                u'checked': u'checked',
                }
            assert_transform(generic.transform_value,
                             u'input', given, expected, bind=bind)

            given = {
                u'type': type,
                u'value': u'999',
                }
            expected = {
                u'type': type,
                u'value': u'999',
                }
            assert_transform(generic.transform_value,
                             u'input', given, expected, bind=bind)

            given = {
                u'type': type,
                u'value': u'999',
                u'checked': u'checked',
                }
            expected = {
                u'type': type,
                u'value': u'999',
                }
            assert_transform(generic.transform_value,
                             u'input', given, expected, bind=bind)

            given = {
                u'type': type,
                u'value': u'999',
                u'checked': u'',
                }
            expected = {
                u'type': type,
                u'value': u'999',
                }
            assert_transform(generic.transform_value,
                             u'input', given, expected, bind=bind)

def test_value_checkbox_boolean():
    bind = boolean_schema(True)
    given = {
        u'type': u'checkbox',
        }
    expected = {
        u'type': u'checkbox',
        u'value': u'1',
        u'checked': u'checked',
        }
    assert_transform(generic.transform_value,
                     u'input', given, expected, bind=bind)

    bind = boolean_schema(False)
    given = {
        u'type': u'checkbox',
        }
    expected = {
        u'type': u'checkbox',
        u'value': u'1',
        }
    assert_transform(generic.transform_value,
                     u'input', given, expected, bind=bind)

    bind = boolean_schema(True)
    given = {
        u'type': u'checkbox',
        u'value': u'2',
        }
    expected = {
        u'type': u'checkbox',
        u'value': u'2',
        }
    assert_transform(generic.transform_value,
                     u'input', given, expected, bind=bind)

def test_value_omitted():
    bind = schema(123)

    for type in u'password', u'file', u'image':
        given = {
            u'type': type,
            }
        expected = {
            u'type': type,
            }
        assert_transform(generic.transform_value,
                         u'input', given, expected, bind=bind)
        given = {
            u'type': type,
            u'value': u'999',
            }
        expected = {
            u'type': type,
            u'value': u'999',
            }
        assert_transform(generic.transform_value,
                         u'input', given, expected, bind=bind)
        given = {
            u'type': type,
            u'auto_value': True,
            }
        expected = {
            u'type': type,
            u'value': u'123',
            }
        assert_transform(generic.transform_value,
                         u'input', given, expected, bind=bind)

        given = {
            u'type': type,
            u'auto_value': True,
            u'value': u'999',
            }
        expected = {
            u'type': type,
            u'value': u'123',
            }
        assert_transform(generic.transform_value,
                         u'input', given, expected, bind=bind)

def test_value_option():
 # check Scalar(..) and Array.of(..)
    for bind in schema(123), partial_anon_schema([123, 456]):
        given = {
            u'value': u'123',
            }
        expected = {
            u'value': u'123',
            u'selected': u'selected',
            }
        assert_transform(generic.transform_value,
                         u'option', given, expected, bind=bind)

        given = {
            u'value': u'999',
            }
        expected = {
            u'value': u'999',
            }
        assert_transform(generic.transform_value,
                         u'option', given, expected, bind=bind)

        contents = expected_contents = u'123'
        given = {
            }
        expected = {
            u'selected': u'selected',
            }
        assert_transform(generic.transform_value,
                         u'option', given, expected, bind=bind,
                         contents=contents,
                         expected_contents=expected_contents)

        contents = expected_contents = u'    123     '
        given = {
            }
        expected = {
            u'selected': u'selected',
            }
        assert_transform(generic.transform_value,
                         u'option', given, expected, bind=bind,
                         contents=contents,
                         expected_contents=expected_contents)

        contents = expected_contents = u'999'
        given = {
            }
        expected = {
            }
        assert_transform(generic.transform_value,
                         u'option', given, expected, bind=bind,
                         contents=contents,
                         expected_contents=expected_contents)

        contents = expected_contents = None
        given = {
            }
        expected = {
            }
        assert_transform(generic.transform_value,
                         u'option', given, expected, bind=bind,
                         contents=contents,
                         expected_contents=expected_contents)

        # This matches value = contents via a sentinel object
        given = {
            }
        expected = {
            }
        assert_transform(generic.transform_value,
                         u'option', given, expected, bind=bind)

        contents = expected_contents = u'123'
        given = {
            u'value': u'999',
            }
        expected = {
            u'value': u'999',
            }
        assert_transform(generic.transform_value,
                         u'option', given, expected, bind=bind,
                         contents=contents,
                         expected_contents=expected_contents)

        given = {
            u'value': u'999',
            u'selected': u'selected',
            }
        expected = {
            u'value': u'999',
            }
        assert_transform(generic.transform_value,
                         u'option', given, expected, bind=bind)

        given = {
            u'value': u'999',
            u'selected': u'',
            }
        expected = {
            u'value': u'999',
            }
        assert_transform(generic.transform_value,
                         u'option', given, expected, bind=bind)

def test_domid_checkable_array():
    bind = partial_anon_schema([123, 456])
    context = Context()
    context[u'auto_domid'] = True

    assert_ = lambda given, expected: assert_transform(
        generic.transform_domid, u'input', given, expected,
        context=context, bind=bind)

    for type in 'radio', 'checkbox':
        given = {
            u'type': u'radio',
            u'value': u'xxx',
            }
        expected = {
            u'type': u'radio',
            u'value': u'xxx',
            u'id': u'f_array_xxx',
            }
        assert_(given, expected)

        given = {
            u'type': u'radio',
            }
        expected = {
            u'type': u'radio',
            u'id': u'f_array',
            }
        assert_(given, expected)

        given = {
            u'type': u'radio',
            u'value': u'Ḑộộḏ!',
            }
        expected = {
            u'type': u'radio',
            u'value': u'Ḑộộḏ!',
            u'id': u'f_array',
            }
        assert_(given, expected)

        given = {
            u'type': u'radio',
            u'value': u'Ḑộộḏ! yo',
            }
        expected = {
            u'type': u'radio',
            u'value': u'Ḑộộḏ! yo',
            u'id': u'f_array_yo',
            }
        assert_(given, expected)

def test_domid_checkable_scalar():
    context = Context()
    context[u'auto_domid'] = True

    for type in 'radio', 'checkbox':
        given = {
            u'type': u'radio',
            u'value': u'xxx',
            }
        expected = {
            u'type': u'radio',
            u'value': u'xxx',
            u'id': u'f_number_xxx',
            }
        assert_bound_transform(generic.transform_domid,
                               u'input', given, expected, context=context)

def test_domid_anonymous_bind():
    bind = partial_anon_schema([123])[0]
    given = {u'auto_domid': True}
    expected = {u'id': u'f_array'}
    assert_transform(generic.transform_domid,
                     u'input', given, expected, bind=bind)

    bind = full_anon_schema([123])[0]
    given = {u'auto_domid': True}
    expected = {}
    assert_transform(generic.transform_domid,
                     u'input', given, expected, bind=bind)

def test_domid_unbound_naming():
    given = {u'name': u'unbound',
             u'auto_domid': u'on'}
    expected = {u'id': u'f_unbound', u'name': u'unbound'}
    assert_unbound_transform(generic.transform_domid,
                             u'input', given, expected)

def test_domid_custom_formatting():
    context = Context()
    context[u'domid_format'] = u'--%s--'
    given = {u'auto_domid': u'on'}
    expected = {u'id': u'--number--'}
    assert_bound_transform(generic.transform_domid,
                           u'input', given, expected, context=context)

def test_for_anonymous_bind():
    bind = partial_anon_schema([123])[0]
    given = {u'auto_for': True}
    expected = {u'for': u'f_array'}
    assert_transform(generic.transform_for,
                     u'label', given, expected, bind=bind)

    bind = full_anon_schema([123])[0]
    given = {u'auto_for': True}
    expected = {}
    assert_transform(generic.transform_for,
                     u'label', given, expected, bind=bind)

def test_tabindex_stop_numbers():
    given = {u'auto_tabindex': u'on'}

    for stop_num in -1, -2:
        context = Context()
        context[u'tabindex'] = stop_num
        expected = {u'tabindex': six.text_type(stop_num)}
        assert_bound_transform(generic.transform_tabindex,
                               u'input', given, expected, context=context)
        assert_unbound_transform(generic.transform_tabindex,
                                 u'input', given, expected, context=context)
        assert context[u'tabindex'] == stop_num

def test_tabindex_zero():
    given = {}
    context = Context()
    context[u'auto_tabindex'] = True
    context[u'tabindex'] = 0

    expected = {}
    assert_unbound_transform(generic.transform_tabindex,
                             u'input', given, expected, context=context)

def test_tabindex_increment():
    given = {}
    context = Context()
    context[u'auto_tabindex'] = True
    context[u'tabindex'] = 1

    expected = {u'tabindex': u'1'}
    assert_unbound_transform(generic.transform_tabindex,
                             u'input', given, expected, context=context)

    expected = {u'tabindex': u'2'}
    assert_unbound_transform(generic.transform_tabindex,
                             u'input', given, expected, context=context)

    assert context[u'tabindex'] != 1

def test_filter():

    given = {}

    def filter1(tagname, attributes, contents, context, bind):
        attributes[u'donut'] = u'xyzzy'
        return contents

    context = Context()
    context[u'auto_filter'] = True
    context[u'filters'] = [filter1]

    expected = {
        u'donut': u'xyzzy',
        }
    assert_bound_transform(generic.transform_filters,
                           u'div', given, expected, context=context)

    def filter2(tagname, attributes, contents, context, bind):
        return bind.label

    context = Context()
    context[u'auto_filter'] = True
    context[u'filters'] = [filter2, filter1]
    contents = u'bbq'
    expected_contents = u'number'

    expected = {
        u'donut': u'xyzzy',
        }
    assert_bound_transform(generic.transform_filters,
                           u'div', given, expected, context=context,
                           contents=contents,
                           expected_contents=expected_contents)

    context = Context()
    context[u'auto_filter'] = True
    context[u'filters'] = ()
    contents = u'bbq'
    expected_contents = u'bbq'

    expected = {}
    assert_bound_transform(generic.transform_filters,
                           u'div', given, expected, context=context,
                           contents=contents,
                           expected_contents=expected_contents)

def test_filter_want():

    def filter1(tagname, attributes, contents, context, bind):
        attributes[u'donut'] = u'xyzzy'
        return contents

    filter1.tags = [u'div', u'input']

    for tag in u'div', u'input':
        context = Context()
        context[u'auto_filter'] = True
        context[u'filters'] = [filter1]
        given = {}
        expected = {
            u'donut': u'xyzzy',
            }
        assert_bound_transform(generic.transform_filters,
                           tag, given, expected, context=context)

    context = Context()
    context[u'auto_filter'] = True
    context[u'filters'] = [filter1]
    given = {}
    expected = {}
    assert_bound_transform(generic.transform_filters,
                           u'horse', given, expected, context=context)


text:
package org.jivesoftware.openfire.nio;

import static org.jivesoftware.openfire.spi.ConnectionManagerImpl.COMPRESSION_FILTER_NAME;
import static org.jivesoftware.openfire.spi.ConnectionManagerImpl.EXECUTOR_FILTER_NAME;
import static org.jivesoftware.openfire.spi.ConnectionManagerImpl.TLS_FILTER_NAME;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;

import javax.net.ssl.*;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.filterchain.IoFilterChain;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.compression.CompressionFilter;
import org.apache.mina.filter.ssl.SslFilter;
import org.jivesoftware.openfire.Connection;
import org.jivesoftware.openfire.ConnectionCloseListener;
import org.jivesoftware.openfire.PacketDeliverer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.net.StanzaHandler;
import org.jivesoftware.openfire.session.LocalSession;
import org.jivesoftware.openfire.session.Session;
import org.jivesoftware.openfire.spi.ConnectionConfiguration;
import org.jivesoftware.openfire.spi.EncryptionArtifactFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.Packet;

/**
 * Implementation of {@link Connection} interface specific for NIO connections when using the Apache MINA framework.
 *
 * @author Gaston Dombiak
 * @see Apache MINA
 */
public class NIOConnection implements Connection {

    private static final Logger Log = LoggerFactory.getLogger(NIOConnection.class);
    private ConnectionConfiguration configuration;

    /**
     * The utf-8 charset for decoding and encoding XMPP packet streams.
     */
    public static final String CHARSET = "UTF-8";

    private LocalSession session;
    private IoSession ioSession;

    private ConnectionCloseListener closeListener;

    /**
     * Deliverer to use when the connection is closed or was closed when delivering
     * a packet.
     */
    private PacketDeliverer backupDeliverer;
    private boolean flashClient = false;
    private int majorVersion = 1;
    private int minorVersion = 0;
    private String language = null;

    /**
     * TLS policy currently in use for this connection.
     */
    private TLSPolicy tlsPolicy = TLSPolicy.optional;
    private boolean usingSelfSignedCertificate;

    /**
     * Compression policy currently in use for this connection.
     */
    private CompressionPolicy compressionPolicy = CompressionPolicy.disabled;
    private static final ThreadLocal<CharsetEncoder> encoder = new ThreadLocalEncoder();

    /**
     * Flag that specifies if the connection should be considered closed. Closing a NIO connection
     * is an asynch operation so instead of waiting for the connection to be actually closed just
     * keep this flag to avoid using the connection between #close was used and the socket is actually
     * closed.
     */
    private AtomicReference<State> state = new AtomicReference<>(State.OPEN);

    /**
     * Lock used to ensure the integrity of the underlying IoSession (refer to
     * https://issues.apache.org/jira/browse/DIRMINA-653 for details)
     *

     * This lock can be removed once Openfire guarantees a stable delivery
     * order, in which case {@link #deliver(Packet)} won't be called
     * concurrently any more, which made this lock necessary in the first place.
     *

     */
    private final ReentrantLock ioSessionLock = new ReentrantLock(true);

    public NIOConnection( IoSession session, PacketDeliverer packetDeliverer, ConnectionConfiguration configuration ) {
        this.ioSession = session;
        this.backupDeliverer = packetDeliverer;
        this.configuration = configuration;
    }

    @Override
    public boolean validate() {
        if (isClosed()) {
            return false;
        }
        deliverRawText(" ");
        return !isClosed();
    }

    @Override
    public void registerCloseListener(ConnectionCloseListener listener, Object ignore) {
        if (closeListener != null) {
            throw new IllegalStateException("Close listener already configured");
        }
        if (isClosed()) {
            listener.onConnectionClose(session);
        }
        else {
            closeListener = listener;
        }
    }

    @Override
    public void removeCloseListener(ConnectionCloseListener listener) {
        if (closeListener == listener) {
            closeListener = null;
        }
    }

    @Override
    public byte[] getAddress() throws UnknownHostException {
        final SocketAddress remoteAddress = ioSession.getRemoteAddress();
        if (remoteAddress == null) throw new UnknownHostException();
        final InetSocketAddress socketAddress = (InetSocketAddress) remoteAddress;
        final InetAddress address = socketAddress.getAddress();
        return address.getAddress();
    }

    @Override
    public String getHostAddress() throws UnknownHostException {
        final SocketAddress remoteAddress = ioSession.getRemoteAddress();
        if (remoteAddress == null) throw new UnknownHostException();
        final InetSocketAddress socketAddress = (InetSocketAddress) remoteAddress;
        final InetAddress inetAddress = socketAddress.getAddress();
        return inetAddress.getHostAddress();
    }

    @Override
    public String getHostName() throws UnknownHostException {
        final SocketAddress remoteAddress = ioSession.getRemoteAddress();
        if (remoteAddress == null) throw new UnknownHostException();
        final InetSocketAddress socketAddress = (InetSocketAddress) remoteAddress;
        final InetAddress inetAddress = socketAddress.getAddress();
        return inetAddress.getHostName();
    }

    @Override
    public Certificate[] getLocalCertificates() {
        SSLSession sslSession = (SSLSession) ioSession.getAttribute(SslFilter.SSL_SESSION);
        if (sslSession != null) {
            return sslSession.getLocalCertificates();
        }
        return new Certificate[0];
    }

    @Override
    public Certificate[] getPeerCertificates() {
        try {
            SSLSession sslSession = (SSLSession) ioSession.getAttribute(SslFilter.SSL_SESSION);
            if (sslSession != null) {
                return sslSession.getPeerCertificates();
            }
        } catch (SSLPeerUnverifiedException e) {
            if (Log.isTraceEnabled()) {
                // This is perfectly acceptable when mutual authentication is not enforced by Openfire configuration.
                Log.trace( "Peer does not offer certificates in session: " + session, e);
            }
        }
        return new Certificate[0];
    }

    @Override
    public void setUsingSelfSignedCertificate(boolean isSelfSigned) {
        this.usingSelfSignedCertificate = isSelfSigned;
    }

    @Override
    public boolean isUsingSelfSignedCertificate() {
        return usingSelfSignedCertificate;
    }

    @Override
    public PacketDeliverer getPacketDeliverer() {
        return backupDeliverer;
    }

    @Override
    public void close() {
        if (state.compareAndSet(State.OPEN, State.CLOSED)) {

            // Ensure that the state of this connection, its session and the MINA context are eventually closed.

            if (session != null) {
                session.setStatus(Session.STATUS_CLOSED);
            }

            try {
                deliverRawText0(flashClient ? "</flash:stream>" : "</stream:stream>");
            } catch (Exception e) {
                Log.error("Failed to deliver stream close tag: " + e.getMessage());
            }

            try {
                ioSession.close(true);
            } catch (Exception e) {
                Log.error("Exception while closing MINA session", e);
            }
            notifyCloseListeners(); // clean up session, etc.
        }
    }

    @Override
    public void systemShutdown() {
        deliverRawText("<stream:error><system-shutdown " +
                "xmlns='urn:ietf:params:xml:ns:xmpp-streams'/></stream:error>");
        close();
    }

    /**
     * Notifies all close listeners that the connection has been closed.
     * Used by subclasses to properly finish closing the connection.
     */
    private void notifyCloseListeners() {
        if (closeListener != null) {
            try {
                closeListener.onConnectionClose(session);
            } catch (Exception e) {
                Log.error("Error notifying listener: " + closeListener, e);
            }
        }
    }

    @Override
    public void init(LocalSession owner) {
        session = owner;
    }

    @Override
    public void reinit(LocalSession owner) {
        session = owner;
        StanzaHandler stanzaHandler = getStanzaHandler();
        stanzaHandler.setSession(owner);
    }

    protected StanzaHandler getStanzaHandler() {
        return (StanzaHandler)ioSession.getAttribute(ConnectionHandler.HANDLER);
    }

    @Override
    public boolean isClosed() {
        return state.get() == State.CLOSED;
    }

    @Override
    public boolean isSecure() {
        return ioSession.getFilterChain().contains(TLS_FILTER_NAME);
    }

    @Override
    public void deliver(Packet packet) throws UnauthorizedException {
        if (isClosed()) {
            backupDeliverer.deliver(packet);
        }
        else {
            boolean errorDelivering = false;
            IoBuffer buffer = IoBuffer.allocate(4096);
            buffer.setAutoExpand(true);
            try {
                buffer.putString(packet.getElement().asXML(), encoder.get());
                if (flashClient) {
                    buffer.put((byte) '\0');
                }
                buffer.flip();

                ioSessionLock.lock();
                try {
                    ioSession.write(buffer);
                } finally {
                    ioSessionLock.unlock();
                }
            }
            catch (Exception e) {
                Log.debug("Error delivering packet:\n" + packet, e);
                errorDelivering = true;
            }
            if (errorDelivering) {
                close();
                // Retry sending the packet again. Most probably if the packet is a
                // Message it will be stored offline
                backupDeliverer.deliver(packet);
            }
            else {
                session.incrementServerPacketCount();
            }
        }
    }

    @Override
    public void deliverRawText(String text) {
        if (!isClosed()) {
            deliverRawText0(text);
        }
    }

    private void deliverRawText0(String text){
        boolean errorDelivering = false;
        IoBuffer buffer = IoBuffer.allocate(text.length());
        buffer.setAutoExpand(true);
        try {
            //Charset charset = Charset.forName(CHARSET);
            //buffer.putString(text, charset.newEncoder());
            buffer.put(text.getBytes(StandardCharsets.UTF_8));
            if (flashClient) {
                buffer.put((byte) '\0');
            }
            buffer.flip();
            ioSessionLock.lock();
            try {
                ioSession.write(buffer);
            }
            finally {
                ioSessionLock.unlock();
            }
        }
        catch (Exception e) {
            Log.debug("Error delivering raw text:\n" + text, e);
            errorDelivering = true;
        }

        // Attempt to close the connection if delivering text fails.
        if (errorDelivering) {
            close();
        }
    }

    @Deprecated
    @Override
    public void startTLS(boolean clientMode, String remoteServer, ClientAuth authentication) throws Exception {
        startTLS( clientMode );
    }

    public void startTLS(boolean clientMode) throws Exception {

        final EncryptionArtifactFactory factory = new EncryptionArtifactFactory( configuration );
        final SslFilter filter;
        if ( clientMode )
        {
            filter = factory.createClientModeSslFilter();
        }
        else
        {
            filter = factory.createServerModeSslFilter();
        }

        ioSession.getFilterChain().addBefore(EXECUTOR_FILTER_NAME, TLS_FILTER_NAME, filter);
        ioSession.setAttribute(SslFilter.DISABLE_ENCRYPTION_ONCE, Boolean.TRUE);

        if ( !clientMode ) {
            // Indicate the client that the server is ready to negotiate TLS
            deliverRawText( "<proceed xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>" );
        }
    }

    @Override
    public void addCompression() {
        IoFilterChain chain = ioSession.getFilterChain();
        String baseFilter = EXECUTOR_FILTER_NAME;
        if (chain.contains(TLS_FILTER_NAME)) {
            baseFilter = TLS_FILTER_NAME;
        }
        chain.addAfter(baseFilter, COMPRESSION_FILTER_NAME, new CompressionFilter(true, false, CompressionFilter.COMPRESSION_MAX));
    }

    @Override
    public void startCompression() {
        CompressionFilter ioFilter = (CompressionFilter) ioSession.getFilterChain().get(COMPRESSION_FILTER_NAME);
        ioFilter.setCompressOutbound(true);
    }

    @Override
    public ConnectionConfiguration getConfiguration()
    {
        return configuration;
    }

    public boolean isFlashClient() {
        return flashClient;
    }

    @Override
    public void setFlashClient(boolean flashClient) {
        this.flashClient = flashClient;
    }

    @Override
    public int getMajorXMPPVersion() {
        return majorVersion;
    }

    @Override
    public int getMinorXMPPVersion() {
        return minorVersion;
    }

    @Override
    public void setXMPPVersion(int majorVersion, int minorVersion) {
        this.majorVersion = majorVersion;
        this.minorVersion = minorVersion;
    }

    @Override
    public boolean isCompressed() {
        return ioSession.getFilterChain().contains(COMPRESSION_FILTER_NAME);
    }

    @Override
    public CompressionPolicy getCompressionPolicy() {
        return compressionPolicy;
    }

    @Override
    public void setCompressionPolicy(CompressionPolicy compressionPolicy) {
        this.compressionPolicy = compressionPolicy;
    }

    @Override
    public TLSPolicy getTlsPolicy() {
        return tlsPolicy;
    }

    @Override
    public void setTlsPolicy(TLSPolicy tlsPolicy) {
        this.tlsPolicy = tlsPolicy;
    }

    @Override
    public String toString() {
        return super.toString() + " MINA Session: " + ioSession;
    }

    private static class ThreadLocalEncoder extends ThreadLocal<CharsetEncoder> {

        @Override
        protected CharsetEncoder initialValue() {
            return StandardCharsets.UTF_8.newEncoder()
                .onMalformedInput(CodingErrorAction.REPORT)
                .onUnmappableCharacter(CodingErrorAction.REPORT);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
These settings apply only when `--python` is specified on the command line.
Please also specify `--python-sdks-folder=<path to the root directory of your azure-sdk-for-python clone>`.
Use `--python-mode=update` if you already have a setup.py and just want to update the code itself.

``` yaml $(python)
azure-arm: true
license-header: MICROSOFT_MIT_NO_VERSION
namespace: azure.mgmt.policyinsights
package-name: azure-mgmt-policyinsights
package-version: 1.0.0b1
clear-output-folder: true
```

``` yaml $(python)
no-namespace-folders: true
output-folder: $(python-sdks-folder)/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights
```

``` yaml $(python)
modelerfour:
  lenient-model-deduplication: true
directive:
  - from: policyEvents.json
    where: $.parameters.fromParameter
    transform: $['x-ms-client-name'] = 'FromProperty'

  - from: policyStates.json
    where: $.parameters.fromParameter
    transform: $['x-ms-client-name'] = 'FromProperty'
```


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace OpenUtau.UI.Models
{
    public class FaderValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double db = (double)value;
            if (db  == -24) return "-Inf";
            if (db < -16) db = db * 2 + 16;
            var result = db > 0 ? string.Format("{0:+00.0}", db) : string.Format("{0:00.0}", db);
            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return 0;
        }
    }

}


text:
    <link rel="stylesheet" type="text/css" href="css/tips.css">

When you need to cast an expression value to the required type the SmartType code completion will help you. For example, type

String s = (<caret is here>

and press &shortcut:SmartTypeCompletion; to see what happens.


text:
var fs = require('fs');
var path = require('path');

var flokme = require('./flok');
var flok = flokme('status-file');

var statusPath = path.join(__dirname, 'status-file', 'flokStatus', 'basic.json');

describe('status-file', function () {

  describe('loadMigrationsStatus', function () {

    var loadMigrationsStatusEmitted = 0;
    var loadedMigrationStatus = 'foobar';
    before(function () {
      flok.on('loadMigrationsStatus', function (migrations) {
        loadMigrationsStatusEmitted++;
        loadedMigrationStatus = migrations;
      });
    });

    it('should load status', function (done) {
      flok._loadMigrationsStatus(function (err) {
        if (err) return done(err);
        done();
      });
    });

    it('should emit loadMigrationsStatus', function () {
      loadMigrationsStatusEmitted.should.equal(1);
      loadedMigrationStatus.should.be.instanceof(Array);
    });

  });

  describe('clearMigrationStatus', function () {
    var status;

    before(function (done) {
      status = fs.readFileSync(statusPath);
      flok._loadMigrations(function (err) {
        if (err) return done(err);
        flok._loadMigrationsStatus(done);
      });
    });

    after(function () {
      if (status) fs.writeFileSync(statusPath, status);
    });

    it('should remove migration status files', function (done) {

      flok._clearMigrationStatus(flok.migrations[0], function (err) {
        if (err) return done(err);
        fs.existsSync(statusPath).should.equal(false);
        done();
      });
    });
  });

});


text:
<?php

$GLOBALS['okt_l10n']['m_contact_config_configuration'] = 'Configuration';

$GLOBALS['okt_l10n']['m_contact_config_general'] = 'General';
$GLOBALS['okt_l10n']['m_contact_config_from_to_choice'] = 'Sender';
$GLOBALS['okt_l10n']['m_contact_config_from_to_website'] = 'The website';
$GLOBALS['okt_l10n']['m_contact_config_from_to_user'] = 'The user';
$GLOBALS['okt_l10n']['m_contact_config_Captcha'] = 'Captcha';
$GLOBALS['okt_l10n']['m_contact_config_no_captcha'] = 'There is no available captcha.';
$GLOBALS['okt_l10n']['m_contact_config_email_image'] = 'Email address image';
$GLOBALS['okt_l10n']['m_contact_config_email_color'] = 'Color';
$GLOBALS['okt_l10n']['m_contact_config_email_font_size'] = 'Font size';

$GLOBALS['okt_l10n']['m_contact_config_access_map'] = 'Access map';
$GLOBALS['okt_l10n']['m_contact_config_activation_access_map'] = 'Activation of the access map';
$GLOBALS['okt_l10n']['m_contact_config_enable_access_map'] = 'Activate the access map';
$GLOBALS['okt_l10n']['m_contact_config_enable_access_map_note'] = 'The information society is not indicated, this feature can not be activated.';
$GLOBALS['okt_l10n']['m_contact_config_display_access_map'] = 'Display of the access map';
$GLOBALS['okt_l10n']['m_contact_config_display_mode_access_map'] = 'Display the access map';
$GLOBALS['okt_l10n']['m_contact_config_display_mode_link'] = 'in a link';
$GLOBALS['okt_l10n']['m_contact_config_display_mode_other_page'] = 'in an other page';
$GLOBALS['okt_l10n']['m_contact_config_display_mode_inside'] = 'inside the contact page';
$GLOBALS['okt_l10n']['m_contact_config_zoom_access_map'] = 'Default zoom level';
$GLOBALS['okt_l10n']['m_contact_config_mode_access_map'] = 'Mode of the access map';
$GLOBALS['okt_l10n']['m_contact_config_mode_access_map_roadmap'] = 'Road map';
$GLOBALS['okt_l10n']['m_contact_config_mode_access_map_satellite'] = 'Satellite';
$GLOBALS['okt_l10n']['m_contact_config_mode_access_map_hybrid'] = 'Hybrid (map and satellite mixed)';
$GLOBALS['okt_l10n']['m_contact_config_mode_access_map_terrain'] = 'Terrain';

$GLOBALS['okt_l10n']['m_contact_config_templates'] = 'Templates';
$GLOBALS['okt_l10n']['m_contact_config_templates_title'] = 'Templates display';
$GLOBALS['okt_l10n']['m_contact_config_templates_contact'] = 'Contact page templates';
$GLOBALS['okt_l10n']['m_contact_config_templates_map'] = 'Access map templates';

$GLOBALS['okt_l10n']['m_contact_config_seo_contact'] = 'Contact page';
$GLOBALS['okt_l10n']['m_contact_config_seo_map'] = 'Access map page';


text:
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com.                */
#include <engine/shared/config.h>

#include <base/math.h>
#include <game/collision.h>
#include <game/client/gameclient.h>
#include <game/client/component.h>

#include "camera.h"
#include "controls.h"

CCamera::CCamera()
{
	m_CamType = CAMTYPE_UNDEFINED;
}

void CCamera::OnRender()
{
	//vec2 center;
	m_Zoom = 1.0f;

	// update camera center
	if(m_pClient->m_Snap.m_SpecInfo.m_Active && !m_pClient->m_Snap.m_SpecInfo.m_UsePosition)
	{
		if(m_CamType != CAMTYPE_SPEC)
		{
			m_pClient->m_pControls->m_MousePos = m_PrevCenter;
			m_pClient->m_pControls->ClampMousePos();
			m_CamType = CAMTYPE_SPEC;
		}
		m_Center = m_pClient->m_pControls->m_MousePos;
	}
	else
	{
		if(m_CamType != CAMTYPE_PLAYER)
		{
			m_pClient->m_pControls->ClampMousePos();
			m_CamType = CAMTYPE_PLAYER;
		}

		vec2 CameraOffset(0, 0);

		float l = length(m_pClient->m_pControls->m_MousePos);
		if(l > 0.0001f) // make sure that this isn't 0
		{
			float DeadZone = g_Config.m_ClMouseDeadzone;
			float FollowFactor = g_Config.m_ClMouseFollowfactor/100.0f;
			float OffsetAmount = max(l-DeadZone, 0.0f) * FollowFactor;

			CameraOffset = normalize(m_pClient->m_pControls->m_MousePos)*OffsetAmount;
		}

		if(m_pClient->m_Snap.m_SpecInfo.m_Active)
			m_Center = m_pClient->m_Snap.m_SpecInfo.m_Position + CameraOffset;
		else
			m_Center = m_pClient->m_LocalCharacterPos + CameraOffset;
	}

	m_PrevCenter = m_Center;
}


text:
Allows running single test in rubymine when using minitest-spec-rails

## Installation

Add this line to your application's Gemfile:

    gem 'rubymine_minitest_spec'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install rubymine_minitest_spec

## Usage

No usage, it simply parses the command line that rubymine passes in so that it can determine what filter to apply to the tests being run.

## Contributing

1. Fork it ( https://github.com/[my-github-username]/rubymine_minitest_spec/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
namespace peloton {
namespace optimizer {

void StatsCalculator::CalculateStats(GroupExpression *gexpr,
                                     ExprSet required_cols, Memo *memo,
                                     concurrency::TransactionContext *txn) {
  gexpr_ = gexpr;
  memo_ = memo;
  required_cols_ = required_cols;
  txn_ = txn;
  gexpr->Op().Accept(this);
}

void StatsCalculator::Visit(const LogicalGet *op) {
  if (op->table == nullptr) {
    // Dummy scan
    return;
  }
  auto table_stats = std::dynamic_pointer_cast<TableStats>(
      StatsStorage::GetInstance()->GetTableStats(op->table->GetDatabaseOid(),
                                                 op->table->GetTableOid(), txn_));
  // First, get the required stats of the base table
  std::unordered_map<std::string, std::shared_ptr<ColumnStats>> required_stats;
  for (auto &col : required_cols_) {
    // Make a copy for required stats since we may want to modify later
    AddBaseTableStats(col, table_stats, required_stats, true);
  }
  auto root_group = memo_->GetGroupByID(gexpr_->GetGroupID());
  // Compute selectivity at the first time
  if (root_group->GetNumRows() == -1) {
    std::unordered_map<std::string, std::shared_ptr<ColumnStats>>
        predicate_stats;
    for (auto &annotated_expr : op->predicates) {
      auto predicate = annotated_expr.expr.get();
      ExprSet expr_set;
      expression::ExpressionUtil::GetTupleValueExprs(expr_set, predicate);
      for (auto &col : expr_set) {
        // Do not copy column stats in predicates since we do not need to modify
        AddBaseTableStats(col, table_stats, predicate_stats, false);
      }
    }
    // Use predicates to update the stats accordingly
    UpdateStatsForFilter(
        table_stats->GetColumnCount() == 0 ? 0 : table_stats->num_rows,
        predicate_stats, op->predicates);
  }
  // Add the stats to the group
  for (auto &column_name_stats_pair : required_stats) {
    auto &column_name = column_name_stats_pair.first;
    auto &column_stats = column_name_stats_pair.second;
    column_stats->num_rows = root_group->GetNumRows();
    memo_->GetGroupByID(gexpr_->GetGroupID())
        ->AddStats(column_name, column_stats);
  }
}

void StatsCalculator::Visit(const LogicalQueryDerivedGet *) {
  // TODO(boweic): Implement stats calculation for logical query derive get
  auto root_group = memo_->GetGroupByID(gexpr_->GetGroupID());
  root_group->SetNumRows(0);
  for (auto &col : required_cols_) {
    PELOTON_ASSERT(col->GetExpressionType() == ExpressionType::VALUE_TUPLE);
    auto tv_expr = reinterpret_cast<expression::TupleValueExpression *>(col);
    auto bound_ids = tv_expr->GetBoundOid();
    root_group->AddStats(tv_expr->GetColFullName(),
                         std::make_shared<ColumnStats>(
                             std::get<0>(bound_ids), std::get<1>(bound_ids),
                             std::get<2>(bound_ids), tv_expr->GetColFullName(),
                             false, 0, 0.f, false, std::vector<double>{},
                             std::vector<double>{}, std::vector<double>{}));
  }
}

void StatsCalculator::Visit(const LogicalInnerJoin *op) {
  // Check if there's join condition
  PELOTON_ASSERT(gexpr_->GetChildrenGroupsSize() == 2);
  auto left_child_group = memo_->GetGroupByID(gexpr_->GetChildGroupId(0));
  auto right_child_group = memo_->GetGroupByID(gexpr_->GetChildGroupId(1));
  auto root_group = memo_->GetGroupByID(gexpr_->GetGroupID());
  // Calculate output num rows first
  if (root_group->GetNumRows() == -1) {
    size_t curr_rows =
        left_child_group->GetNumRows() * right_child_group->GetNumRows();
    for (auto &annotated_expr : op->join_predicates) {
      // See if there are join conditions
      if (annotated_expr.expr->GetExpressionType() ==
              ExpressionType::COMPARE_EQUAL &&
          annotated_expr.expr->GetChild(0)->GetExpressionType() ==
              ExpressionType::VALUE_TUPLE &&
          annotated_expr.expr->GetChild(1)->GetExpressionType() ==
              ExpressionType::VALUE_TUPLE) {
        auto left_child =
            reinterpret_cast<const expression::TupleValueExpression *>(
                annotated_expr.expr->GetChild(0));
        auto right_child =
            reinterpret_cast<const expression::TupleValueExpression *>(
                annotated_expr.expr->GetChild(1));
        if ((left_child_group->HasColumnStats(left_child->GetColFullName()) &&
             right_child_group->HasColumnStats(
                 right_child->GetColFullName())) ||
            (left_child_group->HasColumnStats(right_child->GetColFullName()) &&
             right_child_group->HasColumnStats(left_child->GetColFullName()))) {
          curr_rows /= std::max(std::max(left_child_group->GetNumRows(),
                                         right_child_group->GetNumRows()),
                                1);
        }
      }
    }
    root_group->SetNumRows(curr_rows);
  }
  size_t num_rows = root_group->GetNumRows();
  for (auto &col : required_cols_) {
    PELOTON_ASSERT(col->GetExpressionType() == ExpressionType::VALUE_TUPLE);
    auto tv_expr = reinterpret_cast<expression::TupleValueExpression *>(col);
    std::shared_ptr<ColumnStats> column_stats;
    // Make a copy from the child stats
    if (left_child_group->HasColumnStats(tv_expr->GetColFullName())) {
      column_stats = std::make_shared<ColumnStats>(
          *left_child_group->GetStats(tv_expr->GetColFullName()));
    } else {
      PELOTON_ASSERT(right_child_group->HasColumnStats(tv_expr->GetColFullName()));
      column_stats = std::make_shared<ColumnStats>(
          *right_child_group->GetStats(tv_expr->GetColFullName()));
    }
    // Reset num_rows
    column_stats->num_rows = num_rows;
    root_group->AddStats(tv_expr->GetColFullName(), column_stats);
  }
  // TODO(boweic): calculate stats based on predicates other than join
  // conditions
}
void StatsCalculator::Visit(UNUSED_ATTRIBUTE const LogicalLeftJoin *op) {}
void StatsCalculator::Visit(UNUSED_ATTRIBUTE const LogicalRightJoin *op) {}
void StatsCalculator::Visit(UNUSED_ATTRIBUTE const LogicalOuterJoin *op) {}
void StatsCalculator::Visit(UNUSED_ATTRIBUTE const LogicalSemiJoin *op) {}
void StatsCalculator::Visit(const LogicalAggregateAndGroupBy *) {
  // TODO(boweic): For now we just pass the stats needed without any
  // computation,
  // We need to implement stats computation for aggregation
  PELOTON_ASSERT(gexpr_->GetChildrenGroupsSize() == 1);
  // First, set num rows
  memo_->GetGroupByID(gexpr_->GetGroupID())
      ->SetNumRows(
          memo_->GetGroupByID(gexpr_->GetChildGroupId(0))->GetNumRows());
  for (auto &col : required_cols_) {
    PELOTON_ASSERT(col->GetExpressionType() == ExpressionType::VALUE_TUPLE);
    auto column_name = reinterpret_cast<expression::TupleValueExpression *>(col)
                           ->GetColFullName();
    memo_->GetGroupByID(gexpr_->GetGroupID())
        ->AddStats(column_name, memo_->GetGroupByID(gexpr_->GetChildGroupId(0))
                                    ->GetStats(column_name));
  }
}

void StatsCalculator::Visit(const LogicalLimit *op) {
  PELOTON_ASSERT(gexpr_->GetChildrenGroupsSize() == 1);
  auto group = memo_->GetGroupByID(gexpr_->GetGroupID());
  group->SetNumRows(std::min(
      (size_t)op->limit,
      (size_t)memo_->GetGroupByID(gexpr_->GetChildGroupId(0))->GetNumRows()));
  for (auto &col : required_cols_) {
    PELOTON_ASSERT(col->GetExpressionType() == ExpressionType::VALUE_TUPLE);
    auto column_name = reinterpret_cast<expression::TupleValueExpression *>(col)
                           ->GetColFullName();
    std::shared_ptr<ColumnStats> column_stats = std::make_shared<ColumnStats>(
        *memo_->GetGroupByID(gexpr_->GetChildGroupId(0))
             ->GetStats(column_name));
    column_stats->num_rows = group->GetNumRows();
    group->AddStats(column_name, column_stats);
  }
}

void StatsCalculator::Visit(const LogicalDistinct *) {
  // TODO calculate stats for distinct
  memo_->GetGroupByID(gexpr_->GetGroupID())
      ->SetNumRows(
          memo_->GetGroupByID(gexpr_->GetChildGroupId(0))->GetNumRows());
  PELOTON_ASSERT(gexpr_->GetChildrenGroupsSize() == 1);
  for (auto &col : required_cols_) {
    PELOTON_ASSERT(col->GetExpressionType() == ExpressionType::VALUE_TUPLE);
    auto column_name = reinterpret_cast<expression::TupleValueExpression *>(col)
                           ->GetColFullName();
    memo_->GetGroupByID(gexpr_->GetGroupID())
        ->AddStats(column_name, memo_->GetGroupByID(gexpr_->GetChildGroupId(0))
                                    ->GetStats(column_name));
  }
}

void StatsCalculator::AddBaseTableStats(
    expression::AbstractExpression *col,
    std::shared_ptr<TableStats> table_stats,
    std::unordered_map<std::string, std::shared_ptr<ColumnStats>> &stats,
    bool copy) {
  PELOTON_ASSERT(col->GetExpressionType() == ExpressionType::VALUE_TUPLE);
  auto tv_expr = reinterpret_cast<expression::TupleValueExpression *>(col);
  auto bound_ids = tv_expr->GetBoundOid();
  if (table_stats->GetColumnCount() == 0) {
    // We do not have stats for the table yet, use default value
    stats[tv_expr->GetColFullName()] = std::make_shared<ColumnStats>(
        std::get<0>(bound_ids), std::get<1>(bound_ids), std::get<2>(bound_ids),
        tv_expr->GetColFullName(), false, 0, 0.f, false, std::vector<double>{},
        std::vector<double>{}, std::vector<double>{});
  } else {
    stats[tv_expr->GetColFullName()] =
        copy ? std::make_shared<ColumnStats>(
                   *table_stats->GetColumnStats(std::get<2>(bound_ids)))
             : table_stats->GetColumnStats(std::get<2>(bound_ids));
  }
}

void StatsCalculator::UpdateStatsForFilter(
    size_t num_rows,
    std::unordered_map<std::string, std::shared_ptr<ColumnStats>>
        &predicate_stats,
    const std::vector<AnnotatedExpression> &predicates) {
  // First, construct the table stats as the interface needed it to compute
  // selectivity
  // TODO(boweic): We may want to modify the interface of selectivity
  // computation to not use table_stats
  std::vector<std::shared_ptr<ColumnStats>> predicate_stats_vec;
  for (auto &column_name_stats_pair : predicate_stats) {
    predicate_stats_vec.push_back(column_name_stats_pair.second);
  }
  std::shared_ptr<TableStats> predicate_table_stats =
      std::make_shared<TableStats>(predicate_stats_vec);
  double selectivity = 1.f;
  for (auto &annotated_expr : predicates) {
    // Loop over conjunction exprs
    selectivity *= CalculateSelectivityForPredicate(predicate_table_stats,
                                                    annotated_expr.expr.get());
  }
  // Update selectivity
  memo_->GetGroupByID(gexpr_->GetGroupID())->SetNumRows(num_rows * selectivity);
}

// Calculate the selectivity given the predicate and the stats of columns in the
// predicate
double StatsCalculator::CalculateSelectivityForPredicate(
    const std::shared_ptr<TableStats> predicate_table_stats,
    const expression::AbstractExpression *expr) {
  double selectivity = 1.f;
  if (predicate_table_stats->GetColumnCount() == 0 ||
      predicate_table_stats->GetColumnStats(0)->num_rows == 0) {
    return selectivity;
  }
  // Base case : Column Op Val
  if ((expr->GetChild(0)->GetExpressionType() == ExpressionType::VALUE_TUPLE &&
       (expr->GetChild(1)->GetExpressionType() ==
            ExpressionType::VALUE_CONSTANT ||
        expr->GetChild(1)->GetExpressionType() ==
            ExpressionType::VALUE_PARAMETER)) ||
      (expr->GetChild(1)->GetExpressionType() == ExpressionType::VALUE_TUPLE &&
       (expr->GetChild(0)->GetExpressionType() ==
            ExpressionType::VALUE_CONSTANT ||
        expr->GetChild(0)->GetExpressionType() ==
            ExpressionType::VALUE_PARAMETER))) {
    int right_index =
        expr->GetChild(0)->GetExpressionType() == ExpressionType::VALUE_TUPLE
            ? 1
            : 0;

    auto left_expr = expr->GetChild(1 - right_index);
    PELOTON_ASSERT(left_expr->GetExpressionType() == ExpressionType::VALUE_TUPLE);
    auto col_name =
        reinterpret_cast<const expression::TupleValueExpression *>(left_expr)
            ->GetColFullName();

    auto expr_type = expr->GetExpressionType();
    if (right_index == 0) {
      switch (expr_type) {
        case ExpressionType::COMPARE_LESSTHANOREQUALTO:
          expr_type = ExpressionType::COMPARE_GREATERTHANOREQUALTO;
          break;
        case ExpressionType::COMPARE_LESSTHAN:
          expr_type = ExpressionType::COMPARE_GREATERTHAN;
          break;
        case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
          expr_type = ExpressionType::COMPARE_LESSTHANOREQUALTO;
          break;
        case ExpressionType::COMPARE_GREATERTHAN:
          expr_type = ExpressionType::COMPARE_LESSTHAN;
          break;
        default:
          break;
      }
    }

    type::Value value;
    if (expr->GetChild(right_index)->GetExpressionType() ==
        ExpressionType::VALUE_CONSTANT) {
      value = reinterpret_cast<expression::ConstantValueExpression *>(
                  expr->GetModifiableChild(right_index))
                  ->GetValue();
    } else {
      value = type::ValueFactory::GetParameterOffsetValue(
                  reinterpret_cast<expression::ParameterValueExpression *>(
                      expr->GetModifiableChild(right_index))
                      ->GetValueIdx())
                  .Copy();
    }
    ValueCondition condition(col_name, expr_type, value);
    selectivity =
        Selectivity::ComputeSelectivity(predicate_table_stats, condition);
  } else if (expr->GetExpressionType() == ExpressionType::CONJUNCTION_AND ||
             expr->GetExpressionType() == ExpressionType::CONJUNCTION_OR) {
    double left_selectivity = CalculateSelectivityForPredicate(
        predicate_table_stats, expr->GetChild(0));
    double right_selectivity = CalculateSelectivityForPredicate(
        predicate_table_stats, expr->GetChild(1));
    if (expr->GetExpressionType() == ExpressionType::CONJUNCTION_AND) {
      selectivity = left_selectivity * right_selectivity;
    } else {
      selectivity = left_selectivity + right_selectivity -
                    left_selectivity * right_selectivity;
    }
  }
  return selectivity;
}

}  // namespace optimizer
}  // namespace peloton


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

namespace ThomsonReuters.Languages.TypesLanguage
{
    public interface INamespaceMember
    {
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

API for integration with debuggers of custom languages/frameworks

  {@link com.intellij.xdebugger.XDebugProcess} is the main class which need to be extended to support debugging

  Implement {@link com.intellij.xdebugger.breakpoints.XLineBreakpointType} to support new type of breakpoints

  Use {@link com.intellij.xdebugger.settings.XDebuggerSettings} to provide settings


text:
<link rel="icon" href="favicon.ico" type="image/x-icon" >
<title>Patrick's Lab
</title>
<link rel="stylesheet" href="css2.css" >

Cars

home

here is a couple of pictures
of my favorite car, the peugoet onyx. doors open and closed.

the Terrafugia TF-X... a flying car! my favorite!

here is an earlier Terrafugia that you can buy if you are a multimillionare.it's wings are folding out.

In Melbourne, I saw this Ford Escort MkI!

I also saw a Ferrari F430 which sounded beautiful!


text:
package com.gitblit.plugin.flowdock;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.gitblit.manager.IUserManager;
import com.gitblit.models.TicketModel;
import com.gitblit.models.TicketModel.Change;
import com.gitblit.models.TicketModel.Field;
import com.gitblit.models.UserModel;
import com.gitblit.servlet.GitblitContext;
import com.gitblit.utils.StringUtils;
import com.google.gson.annotations.SerializedName;

/**
 * Pretend to be a JIRA issue.
 *
 * @author James Moger
 *
 */
public class JiraPayload extends Payload implements Serializable {

	private static final long serialVersionUID = 1L;

	@SerializedName("issue_key")
	String id;

	@SerializedName("issue_summary")
	String title;

	@SerializedName("issue_description")
	String description;

	@SerializedName("issue_status")
	String status;

	@SerializedName("issue_resolution")
	String resolution;

	@SerializedName("issue_type")
	String type;

	@SerializedName("project_name")
	String project;

	@SerializedName("issue_votes")
	String votes;

	@SerializedName("issue_reporter_name")
	String createdByName;

	@SerializedName("issue_reporter_email")
	String createdByEmail;

	@SerializedName("issue_assignee_name")
	String responsibleName;

	@SerializedName("issue_assignee_email")
	String responsibleEmail;

	@SerializedName("user_name")
	String updaterName;

	@SerializedName("user_email")
	String updaterEmail;

	@SerializedName("event_type")
	String updateType;

	@SerializedName("comment_body")
	String comment;

	@SerializedName("issue_url")
	String url;

	@SerializedName("project_url")
	String projectUrl;

	@SerializedName("issue_changelog")
	List<Changelog> changes;

	@Override
	public String getEndPoint(String token) {
		return String.format("https://api.flowdock.com/v1/jira/%s", token);
	}

	@Override
	public boolean postForm() {
		return false;
	}

	public JiraPayload ticket(TicketModel ticket) {
		id = String.valueOf(ticket.number);
		title = ticket.title;
		description = ticket.body;
		status = ticket.status.name();
		if (ticket.isClosed()) {
			resolution = ticket.status.name();
		}
		type = ticket.type.name();
		project = StringUtils.stripDotGit(ticket.repository);
		votes = String.valueOf(ticket.getVoters().size());

		IUserManager userManager = GitblitContext.getManager(IUserManager.class);

		UserModel createdBy = userManager.getUserModel(ticket.createdBy);
		if (createdBy != null) {
			createdByName = createdBy.getDisplayName();
			createdByEmail = createdBy.emailAddress;
		} else {
			createdByName = ticket.createdBy;
		}

		if (!StringUtils.isEmpty(ticket.responsible)) {
			UserModel responsible = userManager.getUserModel(ticket.responsible);
			if (responsible != null) {
				responsibleName = responsible.getDisplayName();
				responsibleEmail = responsible.emailAddress;
			} else {
				responsibleName = ticket.responsible;
			}
		}

		Change lastChange = ticket.changes.get(ticket.changes.size() - 1);
		UserModel changedBy = userManager.getUserModel(lastChange.author);
		updaterName = changedBy.getDisplayName();
		updaterEmail = changedBy.emailAddress;

		if (lastChange.hasComment()) {
			comment = lastChange.comment.text;
		}

		if (lastChange.hasFieldChanges()) {
			changes = new ArrayList<Changelog>();
			for (Field field :lastChange.fields.keySet()) {
				Changelog cl = new Changelog();
				cl.field = field.name();
				cl.newValue = lastChange.getField(field).toString();
				changes.add(cl);
			}
		}

		// set the event type
		if (ticket.changes.size() == 1) {
			// new ticket
			updateType = "create";
		} else if (lastChange.hasComment()) {
			// comment on ticket
			updateType = "comment";
		} else if (lastChange.hasField(Field.responsible) && lastChange.getField(Field.responsible) != null) {
			// assign ticket
			updateType = "assign";
		} else if (lastChange.isStatusChange()) {
			// status change
			switch (lastChange.getStatus()) {
			case Open:
				updateType = "reopen";
				break;
			case Resolved:
				updateType = "resolve";
				break;
			default:
				updateType = "close";
				break;
			}
		} else {
			updateType = "update";
		}

		return this;
	}

	public JiraPayload tags(List<String> tags) {
		setTags(tags);
		return this;
	}

	public JiraPayload ticketUrl(String url) {
		this.url = url;
		return this;
	}

	public JiraPayload projectUrl(String url) {
		this.projectUrl = url;
		return this;
	}

	public JiraPayload description(String description) {
		this.description = description;
		return this;
	}

	public JiraPayload comment(String comment) {
		this.comment = comment;
		return this;
	}

	public static class Changelog implements Serializable {

		private static final long serialVersionUID = 1L;

		String field;

		@SerializedName("old_value")
		String oldValue;

		@SerializedName("new_value")
		String newValue;
	}
}


text:
ACCEPTED

#### According to
Integrated Taxonomic Information System

#### Published in
Ann. Sci. Agron. Franç. Étrangère sér. 3, 6(2):190. 1911

#### Original name
null

### Remarks
null


text:
#include "squid.h"
#if HAVE_ASSERT_H
#include <assert.h>
#endif

#include "MemPool.h"
#include "MemPoolChunked.h"
#include "MemPoolMalloc.h"

#define FLUSH_LIMIT 1000	/* Flush memPool counters to memMeters after flush limit calls */

#if HAVE_STRING_H
#include <string.h>
#endif

/*
 * XXX This is a boundary violation between lib and src.. would be good
 * if it could be solved otherwise, but left for now.
 */
extern time_t squid_curtime;

/* local data */
static MemPoolMeter TheMeter;
static MemPoolIterator Iterator;

static int Pool_id_counter = 0;

MemPools &
MemPools::GetInstance()
{
    /* Must use this idiom, as we can be double-initialised
     * if we are called during static initialisations.
     */
    if (!Instance)
        Instance = new MemPools;
    return *Instance;
}

MemPools * MemPools::Instance = NULL;

MemPoolIterator *
memPoolIterate(void)
{
    Iterator.pool = MemPools::GetInstance().pools;
    return &Iterator;
}

void
memPoolIterateDone(MemPoolIterator ** iter)
{
    assert(iter != NULL);
    Iterator.pool = NULL;
    *iter = NULL;
}

MemImplementingAllocator *
memPoolIterateNext(MemPoolIterator * iter)
{
    MemImplementingAllocator *pool;
    assert(iter != NULL);

    pool = iter->pool;
    if (!pool)
        return NULL;

    iter->pool = pool->next;
    return pool;
}

void
MemPools::setIdleLimit(ssize_t new_idle_limit)
{
    mem_idle_limit = new_idle_limit;
}

ssize_t
MemPools::idleLimit() const
{
    return mem_idle_limit;
}

/* Change the default calue of defaultIsChunked to override
 * all pools - including those used before main() starts where
 * MemPools::GetInstance().setDefaultPoolChunking() can be called.
 */
MemPools::MemPools() : pools(NULL), mem_idle_limit(2 * MB),
        poolCount (0), defaultIsChunked (USE_CHUNKEDMEMPOOLS && !RUNNING_ON_VALGRIND)
{
    char *cfg = getenv("MEMPOOLS");
    if (cfg)
        defaultIsChunked = atoi(cfg);
}

MemImplementingAllocator *
MemPools::create(const char *label, size_t obj_size)
{
    ++poolCount;
    if (defaultIsChunked)
        return new MemPoolChunked (label, obj_size);
    else
        return new MemPoolMalloc (label, obj_size);
}

void
MemPools::setDefaultPoolChunking(bool const &aBool)
{
    defaultIsChunked = aBool;
}

char const *
MemAllocator::objectType() const
{
    return label;
}

int
MemAllocator::inUseCount()
{
    return getInUseCount();
}

void
MemImplementingAllocator::flushMeters()
{
    size_t calls;

    calls = free_calls;
    if (calls) {
        meter.gb_freed.count += calls;
        free_calls = 0;
    }
    calls = alloc_calls;
    if (calls) {
        meter.gb_allocated.count += calls;
        alloc_calls = 0;
    }
    calls = saved_calls;
    if (calls) {
        meter.gb_saved.count += calls;
        saved_calls = 0;
    }
}

void
MemImplementingAllocator::flushMetersFull()
{
    flushMeters();
    getMeter().gb_allocated.bytes = getMeter().gb_allocated.count * obj_size;
    getMeter().gb_saved.bytes = getMeter().gb_saved.count * obj_size;
    getMeter().gb_freed.bytes = getMeter().gb_freed.count * obj_size;
}

void
MemPoolMeter::flush()
{
    alloc.level = 0;
    inuse.level = 0;
    idle.level = 0;
    gb_allocated.count = 0;
    gb_allocated.bytes = 0;
    gb_oallocated.count = 0;
    gb_oallocated.bytes = 0;
    gb_saved.count = 0;
    gb_saved.bytes = 0;
    gb_freed.count = 0;
    gb_freed.bytes = 0;
}

MemPoolMeter::MemPoolMeter()
{
    flush();
}

/*
 * Updates all pool counters, and recreates TheMeter totals from all pools
 */
void
MemPools::flushMeters()
{
    MemImplementingAllocator *pool;
    MemPoolIterator *iter;

    TheMeter.flush();

    iter = memPoolIterate();
    while ((pool = memPoolIterateNext(iter))) {
        pool->flushMetersFull();
        memMeterAdd(TheMeter.alloc, pool->getMeter().alloc.level * pool->obj_size);
        memMeterAdd(TheMeter.inuse, pool->getMeter().inuse.level * pool->obj_size);
        memMeterAdd(TheMeter.idle, pool->getMeter().idle.level * pool->obj_size);
        TheMeter.gb_allocated.count += pool->getMeter().gb_allocated.count;
        TheMeter.gb_saved.count += pool->getMeter().gb_saved.count;
        TheMeter.gb_freed.count += pool->getMeter().gb_freed.count;
        TheMeter.gb_allocated.bytes += pool->getMeter().gb_allocated.bytes;
        TheMeter.gb_saved.bytes += pool->getMeter().gb_saved.bytes;
        TheMeter.gb_freed.bytes += pool->getMeter().gb_freed.bytes;
    }
    memPoolIterateDone(&iter);
}

void *
MemImplementingAllocator::alloc()
{
    if (++alloc_calls == FLUSH_LIMIT)
        flushMeters();

    return allocate();
}

void
MemImplementingAllocator::freeOne(void *obj)
{
    assert(obj != NULL);
    (void) VALGRIND_CHECK_MEM_IS_ADDRESSABLE(obj, obj_size);
    deallocate(obj, MemPools::GetInstance().mem_idle_limit == 0);
    ++free_calls;
}

/*
 * Returns all cached frees to their home chunks
 * If chunks unreferenced age is over, destroys Idle chunk
 * Flushes meters for a pool
 * If pool is not specified, iterates through all pools.
 * When used for all pools, if new_idle_limit is above -1, new
 * idle memory limit is set before Cleanup. This allows to shrink
 * memPool memory usage to specified minimum.
 */
void
MemPools::clean(time_t maxage)
{
    flushMeters();
    if (mem_idle_limit < 0) // no limit to enforce
        return;

    int shift = 1;
    if (TheMeter.idle.level > mem_idle_limit)
        maxage = shift = 0;

    MemImplementingAllocator *pool;
    MemPoolIterator *iter;
    iter = memPoolIterate();
    while ((pool = memPoolIterateNext(iter)))
        if (pool->idleTrigger(shift))
            pool->clean(maxage);
    memPoolIterateDone(&iter);
}

/* Persistent Pool stats. for GlobalStats accumulation */
static MemPoolStats pp_stats;

/*
 * Totals statistics is returned
 */
int
memPoolGetGlobalStats(MemPoolGlobalStats * stats)
{
    int pools_inuse = 0;
    MemAllocator *pool;
    MemPoolIterator *iter;

    memset(stats, 0, sizeof(MemPoolGlobalStats));
    memset(&pp_stats, 0, sizeof(MemPoolStats));

    MemPools::GetInstance().flushMeters(); /* recreate TheMeter */

    /* gather all stats for Totals */
    iter = memPoolIterate();
    while ((pool = memPoolIterateNext(iter))) {
        if (pool->getStats(&pp_stats, 1) > 0)
            ++pools_inuse;
    }
    memPoolIterateDone(&iter);

    stats->TheMeter = &TheMeter;

    stats->tot_pools_alloc = MemPools::GetInstance().poolCount;
    stats->tot_pools_inuse = pools_inuse;
    stats->tot_pools_mempid = Pool_id_counter;

    stats->tot_chunks_alloc = pp_stats.chunks_alloc;
    stats->tot_chunks_inuse = pp_stats.chunks_inuse;
    stats->tot_chunks_partial = pp_stats.chunks_partial;
    stats->tot_chunks_free = pp_stats.chunks_free;
    stats->tot_items_alloc = pp_stats.items_alloc;
    stats->tot_items_inuse = pp_stats.items_inuse;
    stats->tot_items_idle = pp_stats.items_idle;

    stats->tot_overhead += pp_stats.overhead + MemPools::GetInstance().poolCount * sizeof(MemAllocator *);
    stats->mem_idle_limit = MemPools::GetInstance().mem_idle_limit;

    return pools_inuse;
}

MemAllocator::MemAllocator(char const *aLabel) : doZeroOnPush(true), label(aLabel)
{
}

size_t MemAllocator::RoundedSize(size_t s)
{
    return ((s + sizeof(void*) - 1) / sizeof(void*)) * sizeof(void*);
}

int
memPoolInUseCount(MemAllocator * pool)
{
    return pool->inUseCount();
}

int
memPoolsTotalAllocated(void)
{
    MemPoolGlobalStats stats;
    memPoolGetGlobalStats(&stats);
    return stats.TheMeter->alloc.level;
}

void *
MemAllocatorProxy::alloc()
{
    return getAllocator()->alloc();
}

void
MemAllocatorProxy::freeOne(void *address)
{
    getAllocator()->freeOne(address);
    /* TODO: check for empty, and if so, if the default type has altered,
     * switch
     */
}

MemAllocator *
MemAllocatorProxy::getAllocator() const
{
    if (!theAllocator)
        theAllocator = MemPools::GetInstance().create(objectType(), size);
    return theAllocator;
}

int
MemAllocatorProxy::inUseCount() const
{
    if (!theAllocator)
        return 0;
    else
        return memPoolInUseCount(theAllocator);
}

size_t
MemAllocatorProxy::objectSize() const
{
    return size;
}

char const *
MemAllocatorProxy::objectType() const
{
    return label;
}

MemPoolMeter const &
MemAllocatorProxy::getMeter() const
{
    return getAllocator()->getMeter();
}

int
MemAllocatorProxy::getStats(MemPoolStats * stats)
{
    return getAllocator()->getStats(stats);
}

MemImplementingAllocator::MemImplementingAllocator(char const *aLabel, size_t aSize) : MemAllocator(aLabel),
        next(NULL),
        alloc_calls(0),
        free_calls(0),
        saved_calls(0),
        obj_size(RoundedSize(aSize))
{
    memPID = ++Pool_id_counter;

    MemImplementingAllocator *last_pool;

    assert(aLabel != NULL && aSize);
    /* Append as Last */
    for (last_pool = MemPools::GetInstance().pools; last_pool && last_pool->next;)
        last_pool = last_pool->next;
    if (last_pool)
        last_pool->next = this;
    else
        MemPools::GetInstance().pools = this;
}

MemImplementingAllocator::~MemImplementingAllocator()
{
    MemImplementingAllocator *find_pool, *prev_pool;

    /* Abort if the associated pool doesn't exist */
    assert(MemPools::GetInstance().pools != NULL );

    /* Pool clean, remove it from List and free */
    for (find_pool = MemPools::GetInstance().pools, prev_pool = NULL; (find_pool && this != find_pool); find_pool = find_pool->next)
        prev_pool = find_pool;

    /* make sure that we found the pool to destroy */
    assert(find_pool != NULL);

    if (prev_pool)
        prev_pool->next = next;
    else
        MemPools::GetInstance().pools = next;
    --MemPools::GetInstance().poolCount;
}

void
MemAllocator::zeroOnPush(bool doIt)
{
    doZeroOnPush = doIt;
}

MemPoolMeter const &
MemImplementingAllocator::getMeter() const
{
    return meter;
}

MemPoolMeter &
MemImplementingAllocator::getMeter()
{
    return meter;
}

size_t
MemImplementingAllocator::objectSize() const
{
    return obj_size;
}


text:
"""usage: git commit [options] [--] [<filepattern>...]

    -h, --help
    -q, --quiet           suppress summary after successful commit
    -v, --verbose         show diff in commit message template

Commit message options
    -F, --file <file>     read message from file
    --author <author>     override author for commit
    --date <date>         override date for commit
    -m, --message <message>
                          commit message
    -c, --reedit-message <commit>
                          reuse and edit message from specified commit
    -C, --reuse-message <commit>
                          reuse message from specified commit
    --fixup <commit>      use autosquash formatted message to fixup specified commit
    --squash <commit>     use autosquash formatted message to squash specified commit
    --reset-author        the commit is authored by me now
                          (used with -C-c/--amend)
    -s, --signoff         add Signed-off-by:
    -t, --template <file>
                          use specified template file
    -e, --edit            force edit of commit
    --cleanup <default>   how to strip spaces and #comments from message
    --status              include status in commit message template

Commit contents options
    -a, --all             commit all changed files
    -i, --include         add specified files to index for commit
    --interactive         interactively add files
    -o, --only            commit only specified files
    -n, --no-verify       bypass pre-commit hook
    --dry-run             show what would be committed
    --short               show status concisely
    --branch              show branch information
    --porcelain           machine-readable output
    -z, --null            terminate entries with NUL
    --amend               amend previous commit
    --no-post-rewrite     bypass post-rewrite hook
    -u, --untracked-files=<mode>
                          show untracked files, optional modes: all, normal, no.
                          [default: all]

"""
from docopt import docopt

if __name__ == '__main__':
    print(docopt(__doc__))


text:
package org.openqa.selenium.chrome;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;

import org.junit.Test;

import java.io.File;
import java.time.Duration;

public class ChromeDriverServiceTest {

  @Test
  public void builderPassesTimeoutToDriverService() {
    File exe = new File("someFile");
    Duration defaultTimeout = Duration.ofSeconds(20);
    Duration customTimeout = Duration.ofSeconds(60);

    ChromeDriverService.Builder builderMock = spy(ChromeDriverService.Builder.class);
    doReturn(exe).when(builderMock).findDefaultExecutable();
    builderMock.build();

    verify(builderMock).createDriverService(any(), anyInt(), eq(defaultTimeout), any(), any());

    builderMock.withTimeout(customTimeout);
    builderMock.build();
    verify(builderMock).createDriverService(any(), anyInt(), eq(customTimeout), any(), any());
  }
}


text:
'use strict';

angular.module('Cases')

.controller('CasesController',
    ['$scope', '$rootScope', '$location', 'CasesService',
    function ($scope, $rootScope, $location, CasesService) {
            $scope.dataLoading = true;

            CasesService.GetContainers(function (response) {

                if (response.success) {
                    $scope.containers = response.data;
                    $location.path('/cases');
                } else {
                    $scope.error = response.message;
                    $scope.dataLoading = false;
                }
            });
    }]);


text:
#if	!defined(lint) && !defined(DOS)
static char rcsid[] = "$Id: fileio.c 769 2007-10-24 00:15:40Z hubert@u.washington.edu $";
#endif

/*
 * The routines in this file read and write ASCII files from the disk. All of
 * the knowledge about files are here. A better message writing scheme should
 * be used.
 */
#include	"headers.h"
#include	"../pith/charconv/filesys.h"

#if	defined(bsd) || defined(lnx)
extern int errno;
#endif

FIOINFO	g_pico_fio;

/*
 * Open a file for reading.
 */
int
ffropen(char *fn)
{
    int status;

    if ((status = fexist(g_pico_fio.name = fn, "r", (off_t *)NULL)) == FIOSUC){
	g_pico_fio.flags = FIOINFO_READ;
	if((g_pico_fio.fp = our_fopen(g_pico_fio.name, "r")) == NULL)
	  status = FIOFNF;
    }

    return (status);
}

/*
 * Write a line to the already opened file. The "buf" points to the buffer,
 * and the "nbuf" is its length, less the free newline. Return the status.
 * Check only at the newline.
 */
int
ffputline(CELL buf[], int nbuf)
{
    register int    i;
    EML eml;

    for(i = 0; i < nbuf; ++i)
       if(write_a_wide_char((UCS) buf[i].c, g_pico_fio.fp) == EOF)
	 break;

   if(i == nbuf)
     write_a_wide_char((UCS) '\n', g_pico_fio.fp);

    if(ferror(g_pico_fio.fp)){
	eml.s = errstr(errno);
        emlwrite("\007Write error: %s", &eml);
	sleep(5);
        return FIOERR;
    }

    return FIOSUC;
}

/*
 * Read a line from a file, and store the bytes in the supplied buffer. The
 * "nbuf" is the length of the buffer. Complain about long lines and lines
 * at the end of the file that don't have a newline present. Check for I/O
 * errors too. Return status.
 *
 * Translate the line from the user's locale charset to UCS-4.
 */
int
ffgetline(UCS buf[], size_t nbuf, size_t *charsreturned, int msg)
{
    size_t i;
    UCS    ucs;

    if(charsreturned)
      *charsreturned = 0;

    i = 0;

    while((ucs = read_a_wide_char(g_pico_fio.fp, input_cs)) != CCONV_EOF && ucs != '\n'){
	/*
	 * Don't blat the CR should the newline be CRLF and we're
	 * running on a unix system.  NOTE: this takes care of itself
	 * under DOS since the non-binary open turns newlines into '\n'.
	 */
	if(ucs == '\r'){
	    if((ucs = read_a_wide_char(g_pico_fio.fp, input_cs)) == CCONV_EOF || ucs == '\n')
	      break;

	    if(i < nbuf-2)		/* Bare CR. Insert it and go on... */
	      buf[i++] = '\r';		/* else, we're up a creek */
	}

        if(i >= nbuf-2){
	    buf[nbuf - 2] = ucs;	/* store last char read */
	    buf[nbuf - 1] = '\0';	/* and terminate it */
	    if(charsreturned)
	      *charsreturned = nbuf - 1;

	    if(msg)
	      emlwrite("File has long line", NULL);

	    return FIOLNG;
        }

        buf[i++] = ucs;
    }

    if(ucs == CCONV_EOF){
        if(ferror(g_pico_fio.fp)){
            emlwrite("File read error", NULL);
	    if(charsreturned)
	      *charsreturned = i;

	    return FIOERR;
        }

        if(i != 0)
	  emlwrite("File doesn't end with newline.  Adding one.", NULL);
	else{
	    if(charsreturned)
	      *charsreturned = i;
	    return FIOEOF;
	}
    }

    buf[i] = '\0';

    if(charsreturned)
      *charsreturned = i;

    return FIOSUC;
}


text:
<?php

namespace Cartalyst\Sentinel\Laravel\Facades;

use Illuminate\Support\Facades\Facade;

class Activation extends Facade
{
    /**
     * {@inheritDoc}
     */
    protected static function getFacadeAccessor()
    {
        return 'sentinel.activations';
    }
}


text:
import _ from 'lodash'

import sortByPoints from './1_sortByPoints'
import getMaxPoints from './2_getMaxPoints'
import makeEachGroupEven from './3_makeEachGroupEven'
import createRooms from './4_createRooms'
import assignWinner from './5_assignWinner'
import convertRoomsToTeamArray from './6_convertRoomsToTeamArray'
import convertRoomTeamsArrayToObject from './7_convertRoomTeamsArrayToObject'

export default (
  theoreticalTeams,
  higherPointWin
) => {
  let teamsSortedByPoints = sortByPoints(
    theoreticalTeams
  )

  const maxPoints = getMaxPoints(
    theoreticalTeams
  )

  makeEachGroupEven(
    teamsSortedByPoints,
    maxPoints
  )

  let theoreticalRooms = createRooms(
    teamsSortedByPoints,
    maxPoints
  )

  const newRoomsArr = convertRoomTeamsArrayToObject(
    _.cloneDeep(theoreticalRooms)
  )

  assignWinner(
    theoreticalRooms,
    higherPointWin
  )

  let newTeamsArr = convertRoomsToTeamArray(
    theoreticalRooms
  )

  newTeamsArr.sort((a, b) => {
    if (a.score < b.score) return 1
    if (a.score > b.score) return -1
    return 0
  })

  return {
    teams: newTeamsArr,
    rooms: newRoomsArr
  }
}


text:
import template from './main.template.html';
import controller from './main.controller';
import './main.css';

export default {
    template,
    controller,
    controllerAs: 'ctrl'
};


text:
AE Quotes Importer
==================

Parse and import daily stock quotes from Agência Estado's .csv files into a database (tested with MySQL).

Some companies listed on Bovespa, like Bradesco and Petrobrás, provide access to adjusted historical quotes in the form of .csv files. These files can be downloaded in their Investor Relations sites.

**DB Setup**

Edit the database connection info on `db/config.yml`.

You can either use your existing tables (as long as they have the correct schema) or create them with:

    rake db:create
    rake db:migrate

**Testing:**

    rake db:test:prepare
    rake test:rspec

**Creating stocks**

    ./bin/ae_quotes_importer create_stock STOCK_CODE [STOCK_NAME [STOCKS_TABLE]]

The default table name is `stocks`. If you don't provide the stock name, the code will be used.

Some examples:

    ./bin/ae_quotes_importer create_stock PETR4
    ./bin/ae_quotes_importer create_stock BBDC4 "BCO BRADESCO" my_stocks_table

**Importing files**

    ./bin/ae_quotes_importer import_quotes STOCK_CODE CSV_FILE_PATH [QUOTES_TABLE]

The default table name is `ae_quotes`.

Some examples:

    ./bin/ae_quotes_importer import_quotes PETR4 petr4.csv
    ./bin/ae_quotes_importer import_quotes BBDC4 ~/stocks/bradesco.csv my_quotes_table

**License:**

The MIT License (MIT)

Copyright (c) 2013 Vinicius Pinto

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
import {
  TestBed,
  inject,
  async,
  ComponentFixture,
} from '@angular/core/testing';
import {APP_BASE_HREF} from '@angular/common';
import { RouterTestingModule } from '@angular/router/testing';
import { XHRBackend, Response, ResponseOptions } from '@angular/http';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { MockBackend } from '@angular/http/testing';
import { SharedModule } from '../../shared/shared.module';
import { TdLoadingService } from '@covalent/core';
import { CovalentHttpModule } from '@covalent/http';

import { ProductOverviewComponent } from './overview.component';

import { NgxChartsModule } from '@swimlane/ngx-charts';

describe('Component: ProductOverview', () => {

  let noop: () => void = () => {
    // noop method
  };

  let generalResponses: Map<string, Response> = new Map<string, Response>();
  generalResponses.set('assets/icons/covalent.svg', new Response(new ResponseOptions({
    status: 200, body: '<svg></svg>',
  })));
  generalResponses.set('assets/icons/github.svg', new Response(new ResponseOptions({
    status: 200, body: '<svg></svg>',
  })));

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        SharedModule,
        CovalentHttpModule.forRoot(),
        RouterTestingModule,
        NgxChartsModule,
        NoopAnimationsModule,
      ],
      declarations: [
        ProductOverviewComponent,
      ],
      providers: [
        MockBackend,
        { provide: XHRBackend, useExisting: MockBackend },
        { provide: APP_BASE_HREF, useValue: '/' },
        { provide: TdLoadingService, useValue: {
            createComponent: noop,
            createReplaceComponent: noop,
            register: noop,
            resolve: noop,
          },
        },
      ],
    });
    TestBed.compileComponents();
  }));

  it('should create the component', (done: any) => {
    inject([MockBackend], (mockBackend: MockBackend) => {
      let responses: Map<string, Response> = new Map<string, Response>(generalResponses);
      mockBackend.connections.subscribe((connection: any) => {
        connection.mockRespond(responses.get(connection.request.url));
      });
      responses.set('data/items.json', new Response(new ResponseOptions({
        status: 200, body: JSON.stringify([{
          item_id: 1,
          name: 'Suzy Cuningham',
          description: 'updated her account',
          icon: 'account_circle',
          created : '07/13/2016 11:05 AM',
        }, {
          item_id: 2,
          name: 'Bobby Daniels',
          description: 'made a deposit of $25.15',
          icon: 'account_balance_wallet',
          created : '07/01/2016 03:41 PM',
        }]),
      })));
      responses.set('data/users.json', new Response(new ResponseOptions({
        status: 200, body: JSON.stringify([{
          displayName : 'Suzy Cuningham',
          id : 'suzy.cuningham',
          email : 'suzy.cuningham@gmail.com',
          created : '10/01/2015 11:05 AM',
          lastAccess : '12/23/2015 11:05 AM',
          siteAdmin: true,
        }, {
          displayName : 'Bobby Daniels',
          id : 'bobbyD',
          email : 'bobbyD@outlook.com',
          created : '10/01/2015 11:05 AM',
          lastAccess : '12/23/2015 11:05 AM',
          siteAdmin: false,
        }]),
      })));

      let fixture: ComponentFixture<any> = TestBed.createComponent(ProductOverviewComponent);
      let testComponent: ProductOverviewComponent = fixture.debugElement.componentInstance;
      let element: HTMLElement = fixture.nativeElement;

      expect(element.querySelector('.item-list')).toBeTruthy();
      expect(element.querySelector('.user-list')).toBeTruthy();
      testComponent.ngAfterViewInit();
      fixture.detectChanges();

      fixture.whenStable().then(() => {
        expect(element.querySelectorAll('.item-list a[md-list-item]').length)
        .toBe(testComponent.items.length);
        expect(element.querySelectorAll('.user-list md-list-item').length)
        .toBe(testComponent.users.length);
        done();
      });
    })();
  });
});