text:
from six.moves.urllib import parse as urllib_parse

from proboscis import SkipTest

from trove.common import exception
from trove.common.utils import poll_until
from trove.tests.scenario.runners.test_runners import TestRunner
from troveclient.compat import exceptions

class UserActionsRunner(TestRunner):

    # TODO(pmalik): I believe the 202 (Accepted) should be replaced by
    # 200 (OK) as the actions are generally very fast and their results
    # available immediately upon execution of the request. This would
    # likely require replacing GA casts with calls which I believe are
    # more appropriate anyways.

    def __init__(self):
        super(UserActionsRunner, self).__init__()
        self.user_defs = []

    @property
    def first_user_def(self):
        if self.user_defs:
            return self.user_defs[0]
        raise SkipTest("No valid user definitions provided.")

    def run_users_create(self, expected_http_code=202):
        users = self.test_helper.get_valid_user_definitions()
        if users:
            self.user_defs = self.assert_users_create(
                self.instance_info.id, users, expected_http_code)
        else:
            raise SkipTest("No valid user definitions provided.")

    def assert_users_create(self, instance_id, serial_users_def,
                            expected_http_code):
        self.auth_client.users.create(instance_id, serial_users_def)
        self.assert_client_code(expected_http_code)
        self._wait_for_user_create(instance_id, serial_users_def)
        return serial_users_def

    def _wait_for_user_create(self, instance_id, expected_user_defs):
        expected_user_names = {user_def['name']
                               for user_def in expected_user_defs}
        self.report.log("Waiting for all created users to appear in the "
                        "listing: %s" % expected_user_names)

        def _all_exist():
            all_users = self._get_user_names(instance_id)
            return all(usr in all_users for usr in expected_user_names)

        try:
            poll_until(_all_exist, time_out=self.GUEST_CAST_WAIT_TIMEOUT_SEC)
            self.report.log("All users now exist on the instance.")
        except exception.PollTimeOut:
            self.fail("Some users were not created within the poll "
                      "timeout: %ds" % self.GUEST_CAST_WAIT_TIMEOUT_SEC)

    def _get_user_names(self, instance_id):
        full_list = self.auth_client.users.list(instance_id)
        return {user.name: user for user in full_list}

    def run_user_show(self, expected_http_code=200):
        for user_def in self.user_defs:
            self.assert_user_show(
                self.instance_info.id, user_def, expected_http_code)

    def assert_user_show(self, instance_id, expected_user_def,
                         expected_http_code):
        user_name = expected_user_def['name']
        user_host = expected_user_def.get('host')

        queried_user = self.auth_client.users.get(
            instance_id, user_name, user_host)
        self.assert_client_code(expected_http_code)
        self._assert_user_matches(queried_user, expected_user_def)

    def _assert_user_matches(self, user, expected_user_def):
        user_name = expected_user_def['name']
        self.assert_equal(expected_user_def['name'], user.name,
                          "Mismatch of names for user: %s" % user_name)
        self.assert_list_elements_equal(
            expected_user_def['databases'], user.databases,
            "Mismatch of databases for user: %s" % user_name)

    def run_users_list(self, expected_http_code=200):
        self.assert_users_list(
            self.instance_info.id, self.user_defs, expected_http_code)

    def assert_users_list(self, instance_id, expected_user_defs,
                          expected_http_code, limit=2):
        full_list = self.auth_client.users.list(instance_id)
        self.assert_client_code(expected_http_code)
        listed_users = {user.name: user for user in full_list}
        self.assert_is_none(full_list.next,
                            "Unexpected pagination in the list.")

        for user_def in expected_user_defs:
            user_name = user_def['name']
            self.assert_true(
                user_name in listed_users,
                "User not included in the 'user-list' output: %s" %
                user_name)
            self._assert_user_matches(listed_users[user_name], user_def)

        # Check that the system (ignored) users are not included in the output.
        system_users = self.get_system_users()
        self.assert_false(
            any(name in listed_users for name in system_users),
            "System users should not be included in the 'user-list' output.")

        # Test list pagination.
        list_page = self.auth_client.users.list(instance_id, limit=limit)
        self.assert_client_code(expected_http_code)

        self.assert_true(len(list_page) <= limit)
        if len(full_list) > limit:
            self.assert_is_not_none(list_page.next, "List page is missing.")
        else:
            self.assert_is_none(list_page.next, "An extra page in the list.")
        marker = list_page.next

        self.assert_pagination_match(list_page, full_list, 0, limit)
        if marker:
            last_user = list_page[-1]
            expected_marker = self.as_pagination_marker(last_user)
            self.assert_equal(expected_marker, marker,
                              "Pagination marker should be the last element "
                              "in the page.")
            list_page = self.auth_client.users.list(instance_id, marker=marker)
            self.assert_client_code(expected_http_code)
            self.assert_pagination_match(
                list_page, full_list, limit, len(full_list))

    def as_pagination_marker(self, user):
        return urllib_parse.quote(user.name)

    def run_user_access_show(self, expected_http_code=200):
        for user_def in self.user_defs:
            self.assert_user_access_show(
                self.instance_info.id, user_def, expected_http_code)

    def assert_user_access_show(self, instance_id, user_def,
                                expected_http_code):
        user_name, user_host = self._get_user_name_host_pair(user_def)
        user_dbs = self.auth_client.users.list_access(instance_id, user_name,
                                                      hostname=user_host)
        self.assert_client_code(expected_http_code)

        expected_dbs = {db_def['name'] for db_def in user_def['databases']}
        listed_dbs = [db.name for db in user_dbs]

        self.assert_equal(len(expected_dbs), len(listed_dbs),
                          "Unexpected number of databases on the user access "
                          "list.")

        for database in expected_dbs:
            self.assert_true(
                database in listed_dbs,
                "Database not found in the user access list: %s" % database)

    def run_user_access_revoke(self, expected_http_code=202):
        self._apply_on_all_databases(
            self.instance_info.id, self.assert_user_access_revoke,
            expected_http_code)

    def _apply_on_all_databases(self, instance_id, action, expected_http_code):
        if any(user_def['databases'] for user_def in self.user_defs):
            for user_def in self.user_defs:
                user_name, user_host = self._get_user_name_host_pair(user_def)
                db_defs = user_def['databases']
                for db_def in db_defs:
                    db_name = db_def['name']
                    action(instance_id, user_name, user_host,
                           db_name, expected_http_code)
        else:
            raise SkipTest("No user databases defined.")

    def assert_user_access_revoke(self, instance_id, user_name, user_host,
                                  database, expected_http_code):
        self.auth_client.users.revoke(
            instance_id, user_name, database, hostname=user_host)
        self.assert_client_code(expected_http_code)
        user_dbs = self.auth_client.users.list_access(
            instance_id, user_name, hostname=user_host)
        self.assert_false(any(db.name == database for db in user_dbs),
                          "Database should no longer be included in the user "
                          "access list after revoke: %s" % database)

    def run_user_access_grant(self, expected_http_code=202):
        self._apply_on_all_databases(
            self.instance_info.id, self.assert_user_access_grant,
            expected_http_code)

    def assert_user_access_grant(self, instance_id, user_name, user_host,
                                 database, expected_http_code):
        self.auth_client.users.grant(
            instance_id, user_name, [database], hostname=user_host)
        self.assert_client_code(expected_http_code)
        user_dbs = self.auth_client.users.list_access(
            instance_id, user_name, hostname=user_host)
        self.assert_true(any(db.name == database for db in user_dbs),
                         "Database should be included in the user "
                         "access list after granting access: %s" % database)

    def run_user_create_with_no_attributes(
            self, expected_exception=exceptions.BadRequest,
            expected_http_code=400):
        self.assert_users_create_failure(
            self.instance_info.id, {}, expected_exception, expected_http_code)

    def run_user_create_with_blank_name(
            self, expected_exception=exceptions.BadRequest,
            expected_http_code=400):
        usr_def = self.test_helper.get_non_existing_user_definition()
        # Test with missing user name attribute.
        no_name_usr_def = self.copy_dict(usr_def, ignored_keys=['name'])
        self.assert_users_create_failure(
            self.instance_info.id, no_name_usr_def,
            expected_exception, expected_http_code)

        # Test with empty user name attribute.
        blank_name_usr_def = self.copy_dict(usr_def)
        blank_name_usr_def.update({'name': ''})
        self.assert_users_create_failure(
            self.instance_info.id, blank_name_usr_def,
            expected_exception, expected_http_code)

    def run_user_create_with_blank_password(
            self, expected_exception=exceptions.BadRequest,
            expected_http_code=400):
        usr_def = self.test_helper.get_non_existing_user_definition()
        # Test with missing password attribute.
        no_pass_usr_def = self.copy_dict(usr_def, ignored_keys=['password'])
        self.assert_users_create_failure(
            self.instance_info.id, no_pass_usr_def,
            expected_exception, expected_http_code)

        # Test with missing databases attribute.
        no_db_usr_def = self.copy_dict(usr_def, ignored_keys=['databases'])
        self.assert_users_create_failure(
            self.instance_info.id, no_db_usr_def,
            expected_exception, expected_http_code)

    def run_existing_user_create(
            self, expected_exception=exceptions.BadRequest,
            expected_http_code=400):
        self.assert_users_create_failure(
            self.instance_info.id, self.first_user_def,
            expected_exception, expected_http_code)

    def run_system_user_create(
            self, expected_exception=exceptions.BadRequest,
            expected_http_code=400):
        # TODO(pmalik): Actions on system users and databases should probably
        # return Forbidden 403 instead. The current error messages are
        # confusing (talking about a malformed request).
        system_users = self.get_system_users()
        if system_users:
            user_defs = [{'name': name, 'password': 'password1',
                          'databases': []} for name in system_users]
            self.assert_users_create_failure(
                self.instance_info.id, user_defs,
                expected_exception, expected_http_code)

    def assert_users_create_failure(
            self, instance_id, serial_users_def,
            expected_exception, expected_http_code):
        self.assert_raises(
            expected_exception, expected_http_code,
            self.auth_client.users.create, instance_id, serial_users_def)

    def run_user_update_with_blank_name(
            self, expected_exception=exceptions.BadRequest,
            expected_http_code=400):
        self.assert_user_attribute_update_failure(
            self.instance_info.id, self.first_user_def, {'name': ''},
            expected_exception, expected_http_code)

    def run_user_update_with_existing_name(
            self, expected_exception=exceptions.BadRequest,
            expected_http_code=400):
        self.assert_user_attribute_update_failure(
            self.instance_info.id, self.first_user_def,
            {'name': self.first_user_def['name']},
            expected_exception, expected_http_code)

    def assert_user_attribute_update_failure(
            self, instance_id, user_def, update_attribites,
            expected_exception, expected_http_code):
        user_name, user_host = self._get_user_name_host_pair(user_def)

        self.assert_raises(
            expected_exception, expected_http_code,
            self.auth_client.users.update_attributes, instance_id,
            user_name, update_attribites, user_host)

    def _get_user_name_host_pair(self, user_def):
        return user_def['name'], user_def.get('host')

    def run_system_user_attribute_update(
            self, expected_exception=exceptions.BadRequest,
            expected_http_code=400):
        # TODO(pmalik): Actions on system users and databases should probably
        # return Forbidden 403 instead. The current error messages are
        # confusing (talking about a malformed request).
        system_users = self.get_system_users()
        if system_users:
            for name in system_users:
                user_def = {'name': name, 'password': 'password2'}
                self.assert_user_attribute_update_failure(
                    self.instance_info.id, user_def, user_def,
                    expected_exception, expected_http_code)

    def run_user_attribute_update(self, expected_http_code=202):
        updated_def = self.first_user_def
        # Update the name by appending a random string to it.
        updated_name = ''.join([updated_def['name'], 'upd'])
        update_attribites = {'name': updated_name,
                             'password': 'password2'}
        self.assert_user_attribute_update(
            self.instance_info.id, updated_def,
            update_attribites, expected_http_code)

    def assert_user_attribute_update(self, instance_id, user_def,
                                     update_attribites, expected_http_code):
        user_name, user_host = self._get_user_name_host_pair(user_def)

        self.auth_client.users.update_attributes(
            instance_id, user_name, update_attribites, user_host)
        self.assert_client_code(expected_http_code)

        # Update the stored definitions with the new value.
        expected_def = None
        for user_def in self.user_defs:
            if user_def['name'] == user_name:
                user_def.update(update_attribites)
                expected_def = user_def

        self._wait_for_user_create(instance_id, self.user_defs)

        # Verify using 'user-show' and 'user-list'.
        self.assert_user_show(instance_id, expected_def, 200)
        self.assert_users_list(instance_id, self.user_defs, 200)

    def run_user_delete(self, expected_http_code=202):
        for user_def in self.user_defs:
            self.assert_user_delete(
                self.instance_info.id, user_def, expected_http_code)

    def assert_user_delete(self, instance_id, user_def, expected_http_code):
        user_name, user_host = self._get_user_name_host_pair(user_def)

        self.auth_client.users.delete(instance_id, user_name, user_host)
        self.assert_client_code(expected_http_code)
        self._wait_for_user_delete(instance_id, user_name)

    def _wait_for_user_delete(self, instance_id, deleted_user_name):
        self.report.log("Waiting for deleted user to disappear from the "
                        "listing: %s" % deleted_user_name)

        def _db_is_gone():
            all_users = self._get_user_names(instance_id)
            return deleted_user_name not in all_users

        try:
            poll_until(_db_is_gone, time_out=self.GUEST_CAST_WAIT_TIMEOUT_SEC)
            self.report.log("User is now gone from the instance.")
        except exception.PollTimeOut:
            self.fail("User still listed after the poll timeout: %ds" %
                      self.GUEST_CAST_WAIT_TIMEOUT_SEC)

    def run_nonexisting_user_show(
            self, expected_exception=exceptions.NotFound,
            expected_http_code=404):
        usr_def = self.test_helper.get_non_existing_user_definition()
        self.assert_user_show_failure(
            self.instance_info.id, {'name': usr_def['name']},
            expected_exception, expected_http_code)

    def assert_user_show_failure(self, instance_id, user_def,
                                 expected_exception, expected_http_code):
        user_name, user_host = self._get_user_name_host_pair(user_def)

        self.assert_raises(
            expected_exception, expected_http_code,
            self.auth_client.users.get, instance_id, user_name, user_host)

    def run_system_user_show(
            self, expected_exception=exceptions.BadRequest,
            expected_http_code=400):
        # TODO(pmalik): Actions on system users and databases should probably
        # return Forbidden 403 instead. The current error messages are
        # confusing (talking about a malformed request).
        system_users = self.get_system_users()
        if system_users:
            for name in system_users:
                self.assert_user_show_failure(
                    self.instance_info.id, {'name': name},
                    expected_exception, expected_http_code)

    def run_nonexisting_user_update(self, expected_http_code=404):
        # Test valid update on a non-existing user.
        usr_def = self.test_helper.get_non_existing_user_definition()
        update_def = {'name': usr_def['name']}
        self.assert_user_attribute_update_failure(
            self.instance_info.id, update_def, update_def,
            exceptions.NotFound, expected_http_code)

    def run_nonexisting_user_delete(
            self, expected_exception=exceptions.NotFound,
            expected_http_code=404):
        usr_def = self.test_helper.get_non_existing_user_definition()
        self.assert_user_delete_failure(
            self.instance_info.id, {'name': usr_def['name']},
            expected_exception, expected_http_code)

    def assert_user_delete_failure(
            self, instance_id, user_def,
            expected_exception, expected_http_code):
        user_name, user_host = self._get_user_name_host_pair(user_def)

        self.assert_raises(expected_exception, expected_http_code,
                           self.auth_client.users.delete,
                           instance_id, user_name, user_host)

    def run_system_user_delete(
            self, expected_exception=exceptions.BadRequest,
            expected_http_code=400):
        # TODO(pmalik): Actions on system users and databases should probably
        # return Forbidden 403 instead. The current error messages are
        # confusing (talking about a malformed request).
        system_users = self.get_system_users()
        if system_users:
            for name in system_users:
                self.assert_user_delete_failure(
                    self.instance_info.id, {'name': name},
                    expected_exception, expected_http_code)

    def get_system_users(self):
        return self.get_datastore_config_property('ignore_users')

class MysqlUserActionsRunner(UserActionsRunner):

    def as_pagination_marker(self, user):
        return urllib_parse.quote('%s@%s' % (user.name, user.host))

class MariadbUserActionsRunner(MysqlUserActionsRunner):

    def __init__(self):
        super(MariadbUserActionsRunner, self).__init__()

class PerconaUserActionsRunner(MysqlUserActionsRunner):

    def __init__(self):
        super(PerconaUserActionsRunner, self).__init__()


text:
<TEMPLATE ID="5502" FORMAT="LAYOUT">

<ELEMENT ID="CPUKMLA" CREATOR="STAFF" IMAGES="0" PROPERTIES="1" SUBTYPE="S" SERIES="2006" FORMAT="LAYOUT" TYPE="CONFIG" RELEASED="00000000"><![CDATA[Search Box 1
Search Hints
Welcome Message
]]>
<TITLE><![CDATA[This is a search results layout designed for the advanced search functionality in the Evolution layout.]]></TITLE>
</ELEMENT>
<ELEMENT ID="CSPFDBG" TYPE="TITLE"><PRETEXT><![CDATA[
]]></PRETEXT>
<POSTTEXT><![CDATA[
]]></POSTTEXT>
</ELEMENT>
<ELEMENT SIZE="50000" ID="PRODUCTLIST" ALTERNATE="2" DATA="page:prodlist" COLS="1" FORMAT="CUSTOM" TYPE="PRODSEARCH"><![CDATA[

<td <% load($bg);  default("");  print(); %>>

		<A HREF="<% load($PROD_URL);  default("");  print(); %>"><% load($zoovy:prod_thumb);  default("");  default($zoovy:prod_image1); image(w=>"50",h=>"50",tag=>"1");  print(); %>

<A HREF="<% load($PROD_URL);  default("");  print(); %>" CLASS="search_list_text" STYLE="font-weight:bold; font-size:11px;"><% load($zoovy:prod_name);  default(""); strip(length=>"35",breaks=>"1",html=>"1");  print(); %>

<A HREF="<% load($PROD_URL);  default("");  print(); %>" CLASS="search_list_text"><% load($zoovy:prod_desc);  default(""); format(wiki,title1=>"",/title1=>"",title2=>"",/title2=>"",title3=>"",/title3=>"",listitem=>"",/listitem=>"",list=>"",/list=>"",hardbreak=>""); strip(length=>"150");  print(); %>

<% load($zoovy:base_price);  default("");  format(money);  format(after=>"space",skipblank=>"1");  format(after=>"bar",skipblank=>"1");  print(); %>  <% load($ADD_LINK);  default("");  print(); %>

]]>
</ELEMENT>

</TEMPLATE>

redpajama_set_name: RedPajamaGithub


text:
package test

import (
	"bytes"
	"fmt"
	"io"
	"net"
	"strings"
	"sync"
	"time"

	"golang.org/x/net/http2"
	"golang.org/x/net/http2/hpack"
)

type listenerWrapper struct {
	net.Listener
	mu  sync.Mutex
	rcw *rawConnWrapper
}

func listenWithConnControl(network, address string) (net.Listener, error) {
	l, err := net.Listen(network, address)
	if err != nil {
		return nil, err
	}
	return &listenerWrapper{Listener: l}, nil
}

// Accept blocks until Dial is called, then returns a net.Conn for the server
// half of the connection.
func (l *listenerWrapper) Accept() (net.Conn, error) {
	c, err := l.Listener.Accept()
	if err != nil {
		return nil, err
	}
	l.mu.Lock()
	l.rcw = newRawConnWrapperFromConn(c)
	l.mu.Unlock()
	return c, nil
}

func (l *listenerWrapper) getLastConn() *rawConnWrapper {
	l.mu.Lock()
	defer l.mu.Unlock()
	return l.rcw
}

type dialerWrapper struct {
	c   net.Conn
	rcw *rawConnWrapper
}

func (d *dialerWrapper) dialer(target string, t time.Duration) (net.Conn, error) {
	c, err := net.DialTimeout("tcp", target, t)
	d.c = c
	d.rcw = newRawConnWrapperFromConn(c)
	return c, err
}

func (d *dialerWrapper) getRawConnWrapper() *rawConnWrapper {
	return d.rcw
}

type rawConnWrapper struct {
	cc io.ReadWriteCloser
	fr *http2.Framer

	// writing headers:
	headerBuf bytes.Buffer
	hpackEnc  *hpack.Encoder

	// reading frames:
	frc       chan http2.Frame
	frErrc    chan error
	readTimer *time.Timer
}

func newRawConnWrapperFromConn(cc io.ReadWriteCloser) *rawConnWrapper {
	rcw := &rawConnWrapper{
		cc:     cc,
		frc:    make(chan http2.Frame, 1),
		frErrc: make(chan error, 1),
	}
	rcw.hpackEnc = hpack.NewEncoder(&rcw.headerBuf)
	rcw.fr = http2.NewFramer(cc, cc)
	rcw.fr.ReadMetaHeaders = hpack.NewDecoder(4096 /*initialHeaderTableSize*/, nil)

	return rcw
}

func (rcw *rawConnWrapper) Close() error {
	return rcw.cc.Close()
}

func (rcw *rawConnWrapper) readFrame() (http2.Frame, error) {
	go func() {
		fr, err := rcw.fr.ReadFrame()
		if err != nil {
			rcw.frErrc <- err
		} else {
			rcw.frc <- fr
		}
	}()
	t := time.NewTimer(2 * time.Second)
	defer t.Stop()
	select {
	case f := <-rcw.frc:
		return f, nil
	case err := <-rcw.frErrc:
		return nil, err
	case <-t.C:
		return nil, fmt.Errorf("timeout waiting for frame")
	}
}

// greet initiates the client's HTTP/2 connection into a state where
// frames may be sent.
func (rcw *rawConnWrapper) greet() error {
	rcw.writePreface()
	rcw.writeInitialSettings()
	rcw.wantSettings()
	rcw.writeSettingsAck()
	for {
		f, err := rcw.readFrame()
		if err != nil {
			return err
		}
		switch f := f.(type) {
		case *http2.WindowUpdateFrame:
			// grpc's transport/http2_server sends this
			// before the settings ack. The Go http2
			// server uses a setting instead.
		case *http2.SettingsFrame:
			if f.IsAck() {
				return nil
			}
			return fmt.Errorf("during greet, got non-ACK settings frame")
		default:
			return fmt.Errorf("during greet, unexpected frame type %T", f)
		}
	}
}

func (rcw *rawConnWrapper) writePreface() error {
	n, err := rcw.cc.Write([]byte(http2.ClientPreface))
	if err != nil {
		return fmt.Errorf("error writing client preface: %v", err)
	}
	if n != len(http2.ClientPreface) {
		return fmt.Errorf("writing client preface, wrote %d bytes; want %d", n, len(http2.ClientPreface))
	}
	return nil
}

func (rcw *rawConnWrapper) writeInitialSettings() error {
	if err := rcw.fr.WriteSettings(); err != nil {
		return fmt.Errorf("error writing initial SETTINGS frame from client to server: %v", err)
	}
	return nil
}

func (rcw *rawConnWrapper) writeSettingsAck() error {
	if err := rcw.fr.WriteSettingsAck(); err != nil {
		return fmt.Errorf("error writing ACK of server's SETTINGS: %v", err)
	}
	return nil
}

func (rcw *rawConnWrapper) wantSettings() (*http2.SettingsFrame, error) {
	f, err := rcw.readFrame()
	if err != nil {
		return nil, fmt.Errorf("error while expecting a SETTINGS frame: %v", err)
	}
	sf, ok := f.(*http2.SettingsFrame)
	if !ok {
		return nil, fmt.Errorf("got a %T; want *SettingsFrame", f)
	}
	return sf, nil
}

func (rcw *rawConnWrapper) wantSettingsAck() error {
	f, err := rcw.readFrame()
	if err != nil {
		return err
	}
	sf, ok := f.(*http2.SettingsFrame)
	if !ok {
		return fmt.Errorf("wanting a settings ACK, received a %T", f)
	}
	if !sf.IsAck() {
		return fmt.Errorf("settings Frame didn't have ACK set")
	}
	return nil
}

// wait for any activity from the server
func (rcw *rawConnWrapper) wantAnyFrame() (http2.Frame, error) {
	f, err := rcw.fr.ReadFrame()
	if err != nil {
		return nil, err
	}
	return f, nil
}

func (rcw *rawConnWrapper) encodeHeaderField(k, v string) error {
	err := rcw.hpackEnc.WriteField(hpack.HeaderField{Name: k, Value: v})
	if err != nil {
		return fmt.Errorf("HPACK encoding error for %q/%q: %v", k, v, err)
	}
	return nil
}

// encodeRawHeader is for usage on both client and server side to construct header based on the input
// key, value pairs.
func (rcw *rawConnWrapper) encodeRawHeader(headers ...string) []byte {
	if len(headers)%2 == 1 {
		panic("odd number of kv args")
	}

	rcw.headerBuf.Reset()

	pseudoCount := map[string]int{}
	var keys []string
	vals := map[string][]string{}

	for len(headers) > 0 {
		k, v := headers[0], headers[1]
		headers = headers[2:]
		if _, ok := vals[k]; !ok {
			keys = append(keys, k)
		}
		if strings.HasPrefix(k, ":") {
			pseudoCount[k]++
			if pseudoCount[k] == 1 {
				vals[k] = []string{v}
			} else {
				// Allows testing of invalid headers w/ dup pseudo fields.
				vals[k] = append(vals[k], v)
			}
		} else {
			vals[k] = append(vals[k], v)
		}
	}
	for _, k := range keys {
		for _, v := range vals[k] {
			rcw.encodeHeaderField(k, v)
		}
	}
	return rcw.headerBuf.Bytes()
}

// encodeHeader is for usage on client side to write request header.
//
// encodeHeader encodes headers and returns their HPACK bytes. headers
// must contain an even number of key/value pairs.  There may be
// multiple pairs for keys (e.g. "cookie").  The :method, :path, and
// :scheme headers default to GET, / and https.
func (rcw *rawConnWrapper) encodeHeader(headers ...string) []byte {
	if len(headers)%2 == 1 {
		panic("odd number of kv args")
	}

	rcw.headerBuf.Reset()

	if len(headers) == 0 {
		// Fast path, mostly for benchmarks, so test code doesn't pollute
		// profiles when we're looking to improve server allocations.
		rcw.encodeHeaderField(":method", "GET")
		rcw.encodeHeaderField(":path", "/")
		rcw.encodeHeaderField(":scheme", "https")
		return rcw.headerBuf.Bytes()
	}

	if len(headers) == 2 && headers[0] == ":method" {
		// Another fast path for benchmarks.
		rcw.encodeHeaderField(":method", headers[1])
		rcw.encodeHeaderField(":path", "/")
		rcw.encodeHeaderField(":scheme", "https")
		return rcw.headerBuf.Bytes()
	}

	pseudoCount := map[string]int{}
	keys := []string{":method", ":path", ":scheme"}
	vals := map[string][]string{
		":method": {"GET"},
		":path":   {"/"},
		":scheme": {"https"},
	}
	for len(headers) > 0 {
		k, v := headers[0], headers[1]
		headers = headers[2:]
		if _, ok := vals[k]; !ok {
			keys = append(keys, k)
		}
		if strings.HasPrefix(k, ":") {
			pseudoCount[k]++
			if pseudoCount[k] == 1 {
				vals[k] = []string{v}
			} else {
				// Allows testing of invalid headers w/ dup pseudo fields.
				vals[k] = append(vals[k], v)
			}
		} else {
			vals[k] = append(vals[k], v)
		}
	}
	for _, k := range keys {
		for _, v := range vals[k] {
			rcw.encodeHeaderField(k, v)
		}
	}
	return rcw.headerBuf.Bytes()
}

// writeHeadersGRPC is for usage on client side to write request header.
func (rcw *rawConnWrapper) writeHeadersGRPC(streamID uint32, path string) {
	rcw.writeHeaders(http2.HeadersFrameParam{
		StreamID: streamID,
		BlockFragment: rcw.encodeHeader(
			":method", "POST",
			":path", path,
			"content-type", "application/grpc",
			"te", "trailers",
		),
		EndStream:  false,
		EndHeaders: true,
	})
}

func (rcw *rawConnWrapper) writeHeaders(p http2.HeadersFrameParam) error {
	if err := rcw.fr.WriteHeaders(p); err != nil {
		return fmt.Errorf("error writing HEADERS: %v", err)
	}
	return nil
}

func (rcw *rawConnWrapper) writeData(streamID uint32, endStream bool, data []byte) error {
	if err := rcw.fr.WriteData(streamID, endStream, data); err != nil {
		return fmt.Errorf("error writing DATA: %v", err)
	}
	return nil
}

func (rcw *rawConnWrapper) writeRSTStream(streamID uint32, code http2.ErrCode) error {
	if err := rcw.fr.WriteRSTStream(streamID, code); err != nil {
		return fmt.Errorf("error writing RST_STREAM: %v", err)
	}
	return nil
}

func (rcw *rawConnWrapper) writeDataPadded(streamID uint32, endStream bool, data, padding []byte) error {
	if err := rcw.fr.WriteDataPadded(streamID, endStream, data, padding); err != nil {
		return fmt.Errorf("error writing DATA with padding: %v", err)
	}
	return nil
}

func (rcw *rawConnWrapper) writeGoAway(maxStreamID uint32, code http2.ErrCode, debugData []byte) error {
	if err := rcw.fr.WriteGoAway(maxStreamID, code, debugData); err != nil {
		return fmt.Errorf("error writing GoAway: %v", err)
	}
	return nil
}

func (rcw *rawConnWrapper) writeRawFrame(t http2.FrameType, flags http2.Flags, streamID uint32, payload []byte) error {
	if err := rcw.fr.WriteRawFrame(t, flags, streamID, payload); err != nil {
		return fmt.Errorf("error writing Raw Frame: %v", err)
	}
	return nil
}


text:
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using SuperSocket.Common;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketEngine.AsyncSocket;

namespace SuperSocket.SocketEngine
{
    class AsyncSocketServer<TAppSession, TCommandInfo> : TcpSocketServerBase<AsyncSocketSession<TAppSession, TCommandInfo>, TAppSession, TCommandInfo>
        where TAppSession : IAppSession, IAppSession<TAppSession, TCommandInfo>, new()
        where TCommandInfo : ICommandInfo
    {
        public AsyncSocketServer(IAppServer<TAppSession> appServer, IPEndPoint localEndPoint, ICustomProtocol<TCommandInfo> protocol)
            : base(appServer, localEndPoint, protocol)
        {

        }

        private AutoResetEvent m_TcpClientConnected;

        private BufferManager m_BufferManager;

        private ConcurrentStack<SocketAsyncEventArgsProxy> m_ReadWritePool;

        private Semaphore m_MaxConnectionSemaphore;

        private Socket m_ListenSocket = null;

        private Thread m_ListenThread = null;

        public override bool Start()
        {
            try
            {
                if (!base.Start())
                    return false;

                m_TcpClientConnected = new AutoResetEvent(false);

                int bufferSize = AppServer.Config.ReceiveBufferSize;

                if (bufferSize <= 0)
                    bufferSize = 1024 * 4;

                m_BufferManager = new BufferManager(bufferSize * AppServer.Config.MaxConnectionNumber, bufferSize);

                try
                {
                    m_BufferManager.InitBuffer();
                }
                catch (Exception e)
                {
                    AppServer.Logger.LogError("Failed to allocate buffer for async socket communication, may because there is no enough memory, please decrease maxConnectionNumber in configuration!", e);
                    return false;
                }

                // preallocate pool of SocketAsyncEventArgs objects
                SocketAsyncEventArgs socketEventArg;

                var socketArgsProxyList = new List<SocketAsyncEventArgsProxy>(AppServer.Config.MaxConnectionNumber);

                for (int i = 0; i < AppServer.Config.MaxConnectionNumber; i++)
                {
                    //Pre-allocate a set of reusable SocketAsyncEventArgs
                    socketEventArg = new SocketAsyncEventArgs();
                    socketEventArg.UserToken = new AsyncUserToken();
                    m_BufferManager.SetBuffer(socketEventArg);

                    socketArgsProxyList.Add(new SocketAsyncEventArgsProxy(socketEventArg));
                }

                m_ReadWritePool = new ConcurrentStack<SocketAsyncEventArgsProxy>(socketArgsProxyList);

                if (m_ListenSocket == null)
                {
                    m_ListenThread = new Thread(StartListen);
                    m_ListenThread.Start();
                }

                WaitForStartupFinished();

                return IsRunning;
            }
            catch (Exception e)
            {
                AppServer.Logger.LogError(e);
                return false;
            }
        }

        private void StartListen()
        {
            m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                m_ListenSocket.Bind(this.EndPoint);
                m_ListenSocket.Listen(this.AppServer.Config.ListenBacklog);

                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
            }
            catch (Exception e)
            {
                AppServer.Logger.LogError(e);
                OnStartupFinished();
                return;
            }

            m_MaxConnectionSemaphore = new Semaphore(this.AppServer.Config.MaxConnectionNumber, this.AppServer.Config.MaxConnectionNumber);

            SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
            acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed);

            IsRunning = true;

            OnStartupFinished();

            while (!IsStopped)
            {
                m_MaxConnectionSemaphore.WaitOne();

                if (IsStopped)
                    break;

                acceptEventArg.AcceptSocket = null;

                bool willRaiseEvent = true;

                try
                {
                    willRaiseEvent = m_ListenSocket.AcceptAsync(acceptEventArg);
                }
                catch (ObjectDisposedException)//listener has been stopped
                {
                    break;
                }
                catch (NullReferenceException)
                {
                    break;
                }
                catch (Exception e)
                {
                    AppServer.Logger.LogError("Failed to accept new tcp client in async server!", e);
                    break;
                }

                if (!willRaiseEvent)
                    AceptNewClient(acceptEventArg);

                m_TcpClientConnected.WaitOne();
            }

            IsRunning = false;
        }

        void acceptEventArg_Completed(object sender, SocketAsyncEventArgs e)
        {
            AceptNewClient(e);
        }

        void AceptNewClient(SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success)
            {
                var client = e.AcceptSocket;
                m_TcpClientConnected.Set();

                //Get the socket for the accepted client connection and put it into the
                //ReadEventArg object user token
                SocketAsyncEventArgsProxy socketEventArgsProxy;
                if (!m_ReadWritePool.TryPop(out socketEventArgsProxy))
                {
                    AppServer.Logger.LogError("There is no enough buffer block to arrange to new accepted client!");
                    return;
                }

                var session = RegisterSession(client, new AsyncSocketSession<TAppSession, TCommandInfo>(client, Protocol.CreateCommandReader(AppServer)));

                if (session != null)
                {
                    session.SocketAsyncProxy = socketEventArgsProxy;
                    session.Closed += new EventHandler<SocketSessionClosedEventArgs>(session_Closed);
                    session.Start();
                }
                else
                {
                    Async.Run(() => client.SafeCloseClientSocket(AppServer.Logger));
                }
            }
            else
            {
                m_TcpClientConnected.Set();
            }
        }

        void session_Closed(object sender, SocketSessionClosedEventArgs e)
        {
            m_MaxConnectionSemaphore.Release();

            IAsyncSocketSession socketSession = sender as IAsyncSocketSession;
            if (socketSession != null && this.m_ReadWritePool != null)
                this.m_ReadWritePool.Push(socketSession.SocketAsyncProxy);
        }

        public override void Stop()
        {
            base.Stop();

            if (m_ListenSocket != null)
            {
                m_ListenSocket.Close();
                m_ListenSocket = null;
            }

            if (m_ReadWritePool != null)
                m_ReadWritePool = null;

            if (m_BufferManager != null)
                m_BufferManager = null;

            VerifySocketServerRunning(false);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (IsRunning)
                    Stop();

                m_TcpClientConnected.Close();
                m_MaxConnectionSemaphore.Close();
            }

            base.Dispose(disposing);
        }
    }
}


text:
.. _reference:

*****************
Command Reference
*****************

.. % \section{Building modules: the \protect\command{build} command family}
.. % \label{build-cmds}
.. % \subsubsection{\protect\command{build}}
.. % \label{build-cmd}
.. % \subsubsection{\protect\command{build\_py}}
.. % \label{build-py-cmd}
.. % \subsubsection{\protect\command{build\_ext}}
.. % \label{build-ext-cmd}
.. % \subsubsection{\protect\command{build\_clib}}
.. % \label{build-clib-cmd}

.. _install-cmd:

Installing modules: the :command:`install` command family
=========================================================

The install command ensures that the build commands have been run and then runs
the subcommands :command:`install_lib`, :command:`install_data` and
:command:`install_scripts`.

.. % \subsubsection{\protect\command{install\_lib}}
.. % \label{install-lib-cmd}

.. _install-data-cmd:

:command:`install_data`
-----------------------

This command installs all data files provided with the distribution.

.. _install-scripts-cmd:

:command:`install_scripts`
--------------------------

This command installs all (Python) scripts in the distribution.

.. % \subsection{Cleaning up: the \protect\command{clean} command}
.. % \label{clean-cmd}

.. % \section{Creating a built distribution: the
.. % \protect\command{bdist} command family}
.. % \label{bdist-cmds}

.. % \subsection{\protect\command{bdist}}
.. % \subsection{\protect\command{bdist\_dumb}}
.. % \subsection{\protect\command{bdist\_rpm}}
.. % \subsection{\protect\command{bdist\_wininst}}


text:
import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;
import org.jspecify.annotations.NullnessUnspecified;

@DefaultNonNull
class NullLiteralToTypeVariableUnionNull<
    Never1T,
    ChildOfNever1T extends Never1T,
    UnspecChildOfNever1T extends @NullnessUnspecified Never1T,
    NullChildOfNever1T extends @Nullable Never1T,
    //
    Never2T extends Object,
    ChildOfNever2T extends Never2T,
    UnspecChildOfNever2T extends @NullnessUnspecified Never2T,
    NullChildOfNever2T extends @Nullable Never2T,
    //
    UnspecT extends @NullnessUnspecified Object,
    ChildOfUnspecT extends UnspecT,
    UnspecChildOfUnspecT extends @NullnessUnspecified UnspecT,
    NullChildOfUnspecT extends @Nullable UnspecT,
    //
    ParametricT extends @Nullable Object,
    ChildOfParametricT extends ParametricT,
    UnspecChildOfParametricT extends @NullnessUnspecified ParametricT,
    NullChildOfParametricT extends @Nullable ParametricT,
    //
    UnusedT> {
  @Nullable
  Never1T x0() {
    return null;
  }

  @Nullable
  ChildOfNever1T x1() {
    return null;
  }

  @Nullable
  UnspecChildOfNever1T x2() {
    return null;
  }

  @Nullable
  NullChildOfNever1T x3() {
    return null;
  }

  @Nullable
  Never2T x4() {
    return null;
  }

  @Nullable
  ChildOfNever2T x5() {
    return null;
  }

  @Nullable
  UnspecChildOfNever2T x6() {
    return null;
  }

  @Nullable
  NullChildOfNever2T x7() {
    return null;
  }

  @Nullable
  UnspecT x8() {
    return null;
  }

  @Nullable
  ChildOfUnspecT x9() {
    return null;
  }

  @Nullable
  UnspecChildOfUnspecT x10() {
    return null;
  }

  @Nullable
  NullChildOfUnspecT x11() {
    return null;
  }

  @Nullable
  ParametricT x12() {
    return null;
  }

  @Nullable
  ChildOfParametricT x13() {
    return null;
  }

  @Nullable
  UnspecChildOfParametricT x14() {
    return null;
  }

  @Nullable
  NullChildOfParametricT x15() {
    return null;
  }
}


text:
import MyCodeSnippetsModule from './my-code-snippets'
import MyCodeSnippetsController from './my-code-snippets.controller';
import MyCodeSnippetsComponent from './my-code-snippets.component';
import MyCodeSnippetsTemplate from './my-code-snippets.html';

describe('MyCodeSnippets', () => {
  let $rootScope, makeController;

  beforeEach(window.module(MyCodeSnippetsModule.name));
  beforeEach(inject((_$rootScope_) => {
    $rootScope = _$rootScope_;
    makeController = () => {
      return new MyCodeSnippetsController();
    };
  }));

  describe('Module', () => {
    // top-level specs: i.e., routes, injection, naming
  });

  describe('Controller', () => {
    // controller specs
    it('has a name property [REMOVE]', () => { // erase if removing this.name from the controller
      let controller = makeController();
      expect(controller).to.have.property('name');
    });
  });

  describe('Template', () => {
    // template specs
    // tip: use regex to ensure correct bindings are used e.g., {{  }}
    it('has name in template [REMOVE]', () => {
      expect(MyCodeSnippetsTemplate).to.match(/{{\s?vm\.name\s?}}/g);
    });
  });

  describe('Component', () => {
      // component/directive specs
      let component = MyCodeSnippetsComponent();

      it('includes the intended template',() => {
        expect(component.template).to.equal(MyCodeSnippetsTemplate);
      });

      it('uses `controllerAs` syntax', () => {
        expect(component).to.have.property('controllerAs');
      });

      it('invokes the right controller', () => {
        expect(component.controller).to.equal(MyCodeSnippetsController);
      });
  });
});


text:
package org.expressme.webwind;

/**
 * Intercept action's execution like servlet Filter, but interceptors are
 * configured and managed by IoC container. Another difference from Filter
 * is that Interceptor is executed around Action's execution, but before
 * rendering view.
 *
 * @author Michael Liao (askxuefeng@gmail.com)
 */
public interface Interceptor {

    /**
     * Do intercept and invoke chain.doInterceptor() to process next interceptor.
     * NOTE that process will not continue if chain.doInterceptor() method is not
     * invoked.
     *
     * @param execution Execution instance to handle http request.
     * @param chain Interceptor chain.
     * @throws Exception If any exception is thrown, process will not continued.
     */
    void intercept(Execution execution, InterceptorChain chain) throws Exception;

}


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"
	"github.com/go-openapi/validate"
)

// QtreeReference qtree reference
//
// swagger:model qtree_reference
type QtreeReference struct {

	// links
	Links *QtreeReferenceLinks `json:"_links,omitempty"`

	// The identifier for the qtree, unique within the qtree's volume.
	//
	// Example: 1
	// Maximum: 4994
	// Minimum: 0
	ID *int64 `json:"id,omitempty"`

	// The name of the qtree.
	// Example: qt1
	Name string `json:"name,omitempty"`
}

// Validate validates this qtree reference
func (m *QtreeReference) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateLinks(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateID(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *QtreeReference) validateLinks(formats strfmt.Registry) error {
	if swag.IsZero(m.Links) { // not required
		return nil
	}

	if m.Links != nil {
		if err := m.Links.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links")
			}
			return err
		}
	}

	return nil
}

func (m *QtreeReference) validateID(formats strfmt.Registry) error {
	if swag.IsZero(m.ID) { // not required
		return nil
	}

	if err := validate.MinimumInt("id", "body", *m.ID, 0, false); err != nil {
		return err
	}

	if err := validate.MaximumInt("id", "body", *m.ID, 4994, false); err != nil {
		return err
	}

	return nil
}

// ContextValidate validate this qtree reference based on the context it is used
func (m *QtreeReference) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateLinks(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *QtreeReference) contextValidateLinks(ctx context.Context, formats strfmt.Registry) error {

	if m.Links != nil {
		if err := m.Links.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links")
			}
			return err
		}
	}

	return nil
}

// MarshalBinary interface implementation
func (m *QtreeReference) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *QtreeReference) UnmarshalBinary(b []byte) error {
	var res QtreeReference
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// QtreeReferenceLinks qtree reference links
//
// swagger:model QtreeReferenceLinks
type QtreeReferenceLinks struct {

	// self
	Self *Href `json:"self,omitempty"`
}

// Validate validates this qtree reference links
func (m *QtreeReferenceLinks) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateSelf(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *QtreeReferenceLinks) validateSelf(formats strfmt.Registry) error {
	if swag.IsZero(m.Self) { // not required
		return nil
	}

	if m.Self != nil {
		if err := m.Self.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links" + "." + "self")
			}
			return err
		}
	}

	return nil
}

// ContextValidate validate this qtree reference links based on the context it is used
func (m *QtreeReferenceLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateSelf(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *QtreeReferenceLinks) contextValidateSelf(ctx context.Context, formats strfmt.Registry) error {

	if m.Self != nil {
		if err := m.Self.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links" + "." + "self")
			}
			return err
		}
	}

	return nil
}

// MarshalBinary interface implementation
func (m *QtreeReferenceLinks) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *QtreeReferenceLinks) UnmarshalBinary(b []byte) error {
	var res QtreeReferenceLinks
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}


text:
var gantt = require('./parser/gantt').parser
gantt.yy = require('./ganttDb')
var d3 = require('../../d3')
var moment = require('moment')

var daysInChart
var conf = {
  titleTopMargin: 25,
  barHeight: 20,
  barGap: 4,
  topPadding: 50,
  rightPadding: 75,
  leftPadding: 75,
  gridLineStartPadding: 35,
  fontSize: 11,
  fontFamily: '"Open-Sans", "sans-serif"'
}
module.exports.setConf = function (cnf) {
  var keys = Object.keys(cnf)

  keys.forEach(function (key) {
    conf[key] = cnf[key]
  })
}
var w
module.exports.draw = function (text, id) {
  gantt.yy.clear()
  gantt.parse(text)

  var elem = document.getElementById(id)
  w = elem.parentElement.offsetWidth

  if (typeof w === 'undefined') {
    w = 1200
  }

  if (typeof conf.useWidth !== 'undefined') {
    w = conf.useWidth
  }

  var taskArray = gantt.yy.getTasks()

  // Set height based on number of tasks
  var h = taskArray.length * (conf.barHeight + conf.barGap) + 2 * conf.topPadding

  elem.setAttribute('height', '100%')
  // Set viewBox
  elem.setAttribute('viewBox', '0 0 ' + w + ' ' + h)
  var svg = d3.select('#' + id)

  var startDate = d3.min(taskArray, function (d) {
    return d.startTime
  })
  var endDate = d3.max(taskArray, function (d) {
    return d.endTime
  })

  // Set timescale
  var timeScale = d3.time.scale()
    .domain([d3.min(taskArray, function (d) {
      return d.startTime
    }),
      d3.max(taskArray, function (d) {
        return d.endTime
      })])
    .rangeRound([0, w - conf.leftPadding - conf.rightPadding])

  var categories = []

  daysInChart = moment.duration(endDate - startDate).asDays()

  for (var i = 0; i < taskArray.length; i++) {
    categories.push(taskArray[i].type)
  }

  var catsUnfiltered = categories // for vert labels

  categories = checkUnique(categories)

  makeGant(taskArray, w, h)
  if (typeof conf.useWidth !== 'undefined') {
    elem.setAttribute('width', w)
  }

  svg.append('text')
    .text(gantt.yy.getTitle())
    .attr('x', w / 2)
    .attr('y', conf.titleTopMargin)
    .attr('class', 'titleText')

  function makeGant (tasks, pageWidth, pageHeight) {
    var barHeight = conf.barHeight
    var gap = barHeight + conf.barGap
    var topPadding = conf.topPadding
    var leftPadding = conf.leftPadding

    var colorScale = d3.scale.linear()
      .domain([0, categories.length])
      .range(['#00B9FA', '#F95002'])
      .interpolate(d3.interpolateHcl)

    makeGrid(leftPadding, topPadding, pageWidth, pageHeight)
    drawRects(tasks, gap, topPadding, leftPadding, barHeight, colorScale, pageWidth, pageHeight)
    vertLabels(gap, topPadding, leftPadding, barHeight, colorScale)
    drawToday(leftPadding, topPadding, pageWidth, pageHeight)
  }

  function drawRects (theArray, theGap, theTopPad, theSidePad, theBarHeight, theColorScale, w, h) {
    svg.append('g')
      .selectAll('rect')
      .data(theArray)
      .enter()
      .append('rect')
      .attr('x', 0)
      .attr('y', function (d, i) {
        return i * theGap + theTopPad - 2
      })
      .attr('width', function () {
        return w - conf.rightPadding / 2
      })
      .attr('height', theGap)
      .attr('class', function (d) {
        for (var i = 0; i < categories.length; i++) {
          if (d.type === categories[i]) {
            return 'section section' + (i % conf.numberSectionStyles)
          }
        }
        return 'section section0'
      })

    var rectangles = svg.append('g')
      .selectAll('rect')
      .data(theArray)
      .enter()

    rectangles.append('rect')
      .attr('rx', 3)
      .attr('ry', 3)
      .attr('x', function (d) {
        return timeScale(d.startTime) + theSidePad
      })
      .attr('y', function (d, i) {
        return i * theGap + theTopPad
      })
      .attr('width', function (d) {
        return (timeScale(d.endTime) - timeScale(d.startTime))
      })
      .attr('height', theBarHeight)
      .attr('class', function (d) {
        var res = 'task '

        var secNum = 0
        for (var i = 0; i < categories.length; i++) {
          if (d.type === categories[i]) {
            secNum = (i % conf.numberSectionStyles)
          }
        }

        if (d.active) {
          if (d.crit) {
            return res + ' activeCrit' + secNum
          } else {
            return res + ' active' + secNum
          }
        }

        if (d.done) {
          if (d.crit) {
            return res + ' doneCrit' + secNum
          } else {
            return res + ' done' + secNum
          }
        }

        if (d.crit) {
          return res + ' crit' + secNum
        }

        return res + ' task' + secNum
      })

    rectangles.append('text')
      .text(function (d) {
        return d.task
      })
      .attr('font-size', conf.fontSize)
      .attr('x', function (d) {
        var startX = timeScale(d.startTime)
        var endX = timeScale(d.endTime)
        var textWidth = this.getBBox().width

        // Check id text width > width of rectangle
        if (textWidth > (endX - startX)) {
          if (endX + textWidth + 1.5 * conf.leftPadding > w) {
            return startX + theSidePad - 5
          } else {
            return endX + theSidePad + 5
          }
        } else {
          return (endX - startX) / 2 + startX + theSidePad
        }
      })
      .attr('y', function (d, i) {
        return i * theGap + (conf.barHeight / 2) + (conf.fontSize / 2 - 2) + theTopPad
      })
      .attr('text-height', theBarHeight)
      .attr('class', function (d) {
        var startX = timeScale(d.startTime)
        var endX = timeScale(d.endTime)
        var textWidth = this.getBBox().width
        var secNum = 0
        for (var i = 0; i < categories.length; i++) {
          if (d.type === categories[i]) {
            secNum = (i % conf.numberSectionStyles)
          }
        }

        var taskType = ''
        if (d.active) {
          if (d.crit) {
            taskType = 'activeCritText' + secNum
          } else {
            taskType = 'activeText' + secNum
          }
        }

        if (d.done) {
          if (d.crit) {
            taskType = taskType + ' doneCritText' + secNum
          } else {
            taskType = taskType + ' doneText' + secNum
          }
        } else {
          if (d.crit) {
            taskType = taskType + ' critText' + secNum
          }
        }

        // Check id text width > width of rectangle
        if (textWidth > (endX - startX)) {
          if (endX + textWidth + 1.5 * conf.leftPadding > w) {
            return 'taskTextOutsideLeft taskTextOutside' + secNum + ' ' + taskType
          } else {
            return 'taskTextOutsideRight taskTextOutside' + secNum + ' ' + taskType
          }
        } else {
          return 'taskText taskText' + secNum + ' ' + taskType
        }
      })
  }

  function makeGrid (theSidePad, theTopPad, w, h) {
    var pre = [
      ['.%L', function (d) {
        return d.getMilliseconds()
      }],
      [':%S', function (d) {
        return d.getSeconds()
      }],
      // Within a hour
      ['h1 %I:%M', function (d) {
        return d.getMinutes()
      }]]
    var post = [
      ['%Y', function () {
        return true
      }]]

    var mid = [
      // Within a day
      ['%I:%M', function (d) {
        return d.getHours()
      }],
      // Day within a week (not monday)
      ['%a %d', function (d) {
        return d.getDay() && d.getDate() !== 1
      }],
      // within a month
      ['%b %d', function (d) {
        return d.getDate() !== 1
      }],
      // Month
      ['%B', function (d) {
        return d.getMonth()
      }]
    ]
    var formatter
    if (typeof conf.axisFormatter !== 'undefined') {
      mid = []
      conf.axisFormatter.forEach(function (item) {
        var n = []
        n[0] = item[0]
        n[1] = item[1]
        mid.push(n)
      })
    }
    formatter = pre.concat(mid).concat(post)

    var xAxis = d3.svg.axis()
      .scale(timeScale)
      .orient('bottom')
      .tickSize(-h + theTopPad + conf.gridLineStartPadding, 0, 0)
      .tickFormat(d3.time.format.multi(formatter))

    if (daysInChart > 7 && daysInChart < 230) {
      xAxis = xAxis.ticks(d3.time.monday.range)
    }

    svg.append('g')
      .attr('class', 'grid')
      .attr('transform', 'translate(' + theSidePad + ', ' + (h - 50) + ')')
      .call(xAxis)
      .selectAll('text')
      .style('text-anchor', 'middle')
      .attr('fill', '#000')
      .attr('stroke', 'none')
      .attr('font-size', 10)
      .attr('dy', '1em')
  }

  function vertLabels (theGap, theTopPad) {
    var numOccurances = []
    var prevGap = 0

    for (var i = 0; i < categories.length; i++) {
      numOccurances[i] = [categories[i], getCount(categories[i], catsUnfiltered)]
    }

    svg.append('g') // without doing this, impossible to put grid lines behind text
      .selectAll('text')
      .data(numOccurances)
      .enter()
      .append('text')
      .text(function (d) {
        return d[0]
      })
      .attr('x', 10)
      .attr('y', function (d, i) {
        if (i > 0) {
          for (var j = 0; j < i; j++) {
            prevGap += numOccurances[i - 1][1]
            return d[1] * theGap / 2 + prevGap * theGap + theTopPad
          }
        } else {
          return d[1] * theGap / 2 + theTopPad
        }
      })
      .attr('class', function (d) {
        for (var i = 0; i < categories.length; i++) {
          if (d[0] === categories[i]) {
            return 'sectionTitle sectionTitle' + (i % conf.numberSectionStyles)
          }
        }
        return 'sectionTitle'
      })
  }

  function drawToday (theSidePad, theTopPad, w, h) {
    var todayG = svg.append('g')
      .attr('class', 'today')

    var today = new Date()

    todayG.append('line')
      .attr('x1', timeScale(today) + theSidePad)
      .attr('x2', timeScale(today) + theSidePad)
      .attr('y1', conf.titleTopMargin)
      .attr('y2', h - conf.titleTopMargin)
      .attr('class', 'today')
  }

  // from this stackexchange question: http://stackoverflow.com/questions/1890203/unique-for-arrays-in-javascript
  function checkUnique (arr) {
    var hash = {}
    var result = []
    for (var i = 0, l = arr.length; i < l; ++i) {
      if (!hash.hasOwnProperty(arr[i])) { // it works with objects! in FF, at least
        hash[arr[i]] = true
        result.push(arr[i])
      }
    }
    return result
  }

  // from this stackexchange question: http://stackoverflow.com/questions/14227981/count-how-many-strings-in-an-array-have-duplicates-in-the-same-array
  function getCounts (arr) {
    var i = arr.length // var to loop over
    var obj = {} // obj to store results
    while (i) {
      obj[arr[--i]] = (obj[arr[i]] || 0) + 1 // count occurrences
    }
    return obj
  }

  // get specific from everything
  function getCount (word, arr) {
    return getCounts(arr)[word] || 0
  }
}


text:
#include <boost/scoped_ptr.hpp>
#include <boost/optional.hpp>
#include <testing/gunit.h>
#include <base/logging.h>

#include <bfd/bfd_state_machine.h>
#include "bfd/test/bfd_test_utils.h"

using namespace BFD;

class StateMachineTest : public ::testing::Test {
  public:
    StateMachineTest() : sm(CreateStateMachine(&evm, NULL)) {}

    EventManager evm;
    boost::scoped_ptr<StateMachine> sm;
};

TEST_F(StateMachineTest, Test1) {
    EXPECT_EQ(kInit, sm->GetState());
    sm->ProcessRemoteState(kInit);
    EXPECT_EQ(kUp, sm->GetState());
    sm->ProcessRemoteState(kInit);
    EXPECT_EQ(kUp, sm->GetState());
    sm->ProcessRemoteState(kUp);
    EXPECT_EQ(kUp, sm->GetState());
    sm->ProcessRemoteState(kInit);
    EXPECT_EQ(kUp, sm->GetState());
    sm->ProcessRemoteState(kDown);
    EXPECT_EQ(kDown, sm->GetState());
    sm->ProcessRemoteState(kUp);
    EXPECT_EQ(kDown, sm->GetState());
    sm->ProcessRemoteState(kDown);
    EXPECT_EQ(kInit, sm->GetState());
    sm->ProcessRemoteState(kDown);
    EXPECT_EQ(kInit, sm->GetState());
    sm->ProcessRemoteState(kUp);
    EXPECT_EQ(kUp, sm->GetState());
}

TEST_F(StateMachineTest, Test2) {
    EXPECT_EQ(kInit, sm->GetState());
    sm->ProcessTimeout();
    EXPECT_EQ(kDown, sm->GetState());
    sm->ProcessTimeout();
    EXPECT_EQ(kDown, sm->GetState());
    sm->ProcessRemoteState(kDown);
    EXPECT_EQ(kInit, sm->GetState());
    sm->ProcessRemoteState(kInit);
    EXPECT_EQ(kUp, sm->GetState());
    sm->ProcessTimeout();
    EXPECT_EQ(kDown, sm->GetState());
}

static void ChangeCallback(const SessionKey &key, const BFDState &input,
                           boost::optional<BFDState> *output) {
    *output = input;
}

TEST_F(StateMachineTest, Test_Callback) {
    EventManagerThread evt(&evm);

    boost::optional<BFDState> state;
    boost::optional<ChangeCb> cb(boost::bind(&ChangeCallback, _1, _2, &state));
    sm->SetCallback(cb);

    EXPECT_EQ(kInit, sm->GetState());

    sm->ProcessTimeout();
    TASK_UTIL_EXPECT_TRUE(state.is_initialized());
    EXPECT_EQ(kDown, state.get());
    EXPECT_EQ(kDown, sm->GetState());
    state.reset();

    sm->ProcessTimeout();
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    EXPECT_FALSE(state.is_initialized());
    EXPECT_EQ(kDown, sm->GetState());

    sm->ProcessRemoteState(kDown);
    TASK_UTIL_EXPECT_TRUE(state.is_initialized());
    EXPECT_EQ(kInit, state.get());
    EXPECT_EQ(kInit, sm->GetState());
    state.reset();

    sm->ProcessRemoteState(kInit);
    TASK_UTIL_EXPECT_TRUE(state.is_initialized());
    EXPECT_EQ(kUp, state.get());
    EXPECT_EQ(kUp, sm->GetState());
    state.reset();

    sm->ProcessRemoteState(kUp);
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    EXPECT_FALSE(state.is_initialized());
    EXPECT_EQ(kUp, sm->GetState());

    sm->ProcessTimeout();
    TASK_UTIL_EXPECT_TRUE(state.is_initialized());
    EXPECT_EQ(kDown, state.get());
    EXPECT_EQ(kDown, sm->GetState());
    state.reset();
}

int main(int argc, char **argv) {
    LoggingInit();
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


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

<title>Uses of Class gui.ImgShowComponent</title>
<meta name="date" content="2014-09-24">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
gui.ImgShowComponent

Packages that use ImgShowComponent

Package
Description

gui

Uses of ImgShowComponent in gui

Methods in gui that return ImgShowComponent

Modifier and Type
Method and Description

static ImgShowComponent
ImgShowComponent.replaceImg(ImgShowComponent oldImg,
          int newIndex)

Methods in gui with parameters of type ImgShowComponent

Modifier and Type
Method and Description

static ImgShowComponent
ImgShowComponent.replaceImg(ImgShowComponent oldImg,
          int newIndex)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 */

#include "tomcrypt_private.h"

#ifdef LTC_CHACHA20POLY1305_MODE

/**
  Terminate a ChaCha20Poly1305 stream
  @param st      The ChaCha20Poly1305 state
  @param tag     [out] The destination for the MAC tag
  @param taglen  [in/out]  The length of the MAC tag
  @return CRYPT_OK on success
 */
int chacha20poly1305_done(chacha20poly1305_state *st, unsigned char *tag, unsigned long *taglen)
{
   unsigned char padzero[16] = { 0 };
   unsigned long padlen;
   unsigned char buf[16];
   int err;

   LTC_ARGCHK(st != NULL);

   padlen = 16 - (unsigned long)(st->ctlen % 16);
   if (padlen < 16) {
     if ((err = poly1305_process(&st->poly, padzero, padlen)) != CRYPT_OK) return err;
   }
   STORE64L(st->aadlen, buf);
   STORE64L(st->ctlen, buf + 8);
   if ((err = poly1305_process(&st->poly, buf, 16)) != CRYPT_OK)           return err;
   if ((err = poly1305_done(&st->poly, tag, taglen)) != CRYPT_OK)          return err;
   if ((err = chacha_done(&st->chacha)) != CRYPT_OK)                       return err;
   return CRYPT_OK;
}

#endif

/* ref:         HEAD -> develop */
/* git commit:  9c0d7085234bd6baba2ab8fd9eee62254599341c */
/* commit time: 2018-10-15 10:51:17 +0200 */


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Bastos</logradouro><bairro>Santa Maria</bairro><cidade>Aracaju</cidade><uf>SE</uf><cep>49043540</cep></feed>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <packaging>pom</packaging>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.bookkeeper.tests</groupId>
    <artifactId>integration-tests-base-groovy</artifactId>
    <version>4.8.0-SNAPSHOT</version>
    <relativePath>../integration-tests-base-groovy</relativePath>
  </parent>
  <groupId>org.apache.bookkeeper.tests.backward-compat</groupId>
  <artifactId>tests-parent</artifactId>
  <name>Apache BookKeeper :: Tests :: Backward Compatibility</name>
  <modules>
    <module>upgrade</module>
    <module>upgrade-direct</module>
    <module>hierarchical-ledger-manager</module>
    <module>hostname-bookieid</module>
    <module>recovery-no-password</module>
    <module>old-cookie-new-cluster</module>
    <module>current-server-old-clients</module>
    <module>yahoo-custom-version</module>
  </modules>
</project>


text:
require "helper"
require "lint/strings"

class TestDistributedCommandsOnStrings < Test::Unit::TestCase

  include Helper::Distributed
  include Lint::Strings

  def test_mget
    assert_raise Redis::Distributed::CannotDistribute do
      r.mget("foo", "bar")
    end
  end

  def test_mget_mapped
    assert_raise Redis::Distributed::CannotDistribute do
      r.mapped_mget("foo", "bar")
    end
  end

  def test_mset
    assert_raise Redis::Distributed::CannotDistribute do
      r.mset(:foo, "s1", :bar, "s2")
    end
  end

  def test_mset_mapped
    assert_raise Redis::Distributed::CannotDistribute do
      r.mapped_mset(:foo => "s1", :bar => "s2")
    end
  end

  def test_msetnx
    assert_raise Redis::Distributed::CannotDistribute do
      r.set("foo", "s1")
      r.msetnx(:foo, "s2", :bar, "s3")
    end
  end

  def test_msetnx_mapped
    assert_raise Redis::Distributed::CannotDistribute do
      r.set("foo", "s1")
      r.mapped_msetnx(:foo => "s2", :bar => "s3")
    end
  end

  def test_bitop
    return if version < "2.5.10"

    assert_raise Redis::Distributed::CannotDistribute do
      r.set("foo", "a")
      r.set("bar", "b")

      r.bitop(:and, "foo&bar", "foo", "bar")
    end
  end
end


text:
import unittest

from aiorest_ws.db.orm.sqlalchemy.fields import CharField
from aiorest_ws.db.orm.sqlalchemy.validators import ORMFieldValidator, \
    UniqueORMValidator
from aiorest_ws.db.orm.exceptions import ValidationError
from aiorest_ws.test.utils import override_settings

from sqlalchemy import Column, Integer, String

from tests.fixtures.sqlalchemy import SESSION
from tests.db.orm.sqlalchemy.base import Base, SQLAlchemyUnitTest

class TestORMFieldValidator(unittest.TestCase):

    class SQLAlchemyModel(object):
        email = CharField()

        def validate_email(self, key, address):
            assert '@' in address, '@ must be in email address'
            return address

    def test_validation_passed_sucessfully(self):
        validator = ORMFieldValidator(
            self.SQLAlchemyModel.validate_email, self.SQLAlchemyModel.email,
            'email'
        )
        self.assertIsNone(validator('admin@site.com'))

    def test_validation_raises_validation_error(self):
        validator = ORMFieldValidator(
            self.SQLAlchemyModel.validate_email, self.SQLAlchemyModel.email,
            'email'
        )

        with self.assertRaises(ValidationError):
            validator('wrong email address')

class TestUniqueORMValidator(SQLAlchemyUnitTest):

    class TableWithUniqueName(Base):
        __tablename__ = 'test_unique_field'
        id = Column(Integer, primary_key=True)
        name = Column(String(50), unique=True)

    tables = [TableWithUniqueName.__table__, ]

    @classmethod
    def setUpClass(cls):
        super(TestUniqueORMValidator, cls).setUpClass()
        cls.session = SESSION()
        cls.session.add_all([
            cls.TableWithUniqueName(name='Adam'),
            cls.TableWithUniqueName(name='Bob'),
            cls.TableWithUniqueName(name='Eve'),
        ])
        cls.session.commit()

    def test_filter_queryset(self):
        validator = UniqueORMValidator(
            self.TableWithUniqueName, 'name'
        )
        result_queryset = validator.filter_queryset(
            'Bob', self.session.query(validator.model)
        )
        self.assertEqual(result_queryset.count(), 1)
        self.assertEqual(result_queryset.value('name'), 'Bob')

    def test_exclude_current_instance(self):
        validator = UniqueORMValidator(
            self.TableWithUniqueName, 'name'
        )

        validator.instance = self.session.query(validator.model)\
            .filter(self.TableWithUniqueName.name == 'Adam')\
            .first()
        queryset = self.session.query(validator.model)
        self.assertEqual(queryset.count(), 3)
        self.assertEqual(
            validator.exclude_current_instance(queryset).count(), 2
        )

    def test_exclude_current_instance_not_applied(self):
        validator = UniqueORMValidator(
            self.TableWithUniqueName, 'name'
        )

        queryset = self.session.query(validator.model)
        self.assertEqual(queryset.count(), 3)
        self.assertEqual(
            validator.exclude_current_instance(queryset).count(), 3
        )

    @override_settings(SQLALCHEMY_SESSION=SESSION)
    def test_validation_passed_sucessfully(self):
        validator = UniqueORMValidator(
            self.TableWithUniqueName, 'name'
        )
        self.assertIsNone(validator('John'))

    @override_settings(SQLALCHEMY_SESSION=SESSION)
    def test_validation_raises_validation_error(self):
        validator = UniqueORMValidator(
            self.TableWithUniqueName, 'name'
        )

        with self.assertRaises(ValidationError):
            self.assertIsNone(validator('Eve'))


text:
package aQute.launcher;

import static java.nio.charset.StandardCharsets.UTF_8;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.SynchronousBundleListener;
import org.osgi.service.permissionadmin.PermissionAdmin;
import org.osgi.service.permissionadmin.PermissionInfo;

import aQute.lib.io.IO;

/**
 * Implements a permissionpolicy. It will tried to read a resource from the
 * bundle. This resource should have the following format:
 *
 *

 *  '('
 * permission-class [ '"' name-parameter '"' [ '"' action [ ','
 * action ] ... '"' ] ] ')' Or '#' *
 *

 *
 * Each valid line is translated into a PermissionInfo object and these objects
 * together form the permissions for a specific bundle. The class will also
 * attempt to read a file called "default.perm" from the current bundle that
 * will have the same format. This is used for the default permissions.
 *

 * If there is no permission admin service, this class does nothing relevant.
 */
public class SimplePermissionPolicy implements SynchronousBundleListener {
	static final String	DEFAULT_PERMISSION_RESOURCE	= "default.perm";
	BundleContext		context;
	List<Bundle>		bundles;
	PermissionInfo[]	defaultPermissions;
	final Launcher		launcher;

	/**
	 * Create a new permission policy. This will set the default permissions and
	 * the permissions for this bundle (if the resource is present).
	 */
	SimplePermissionPolicy(Launcher launcher, BundleContext context) throws Exception {
		this.launcher = launcher;
		this.context = context;
		bundles = new ArrayList<Bundle>();
		context.addBundleListener(this);
		PermissionAdmin permissionAdmin = getPermissionAdmin();
		if (permissionAdmin == null) /* no permission admin service */ {
			launcher.trace("no permission admin available => ! security");
			return;
		}
		// Set the default permissions.
		try (InputStream in = getClass().getResourceAsStream(DEFAULT_PERMISSION_RESOURCE)) {
			if (in != null) {
				PermissionInfo[] info = parse(in);
				permissionAdmin.setDefaultPermissions(info);
				launcher.trace("Found default permission resource %s", DEFAULT_PERMISSION_RESOURCE);
			} else {
				launcher.trace("No default permission resource %s", DEFAULT_PERMISSION_RESOURCE);
			}
		}
		//
		// Set this bundles permissions.
		//
		Bundle self = context.getBundle();
		setPermissions(self);
	}

	/**
	 * Sets the permissions of a bundle from a resource, if exists.
	 */
	public void setPermissions(Bundle bundle) {
		PermissionAdmin permissionAdmin = getPermissionAdmin();
		if (permissionAdmin == null) /* no permission admin service */ {
			return;
		}
		PermissionInfo[] info = getPermissions(bundle);
		if (info == null) {
			launcher.trace("Using default permissions for %s", bundle.getLocation());
			info = defaultPermissions;
		} else
			launcher.trace("For permissions inside bundle %s", bundle.getLocation());

		if (info != null && info.length > 0) {
			bundles.add(bundle);
			permissionAdmin.setPermissions(bundle.getLocation(), info);
		} else
			launcher.trace("No permissions for %s", bundle.getLocation());
	}

	/**
	 * Get the resource and parse it into PermissionInfo objects.
	 */
	public PermissionInfo[] getPermissions(Bundle bundle) {
		URL url = bundle.getEntry("/OSGI-INF/permissions.perm");
		if (url == null)
			url = bundle.getEntry("/OSGI-INF/permissions.perm".toUpperCase());

		PermissionInfo[] info = null;
		if (url != null)
			try {
				InputStream in = url.openStream();
				info = parse(in);
			} catch (IOException e) {
				System.err.println("Unable to read permission info for bundle  " + bundle.getLocation() + " " + e);
			}
		return info;
	}

	/**
	 * Parse a permission info file.
	 */
	public PermissionInfo[] parse(InputStream in) throws IOException {
		PermissionInfo[] info = null;
		if (in != null) {
			List<PermissionInfo> permissions = new ArrayList<PermissionInfo>();
			try (BufferedReader reader = IO.reader(in, UTF_8)) {
				String line;
				while ((line = reader.readLine()) != null) {
					line = line.trim();
					if ((line.length() == 0) || line.startsWith("#") || line.startsWith("//")) /* comments */
						continue;
					try {
						permissions.add(new PermissionInfo(line));
					} catch (IllegalArgumentException iae) {
						/* incorrectly encoded permission */
						System.err.println("Permission incorrectly encoded: " + line + " " + iae);
					}
				}
			}
			int size = permissions.size();
			if (size > 0) {
				info = permissions.toArray(new PermissionInfo[0]);
			}
		}
		return info;
	}

	/**
	 * Clear the permissions for a bundle.
	 */
	public void clearPermissions(Bundle bundle) {
		PermissionAdmin permissionAdmin = getPermissionAdmin();
		if (permissionAdmin == null) /* no permission admin service */
			return;
		if (bundles.remove(bundle)) {
			permissionAdmin.setPermissions(bundle.getLocation(), null);
		}
	}

	private PermissionAdmin getPermissionAdmin() {
		ServiceReference ref = context.getServiceReference(PermissionAdmin.class.getName());
		if (ref == null)
			return null;

		return (PermissionAdmin) context.getService(ref);
	}

	/**
	 * Event when a bundle has changed so we need to inspect if it is installed,
	 * and if so we need to set the permissions or remove it when it is
	 * uninstalled.
	 */
	public void bundleChanged(BundleEvent event) {
		Bundle bundle = event.getBundle();
		if (bundle.getBundleId() == 0) /* ignore the system bundle */
			return;
		int type = event.getType();
		switch (type) {
			case BundleEvent.INSTALLED :
			case BundleEvent.UPDATED :
				setPermissions(bundle);
				break;
			case BundleEvent.UNINSTALLED :
				clearPermissions(bundle);
				break;
		}
	}

	public void setDefaultPermissions(PermissionInfo defaultPermissions[]) {
		this.defaultPermissions = defaultPermissions;
	}
}


text:
from sqlalchemy import and_

from .common import Base, session_scope
from .player import Player
from .game import Game

class PlayerGame(Base):
    __tablename__ = 'player_games'
    __autoload__ = True

    HUMAN_READABLE = 'player game'

    STANDARD_ATTRS = [
        "position", "no", "goals", "assists", "primary_assists",
        "secondary_assists", "points", "plus_minus", "penalties", "pim",
        "toi_overall", "toi_pp", "toi_sh", "toi_ev", "avg_shift", "no_shifts",
        "shots_on_goal", "shots_blocked", "shots_missed", "hits",
        "giveaways", "takeaways", "blocks", "faceoffs_won", "faceoffs_lost",
        "on_ice_shots_on_goal", "on_ice_shots_blocked", "on_ice_shots_missed",
        "captain", "alternate_captain", "starting"
    ]

    def __init__(self, game_id, team_id, plr_id, data_dict):
        self.player_game_id = int("%d%02d%d" % (game_id, team_id, plr_id))
        self.game_id = game_id
        self.team_id = team_id
        self.player_id = plr_id
        for attr in self.STANDARD_ATTRS:
            if attr in data_dict:
                setattr(self, attr, data_dict[attr])
            else:
                if attr in ("captain", "alternate_captain", "starting"):
                    setattr(self, attr, False)
                # TODO: activate when database has been updated
                # elif attr in ("primary_assists", "secondary_assists"):
                #     setattr(self, attr, 0)
                else:
                    setattr(self, attr, None)

    @classmethod
    def find(self, game_id, player_id):
        with session_scope() as session:
            try:
                plr_game = session.query(PlayerGame).filter(
                    and_(
                        PlayerGame.game_id == game_id,
                        PlayerGame.player_id == player_id
                    )).one()
            except Exception as e:
                plr_game = None
            return plr_game

    @classmethod
    def get_players_in_game(self, game_id, positions=["C", "L", "R", "D"]):
        with session_scope() as session:
            game = Game.find_by_id(game_id)

            players_in_game = dict()

            for team_type in ['home', 'road']:
                team_id = getattr(game, "_".join((team_type, "team_id")))
                team_players_in_game = session.query(PlayerGame).filter(
                    and_(
                        PlayerGame.game_id == game_id,
                        PlayerGame.team_id == team_id,
                        PlayerGame.position.in_(positions)
                    )).all()
                team_dict = dict()
                team_dict['team_id'] = team_id
                team_dict['player_games'] = team_players_in_game

                players_in_game[team_type] = team_dict

        return players_in_game

    def get_player(self):
        return Player.find_by_id(self.player_id)

    def update(self, other):
        for attr in self.STANDARD_ATTRS:
            # assuring boolean attributes don't get set to null
            if attr in ['starting', 'captain', 'alternate_captain']:
                if getattr(other, attr) is True:
                    setattr(self, attr, True)
                else:
                    setattr(self, attr, False)
            # updating regular attributes
            else:
                setattr(self, attr, getattr(other, attr))

    # TODO: include further attributes
    def __eq__(self, other):
        return (
            (
                self.no, self.position, self.goals, self.assists,
                # self.primary_assists, self.secondary_assists,
                self.points, self.plus_minus, self.penalties, self.pim,
                self.toi_overall, self.toi_pp, self.toi_sh, self.toi_ev,
                self.avg_shift, self.no_shifts, self.shots_on_goal,
                self.shots_blocked, self.shots_missed, self.hits,
                self.giveaways, self.takeaways,
                self.blocks, self.faceoffs_won, self.faceoffs_lost,
                self.starting, self.captain, self.alternate_captain,
                # self.on_ice_shots_on_goal, self.on_ice_shots_missed,
                # self.on_ice_shots_blocked
                ) == (
                other.no, other.position, other.goals, other.assists,
                # other.primary_assists, other.secondary_assists,
                other.points, other.plus_minus, other.penalties, other.pim,
                other.toi_overall, other.toi_pp, other.toi_sh, other.toi_ev,
                other.avg_shift, other.no_shifts, other.shots_on_goal,
                other.shots_blocked, other.shots_missed, other.hits,
                other.giveaways, other.takeaways,
                other.blocks, other.faceoffs_won, other.faceoffs_lost,
                other.starting, other.captain, other.alternate_captain,
                # other.on_ice_shots_on_goal, other.on_ice_shots_missed,
                # other.on_ice_shots_blocked
                ))

    def __ne__(self, other):
        return not self == other

    def __str__(self):
        if not hasattr(self, 'player') or self.player is None:
            self.player = Player.find_by_id(self.player_id)
        return "%-40s %d G %d A %d Pts./%d PIM" % (
            self.player, self.goals, self.assists, self.points, self.pim)


text:
from __future__ import print_function

import argparse
import os
import sys

from scantrace import walk_logs

def execute(params):

    results = walk_logs.scan_for_template(params.paths,
                                          identity_files=params.identity_files,
                                          template_filename=params.template,
                                          verbose=params.verbose)

    # 1. Sort results by time
    res = sorted(results, key=lambda x: x['time'])

    # 2. Filter the results by tailnum
    if params.tailnum:
        res = res[-params.tailnum:]

    # 3. Filter the results by tailtime
    if params.tailtime:
        res = [x for x in res if x['time'] >= params.tailtime]

    # 4. Print exceptions or hashes
    if params.hash_only:

        # Only list of found hashes
        for r in res:
            print ("{} | {}".format(r['res_hash'], r['time']))

    elif params.uniq_only:

        # Unique errors
        uniq_res = {}

        for r in res:
            if r['res_hash'] not in uniq_res:
                uniq_res[r['res_hash']] = {
                    'count': 1,
                    'strings': r['strings'],
                }
            else:
                uniq_res[r['res_hash']]['count'] += 1

        for ur in sorted(uniq_res, key=lambda x: uniq_res[x]['count'], reverse=True):

            print ("{} | count={}".format(ur, uniq_res[ur]['count']))
            for s in uniq_res[ur]['strings']:
                for store in s['cur_query']['store']:
                    print("  " + s['results'][store])
            print("")

    else:
        # Original errors
        for r in res:
            print ("{} - '{}' (hash: {}):".format(r['time'], r['logfile'], r['res_hash']))
            for s in r['strings']:
                if params.verbose:
                    print ("{}".format(s['line']).rstrip())
                else:
                    if 'error_string' in s['results']:
                        print ("{}".format(s['line']).rstrip())

def get_params(args):

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter,
        description="Search for tracebacks in log files. "
                    "For additional help, use with -h/--help option.\n"
                    "Example usage:\n\n"
                    "$ scantrace /var/log/nova /var/log/neutron\n"
                    "$ scantrace /var/log --verbose  # Show processed filenames and completed error messages\n"
                    "$ scantrace root@ctl01:/var/log root@ctl02:/var/log root@ctl03:/var/log -i ~/.ssh/id_rsa  # Scan /var/log on remote nodes\n"
                    "$ scantrace /var/log --uniq --tailtime '2017-03-27 16:10' # Show only uniq errors appeared after the specified datetime\n"
    )
    parser.add_argument('--template', dest='template', help='template with search patterns')
    parser.add_argument('-i', dest='identity_files',
                        help=('For SSH connections, selects a file from which \n'
                              'the identity (private key) for public key \n'
                              'authentication is read. It is possible to have \n'
                              'multiple -i options.'),
                        action='append')
    parser.add_argument('--tailnum', dest='tailnum',
                        help='Print only latest TAILNUM results.', default=0, type=int)
    parser.add_argument('--tailtime', dest='tailtime',
                        help=('Print results starting from date and time \n'
                              'specified in the format "YYYY-MM-DD hh:mm:ss". \n'
                              'The specified string can contain only part of \n'
                              'parameters, for example only "2017-03", it will \n'
                              'be used for string comparison.'),
                        default=None)
    parser.add_argument('--verbose', dest='verbose', action='store_const', const=True,
                        help='Show verbosed output.', default=False)
    parser.add_argument('--hash', dest='hash_only', action='store_const', const=True,
                        help='Show only hashes of errors.', default=False)
    parser.add_argument('--uniq', dest='uniq_only', action='store_const', const=True,
                        help='Show only unique errors without datetime (in stripped condition).',
                        default=False)
    parser.add_argument('paths', help='Paths to search for *.log files.', nargs='+')

    if len(args) == 0:
        args = ['-h']
    return parser.parse_args(args)

def main(args=None):
    if args is None:
        args = sys.argv[1:]

    params = get_params(args)
    execute(params)


text:
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using UnityEditor;

public static class SerializedParent
{
    public static object GetParent(SerializedProperty prop)
    {
        var path = prop.propertyPath.Replace(".Array.data[", "[");
        object obj = prop.serializedObject.targetObject;
        var elements = path.Split('.');
        foreach (var element in elements.Take(elements.Length - 1))
        {
            if (element.Contains("["))
            {
                var elementName = element.Substring(0, element.IndexOf("["));
                var index = Convert.ToInt32(element.Substring(element.IndexOf("[")).Replace("[", "").Replace("]", ""));
                obj = GetValue(obj, elementName, index);
            }
            else
            {
                obj = GetValue(obj, element);
            }
        }
        return obj;
    }

    public static object GetValue(object source, string name)
    {
        if (source == null)
            return null;
        var type = source.GetType();
        var f = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
        if (f == null)
        {
            var p = type.GetProperty(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
            if (p == null)
                return null;
            return p.GetValue(source, null);
        }
        return f.GetValue(source);
    }

    public static object GetValue(object source, string name, int index)
    {
        var enumerable = GetValue(source, name) as IEnumerable;
        var enm = enumerable.GetEnumerator();
        while (index-- >= 0)
            enm.MoveNext();
        return enm.Current;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <title></title>

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <link rel="stylesheet" href="https://unpkg.com/font-awesome@4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="lib/reveal/css/reveal.css">
    <link rel="stylesheet" href="lib/reveal/lib/css/zenburn.css">

    <link rel="stylesheet" href="css/slide_style.css">

    <link rel="stylesheet" href="lib/reveal/lib/css/zenburn.css">

                # CSS Selectors and Specificity

                ### Structure vs. Presentation

                HTML intended to define structure of document

                **NOT** intended for presentation/styling

                ### CSS

                * Cascading Style Sheets
                * rules that tell a browser how to display an element

                <textarea data-template>
### CSS

```css
selector {
    property: value;
    property: value;
    property: value;
}
```
</textarea>

                <textarea data-template>
### Element Selector

Select all HTML elements of the same type using the tag name

```css
p { ... }
```

```css
h1 { ... }
```

```css
article { ... }
```
</textarea>

                <textarea data-template>
### id Selector

Select elements based on the value of their `id` attribute

```css
#heading1 { ... }
```

will match only the first `<h1>..</h1>` element below:

```html
<h1 id="heading1">Heading 1</h1>
<h1 id="heading2">Heading 2</h1>
```
</textarea>

                <textarea data-template>
### class Selector

Select elements based on the value of their `class` attribute

```css
.centre { ... }
```

will match everything with a class of `centre`:

```html
<p class="centre">...</p>
<h1 class="centre">...</h1>
```
</textarea>

                ### pseudo-class selector

                * Can add 'pseudo-classes' to our selectors
                * Allow us to select very specific elements, or elements under certain conditions

See the Pen Pseudo-Class 1 by Martin Chorley (@martinjc) on CodePen.

See the Pen Pseudo-Class 2 by Martin Chorley (@martinjc) on CodePen.

                ### pseudo-element selector

                * Can add 'pseudo-elements' to our selectors
                * Allow us to select very specific parts of elements, or content before or after elements

See the Pen Pseudo-Element by Martin Chorley (@martinjc) on CodePen.

                <textarea data-template>
### **Cascading** Style Sheets

* Styling rules for an element 'cascade' from many sources
    * more than one CSS rule may apply to an element
* Stylesheets are read from top to bottom
    * styles declared in one part of a stylesheet can override previously declared styles
</textarea>

                ### Inheritance

                * Elements within other HTML elements usually **inherit** some of the **CSS rules** applied to their **parents**
                * An element's **own style takes priority** over style rules inherited from it's parents

                ### Specificity

                * If a stylesheet contains multiple selectors that match to an element, how do we know which is applied?
                * **Specificity**
                * Each type of selector has a **specificity weight**
                * Add the weights together - highest weight wins!

                ### Specificity Weights

                * ID selector (`#id`): 1-0-0
                * Class selector (`.class`) or pseduo-class (`:pseudo-class`): 0-1-0
                * Element selector (`element`) or pseudo-element (`::pseudo-element`): 0-0-1

                ### Calculating Specificity

                * Count the number of ID selectors = **a**
                * Count the number of class and pseudo-class selectors = **b**
                * Count the number of element and pseudo-element selectors = **c**
                * Specificity of rule = a-b-c

                ### Browser Default

                * Some browsers have their own 'default' way of styling HTML elements if no CSS is specified
                * CSS resets can be used to 'normalise' presentation across browsers
                * http://cssreset.com/what-is-a-css-reset/

                # CSS

                * Cascading Style Sheet
                * Apply layout, presentation and styling to our html
                * Consists of rules made of selectors and declarations
                * Select by element type, class, id
                * Combine selectors to select more specific elements
                * Many different CSS properties to apply