text:
package com.lowagie.text.pdf;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.lowagie.text.Image;

/**
 * PdfImage is a PdfStream containing an image-Dictionary and -stream.
 */

public class PdfImage extends PdfStream {

    private static final int TRANSFERSIZE = 4096;
    // membervariables

    /** This is the PdfName of the image. */
    private PdfName name = null;

    // constructor

    /**
     * Constructs a PdfImage-object.
     *
     * @param image the Image-object
     * @param name the PdfName for this image
     * @throws BadPdfFormatException on error
     */

    PdfImage(final Image image, final String name, final PdfIndirectReference maskRef) throws BadPdfFormatException {
        super();
        this.name = new PdfName(name);
        put(PdfName.TYPE, PdfName.XOBJECT);
        put(PdfName.SUBTYPE, PdfName.IMAGE);
        put(PdfName.WIDTH, new PdfNumber(image.getWidth()));
        put(PdfName.HEIGHT, new PdfNumber(image.getHeight()));
        if (image.getLayer() != null) {
			put(PdfName.OC, image.getLayer().getRef());
		}
        if (image.isMask() && (image.getBpc() == 1 || image.getBpc() > 0xff)) {
			put(PdfName.IMAGEMASK, PdfBoolean.PDFTRUE);
		}
        if (maskRef != null) {
            if (image.isSmask()) {
				put(PdfName.SMASK, maskRef);
			} else {
				put(PdfName.MASK, maskRef);
			}
        }
        if (image.isMask() && image.isInverted()) {
			put(PdfName.DECODE, new PdfLiteral("[1 0]"));
		}
        if (image.isInterpolation()) {
			put(PdfName.INTERPOLATE, PdfBoolean.PDFTRUE);
		}
        InputStream is = null;
        try {
            // Raw Image data
            if (image.isImgRaw()) {
                // will also have the CCITT parameters
                final int colorspace = image.getColorspace();
                final int transparency[] = image.getTransparency();
                if (transparency != null && !image.isMask() && maskRef == null) {
                    String s = "[";
                    for (final int element : transparency) {
						s += element + " ";
					}
                    s += "]";
                    put(PdfName.MASK, new PdfLiteral(s));
                }
                this.bytes = image.getRawData();
                put(PdfName.LENGTH, new PdfNumber(this.bytes.length));
                final int bpc = image.getBpc();
                if (bpc > 0xff) {
                    if (!image.isMask()) {
						put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
					}
                    put(PdfName.BITSPERCOMPONENT, new PdfNumber(1));
                    put(PdfName.FILTER, PdfName.CCITTFAXDECODE);
                    final int k = bpc - Image.CCITTG3_1D;
                    final PdfDictionary decodeparms = new PdfDictionary();
                    if (k != 0) {
						decodeparms.put(PdfName.K, new PdfNumber(k));
					}
                    if ((colorspace & Image.CCITT_BLACKIS1) != 0) {
						decodeparms.put(PdfName.BLACKIS1, PdfBoolean.PDFTRUE);
					}
                    if ((colorspace & Image.CCITT_ENCODEDBYTEALIGN) != 0) {
						decodeparms.put(PdfName.ENCODEDBYTEALIGN, PdfBoolean.PDFTRUE);
					}
                    if ((colorspace & Image.CCITT_ENDOFLINE) != 0) {
						decodeparms.put(PdfName.ENDOFLINE, PdfBoolean.PDFTRUE);
					}
                    if ((colorspace & Image.CCITT_ENDOFBLOCK) != 0) {
						decodeparms.put(PdfName.ENDOFBLOCK, PdfBoolean.PDFFALSE);
					}
                    decodeparms.put(PdfName.COLUMNS, new PdfNumber(image.getWidth()));
                    decodeparms.put(PdfName.ROWS, new PdfNumber(image.getHeight()));
                    put(PdfName.DECODEPARMS, decodeparms);
                }
                else {
                    switch(colorspace) {
                        case 1:
                            put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                            if (image.isInverted()) {
								put(PdfName.DECODE, new PdfLiteral("[1 0]"));
							}
                            break;
                        case 3:
                            put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                            if (image.isInverted()) {
								put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0]"));
							}
                            break;
                        case 4:
                        default:
                            put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                            if (image.isInverted()) {
								put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0 1 0]"));
							}
                    }
                    final PdfDictionary additional = image.getAdditional();
                    if (additional != null) {
						putAll(additional);
					}
                    if (image.isMask() && (image.getBpc() == 1 || image.getBpc() > 8)) {
						remove(PdfName.COLORSPACE);
					}
                    put(PdfName.BITSPERCOMPONENT, new PdfNumber(image.getBpc()));
                    if (image.isDeflated()) {
						put(PdfName.FILTER, PdfName.FLATEDECODE);
					} else {
                        flateCompress(image.getCompressionLevel());
                    }
                }
                return;
            }
            // GIF, JPEG or PNG
            String errorID;
            if (image.getRawData() == null){
                is = image.getUrl().openStream();
                errorID = image.getUrl().toString();
            }
            else{
                is = new java.io.ByteArrayInputStream(image.getRawData());
                errorID = "Byte array";
            }
            switch(image.type()) {
                case Image.JPEG:
                    put(PdfName.FILTER, PdfName.DCTDECODE);
                    switch(image.getColorspace()) {
                        case 1:
                            put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                            break;
                        case 3:
                            put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                            break;
                        default:
                            put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                            if (image.isInverted()) {
                                put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0 1 0]"));
                            }
                    }
                    put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
                    if (image.getRawData() != null){
                        this.bytes = image.getRawData();
                        put(PdfName.LENGTH, new PdfNumber(this.bytes.length));
                        return;
                    }
                    this.streamBytes = new ByteArrayOutputStream();
                    transferBytes(is, this.streamBytes, -1);
                    break;
                case Image.JPEG2000:
                    put(PdfName.FILTER, PdfName.JPXDECODE);
                    if (image.getColorspace() > 0) {
                        switch(image.getColorspace()) {
                            case 1:
                                put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                                break;
                            case 3:
                                put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                                break;
                            default:
                                put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                        }
                        put(PdfName.BITSPERCOMPONENT, new PdfNumber(image.getBpc()));
                    }
                    if (image.getRawData() != null){
                        this.bytes = image.getRawData();
                        put(PdfName.LENGTH, new PdfNumber(this.bytes.length));
                        return;
                    }
                    this.streamBytes = new ByteArrayOutputStream();
                    transferBytes(is, this.streamBytes, -1);
                    break;
                case Image.JBIG2:
                    put(PdfName.FILTER, PdfName.JBIG2DECODE);
                    put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                    put(PdfName.BITSPERCOMPONENT, new PdfNumber(1));
                    if (image.getRawData() != null){
                        this.bytes = image.getRawData();
                        put(PdfName.LENGTH, new PdfNumber(this.bytes.length));
                        return;
                    }
                    this.streamBytes = new ByteArrayOutputStream();
                    transferBytes(is, this.streamBytes, -1);
                	break;
                default:
                    throw new BadPdfFormatException(errorID + " is an unknown Image format.");
            }
            put(PdfName.LENGTH, new PdfNumber(this.streamBytes.size()));
        }
        catch(final IOException ioe) {
            throw new BadPdfFormatException(ioe.getMessage());
        }
        finally {
            if (is != null) {
                try{
                    is.close();
                }
                catch (final Exception ee) {
                    // empty on purpose
                }
            }
        }
    }

    /**
     * Returns the PdfName of the image.
     *
     * @return		the name
     */

    PdfName name() {
        return this.name;
    }

    private static void transferBytes(final InputStream in, final OutputStream out, int len) throws IOException {
        final byte buffer[] = new byte[TRANSFERSIZE];
        if (len < 0) {
			len = 0x7ffffff;
		}
        int size;
        while (len != 0) {
            size = in.read(buffer, 0, Math.min(len, TRANSFERSIZE));
            if (size < 0) {
				return;
			}
            out.write(buffer, 0, size);
            len -= size;
        }
    }

}


text:
from neutron_lib.api.definitions import qos as qos_apidef
from neutron_lib.callbacks import events as callbacks_events
from neutron_lib.callbacks import registry as callbacks_registry
from neutron_lib.callbacks import resources as callbacks_resources
from neutron_lib import exceptions as lib_exc
from neutron_lib.services.qos import constants as qos_consts

from neutron.common import exceptions as n_exc
from neutron.db import api as db_api
from neutron.db import db_base_plugin_common
from neutron.extensions import qos
from neutron.objects import base as base_obj
from neutron.objects import network as network_object
from neutron.objects import ports as ports_object
from neutron.objects.qos import policy as policy_object
from neutron.objects.qos import qos_policy_validator as checker
from neutron.objects.qos import rule_type as rule_type_object
from neutron.services.qos.drivers import manager

class QoSPlugin(qos.QoSPluginBase):
    """Implementation of the Neutron QoS Service Plugin.

    This class implements a Quality of Service plugin that provides quality of
    service parameters over ports and networks.

    """
    supported_extension_aliases = [qos_apidef.ALIAS,
                                   'qos-bw-limit-direction',
                                   'qos-default',
                                   'qos-rule-type-details']

    __native_pagination_support = True
    __native_sorting_support = True

    def __init__(self):
        super(QoSPlugin, self).__init__()
        self.driver_manager = manager.QosServiceDriverManager()

        callbacks_registry.subscribe(
            self._validate_create_port_callback,
            callbacks_resources.PORT,
            callbacks_events.PRECOMMIT_CREATE)
        callbacks_registry.subscribe(
            self._validate_update_port_callback,
            callbacks_resources.PORT,
            callbacks_events.PRECOMMIT_UPDATE)
        callbacks_registry.subscribe(
            self._validate_update_network_callback,
            callbacks_resources.NETWORK,
            callbacks_events.PRECOMMIT_UPDATE)

    def _get_ports_with_policy(self, context, policy):
        networks_ids = policy.get_bound_networks()
        ports_with_net_policy = ports_object.Port.get_objects(
            context, network_id=networks_ids)

        # Filter only this ports which don't have overwritten policy
        ports_with_net_policy = [
            port for port in ports_with_net_policy if
            port.qos_policy_id is None
        ]

        ports_ids = policy.get_bound_ports()
        ports_with_policy = ports_object.Port.get_objects(
            context, id=ports_ids)
        return list(set(ports_with_policy + ports_with_net_policy))

    def _validate_create_port_callback(self, resource, event, trigger,
                                       **kwargs):
        context = kwargs['context']
        port_id = kwargs['port']['id']
        port = ports_object.Port.get_object(context, id=port_id)
        network = network_object.Network.get_object(context,
                                                    id=port.network_id)

        policy_id = port.qos_policy_id or network.qos_policy_id
        if policy_id is None:
            return

        policy = policy_object.QosPolicy.get_object(context, id=policy_id)
        self.validate_policy_for_port(policy, port)

    def _validate_update_port_callback(self, resource, event, trigger,
                                       **kwargs):
        context = kwargs['context']
        original_policy_id = kwargs['original_port'].get(
            qos_consts.QOS_POLICY_ID)
        policy_id = kwargs['port'].get(qos_consts.QOS_POLICY_ID)

        if policy_id is None or policy_id == original_policy_id:
            return

        updated_port = ports_object.Port.get_object(
            context, id=kwargs['port']['id'])
        policy = policy_object.QosPolicy.get_object(context, id=policy_id)

        self.validate_policy_for_port(policy, updated_port)

    def _validate_update_network_callback(self, resource, event, trigger,
                                          **kwargs):
        context = kwargs['context']
        original_network = kwargs['original_network']
        updated_network = kwargs['network']

        original_policy_id = original_network.get(qos_consts.QOS_POLICY_ID)
        policy_id = updated_network.get(qos_consts.QOS_POLICY_ID)

        if policy_id is None or policy_id == original_policy_id:
            return

        policy = policy_object.QosPolicy.get_object(context, id=policy_id)
        ports = ports_object.Port.get_objects(
                context, network_id=updated_network['id'])
        # Filter only this ports which don't have overwritten policy
        ports = [
            port for port in ports if port.qos_policy_id is None
        ]
        self.validate_policy_for_ports(policy, ports)

    def validate_policy(self, context, policy):
        ports = self._get_ports_with_policy(context, policy)
        self.validate_policy_for_ports(policy, ports)

    def validate_policy_for_ports(self, policy, ports):
        for port in ports:
            self.validate_policy_for_port(policy, port)

    def validate_policy_for_port(self, policy, port):
        for rule in policy.rules:
            if not self.driver_manager.validate_rule_for_port(rule, port):
                raise n_exc.QosRuleNotSupported(rule_type=rule.rule_type,
                                                port_id=port['id'])

    @db_base_plugin_common.convert_result_to_dict
    def create_policy(self, context, policy):
        """Create a QoS policy.

        :param context: neutron api request context
        :type context: neutron_lib.context.Context
        :param policy: policy data to be applied
        :type policy: dict

        :returns: a QosPolicy object
        """
        # NOTE(dasm): body 'policy' contains both tenant_id and project_id
        # but only latter needs to be used to create QosPolicy object.
        # We need to remove redundant keyword.
        # This cannot be done in other place of stacktrace, because neutron
        # needs to be backward compatible.
        policy['policy'].pop('tenant_id', None)
        policy_obj = policy_object.QosPolicy(context, **policy['policy'])
        with db_api.context_manager.writer.using(context):
            policy_obj.create()
            self.driver_manager.call(qos_consts.CREATE_POLICY_PRECOMMIT,
                                     context, policy_obj)

        self.driver_manager.call(qos_consts.CREATE_POLICY, context, policy_obj)

        return policy_obj

    @db_base_plugin_common.convert_result_to_dict
    def update_policy(self, context, policy_id, policy):
        """Update a QoS policy.

        :param context: neutron api request context
        :type context: neutron.context.Context
        :param policy_id: the id of the QosPolicy to update
        :param policy_id: str uuid
        :param policy: new policy data to be applied
        :type policy: dict

        :returns: a QosPolicy object
        """
        policy_data = policy['policy']
        with db_api.context_manager.writer.using(context):
            policy_obj = self._get_policy_obj(context, policy_id)
            policy_obj.update_fields(policy_data, reset_changes=True)
            policy_obj.update()
            self.driver_manager.call(qos_consts.UPDATE_POLICY_PRECOMMIT,
                                     context, policy_obj)

        self.driver_manager.call(qos_consts.UPDATE_POLICY,
                                 context, policy_obj)

        return policy_obj

    def delete_policy(self, context, policy_id):
        """Delete a QoS policy.

        :param context: neutron api request context
        :type context: neutron.context.Context
        :param policy_id: the id of the QosPolicy to delete
        :type policy_id: str uuid

        :returns: None
        """
        with db_api.context_manager.writer.using(context):
            policy = policy_object.QosPolicy(context)
            policy.id = policy_id
            policy.delete()
            self.driver_manager.call(qos_consts.DELETE_POLICY_PRECOMMIT,
                                     context, policy)

        self.driver_manager.call(qos_consts.DELETE_POLICY,
                                 context, policy)

    def _get_policy_obj(self, context, policy_id):
        """Fetch a QoS policy.

        :param context: neutron api request context
        :type context: neutron.context.Context
        :param policy_id: the id of the QosPolicy to fetch
        :type policy_id: str uuid

        :returns: a QosPolicy object
        :raises: n_exc.QosPolicyNotFound
        """
        obj = policy_object.QosPolicy.get_object(context, id=policy_id)
        if obj is None:
            raise n_exc.QosPolicyNotFound(policy_id=policy_id)
        return obj

    @db_base_plugin_common.filter_fields
    @db_base_plugin_common.convert_result_to_dict
    def get_policy(self, context, policy_id, fields=None):
        """Get a QoS policy.

        :param context: neutron api request context
        :type context: neutron.context.Context
        :param policy_id: the id of the QosPolicy to update
        :type policy_id: str uuid

        :returns: a QosPolicy object
        """
        return self._get_policy_obj(context, policy_id)

    @db_base_plugin_common.filter_fields
    @db_base_plugin_common.convert_result_to_dict
    def get_policies(self, context, filters=None, fields=None, sorts=None,
                     limit=None, marker=None, page_reverse=False):
        """Get QoS policies.

        :param context: neutron api request context
        :type context: neutron.context.Context
        :param filters: search criteria
        :type filters: dict

        :returns: QosPolicy objects meeting the search criteria
        """
        filters = filters or dict()
        pager = base_obj.Pager(sorts, limit, page_reverse, marker)
        return policy_object.QosPolicy.get_objects(context, _pager=pager,
                                                   **filters)

    @db_base_plugin_common.filter_fields
    @db_base_plugin_common.convert_result_to_dict
    def get_rule_type(self, context, rule_type_name, fields=None):
        if not context.is_admin:
            raise lib_exc.NotAuthorized()
        return rule_type_object.QosRuleType.get_object(rule_type_name)

    @db_base_plugin_common.filter_fields
    @db_base_plugin_common.convert_result_to_dict
    def get_rule_types(self, context, filters=None, fields=None,
                       sorts=None, limit=None,
                       marker=None, page_reverse=False):
        if not filters:
            filters = {}
        return rule_type_object.QosRuleType.get_objects(**filters)

    def supported_rule_type_details(self, rule_type_name):
        return self.driver_manager.supported_rule_type_details(rule_type_name)

    @property
    def supported_rule_types(self):
        return self.driver_manager.supported_rule_types

    @db_base_plugin_common.convert_result_to_dict
    def create_policy_rule(self, context, rule_cls, policy_id, rule_data):
        """Create a QoS policy rule.

        :param context: neutron api request context
        :type context: neutron.context.Context
        :param rule_cls: the rule object class
        :type rule_cls: a class from the rule_object (qos.objects.rule) module
        :param policy_id: the id of the QosPolicy for which to create the rule
        :type policy_id: str uuid
        :param rule_data: the rule data to be applied
        :type rule_data: dict

        :returns: a QoS policy rule object
        """
        rule_type = rule_cls.rule_type
        rule_data = rule_data[rule_type + '_rule']

        with db_api.autonested_transaction(context.session):
            # Ensure that we have access to the policy.
            policy = self._get_policy_obj(context, policy_id)
            checker.check_bandwidth_rule_conflict(policy, rule_data)
            rule = rule_cls(context, qos_policy_id=policy_id, **rule_data)
            rule.create()
            policy.obj_load_attr('rules')
            self.validate_policy(context, policy)
            self.driver_manager.call(qos_consts.UPDATE_POLICY_PRECOMMIT,
                                     context, policy)

        self.driver_manager.call(qos_consts.UPDATE_POLICY, context, policy)

        return rule

    @db_base_plugin_common.convert_result_to_dict
    def update_policy_rule(self, context, rule_cls, rule_id, policy_id,
            rule_data):
        """Update a QoS policy rule.

        :param context: neutron api request context
        :type context: neutron.context.Context
        :param rule_cls: the rule object class
        :type rule_cls: a class from the rule_object (qos.objects.rule) module
        :param rule_id: the id of the QoS policy rule to update
        :type rule_id: str uuid
        :param policy_id: the id of the rule's policy
        :type policy_id: str uuid
        :param rule_data: the new rule data to update
        :type rule_data: dict

        :returns: a QoS policy rule object
        """
        rule_type = rule_cls.rule_type
        rule_data = rule_data[rule_type + '_rule']

        with db_api.autonested_transaction(context.session):
            # Ensure we have access to the policy.
            policy = self._get_policy_obj(context, policy_id)
            # Ensure the rule belongs to the policy.
            checker.check_bandwidth_rule_conflict(policy, rule_data)
            policy.get_rule_by_id(rule_id)
            rule = rule_cls(context, id=rule_id)
            rule.update_fields(rule_data, reset_changes=True)
            rule.update()
            policy.obj_load_attr('rules')
            self.validate_policy(context, policy)
            self.driver_manager.call(qos_consts.UPDATE_POLICY_PRECOMMIT,
                                     context, policy)

        self.driver_manager.call(qos_consts.UPDATE_POLICY, context, policy)

        return rule

    def delete_policy_rule(self, context, rule_cls, rule_id, policy_id):
        """Delete a QoS policy rule.

        :param context: neutron api request context
        :type context: neutron.context.Context
        :param rule_cls: the rule object class
        :type rule_cls: a class from the rule_object (qos.objects.rule) module
        :param rule_id: the id of the QosPolicy Rule to delete
        :type rule_id: str uuid
        :param policy_id: the id of the rule's policy
        :type policy_id: str uuid

        :returns: None
        """
        with db_api.autonested_transaction(context.session):
            # Ensure we have access to the policy.
            policy = self._get_policy_obj(context, policy_id)
            rule = policy.get_rule_by_id(rule_id)
            rule.delete()
            policy.obj_load_attr('rules')
            self.driver_manager.call(qos_consts.UPDATE_POLICY_PRECOMMIT,
                                     context, policy)

        self.driver_manager.call(qos_consts.UPDATE_POLICY, context, policy)

    @db_base_plugin_common.filter_fields
    @db_base_plugin_common.convert_result_to_dict
    def get_policy_rule(self, context, rule_cls, rule_id, policy_id,
                        fields=None):
        """Get a QoS policy rule.

        :param context: neutron api request context
        :type context: neutron.context.Context
        :param rule_cls: the rule object class
        :type rule_cls: a class from the rule_object (qos.objects.rule) module
        :param rule_id: the id of the QoS policy rule to get
        :type rule_id: str uuid
        :param policy_id: the id of the rule's policy
        :type policy_id: str uuid

        :returns: a QoS policy rule object
        :raises: n_exc.QosRuleNotFound
        """
        with db_api.autonested_transaction(context.session):
            # Ensure we have access to the policy.
            self._get_policy_obj(context, policy_id)
            rule = rule_cls.get_object(context, id=rule_id)
        if not rule:
            raise n_exc.QosRuleNotFound(policy_id=policy_id, rule_id=rule_id)
        return rule

    # TODO(QoS): enforce rule types when accessing rule objects
    @db_base_plugin_common.filter_fields
    @db_base_plugin_common.convert_result_to_dict
    def get_policy_rules(self, context, rule_cls, policy_id, filters=None,
                         fields=None, sorts=None, limit=None, marker=None,
                         page_reverse=False):
        """Get QoS policy rules.

        :param context: neutron api request context
        :type context: neutron.context.Context
        :param rule_cls: the rule object class
        :type rule_cls: a class from the rule_object (qos.objects.rule) module
        :param policy_id: the id of the QosPolicy for which to get rules
        :type policy_id: str uuid

        :returns: QoS policy rule objects meeting the search criteria
        """
        with db_api.autonested_transaction(context.session):
            # Ensure we have access to the policy.
            self._get_policy_obj(context, policy_id)
            filters = filters or dict()
            filters[qos_consts.QOS_POLICY_ID] = policy_id
            pager = base_obj.Pager(sorts, limit, page_reverse, marker)
            return rule_cls.get_objects(context, _pager=pager, **filters)

redpajama_set_name: RedPajamaGithub


text:
"""
Django settings for coffeedapp project.

Generated by 'django-admin startproject' using Django 1.8.3.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
MAIN_DIR = os.path.dirname(os.path.dirname(__file__))

ON_HEROKU = os.environ.get('ON_HEROKU')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 's)rhw!d&t&%88w%=_8ro^)2y@$e4sxjt+@&o&cbvll4&y0+po-'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'coffeedapp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(MAIN_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'coffeedapp.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

if ON_HEROKU == 1:
    # Parse database configuration from $DATABASE_URL
    import dj_database_url
    DATABASES['default'] = dj_database_url.config()
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers
ALLOWED_HOSTS = ['*']

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'

TEMPLATE_DIRS = (
    os.path.join(MAIN_DIR, 'templates'),
    )

STATICFILES_DIRS = (
    os.path.join(MAIN_DIR, 'static'),
    )

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_S3_FORCE_HTTP_URL = True
AWS_QUERYSTRING_AUTH = False
AWS_SECRET_ACCESS_KEY = os.environ.get('AWSSecretKey')
AWS_ACCESS_KEY_ID = os.environ.get('AWSAccessKeyId')

AWS_STORAGE_BUCKET_NAME = 'ompcoffeedmt'


text:
package vogar;

/**
 * TestProperties is a common class of constants shared between the
 * Vogar on the host and TestRunner classes potentially running
 * on other devices.
 */
final public class TestProperties {

    /**
     * The name of the test properties file within the {@code .jar} file.
     */
    public static final String FILE = "test.properties";

    /**
     * Name of the property giving the class name or package name of the test to be performed.
     */
    public static final String TEST_CLASS_OR_PACKAGE = "testClassOrPackage";

    /**
     * Name of the property giving the test's name, such as {@code
     * java.math.BigDecimal.PowTests}.
     */
    public static final String QUALIFIED_NAME = "qualifiedName";

    /**
     * Port to accept monitor connections on.
     */
    public static final String MONITOR_PORT = "monitorPort";

    /**
     * Integer timeout in seconds
     */
    public static final String TIMEOUT = "timeout";

    /**
     * Profile enabled?
     */
    public static final String PROFILE = "profile";

    /**
     * Profile frame depth
     */
    public static final String PROFILE_DEPTH = "profileDepth";

    /**
     * Profile interval in milliseconds
     */
    public static final String PROFILE_INTERVAL = "profileInterval";

    /**
     * Profile output file
     */
    public static final String PROFILE_FILE = "profileFile";

    /**
     * Profile thread group instead of just single thread (where supported)
     */
    public static final String PROFILE_THREAD_GROUP = "profileThreadGroup";

    private TestProperties() {}
}


text:
package de.ifcore.hdv.converter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import de.ifcore.hdv.converter.data.AccountClass;
import de.ifcore.hdv.converter.data.AccountsPerArea;
import de.ifcore.hdv.converter.data.BalanceItem;
import de.ifcore.hdv.converter.data.BalanceValue;
import de.ifcore.hdv.converter.data.Category;
import de.ifcore.hdv.converter.data.InOutProduct;
import de.ifcore.hdv.converter.data.KeyAccount;
import de.ifcore.hdv.converter.data.MergedData;

public class DataMocks {

	public static SortedSet<Category> mockCategories() {
		SortedSet<Category> categories = new TreeSet<>();
		categories.add(new Category(31, "Cat3"));
		categories.add(new Category(21, "Alpha"));
		categories.add(new Category(11, "Cat1"));
		return categories;
	}

	public static List<MinMaxProduct> mockAccounts() {
		List<MinMaxProduct> accounts = new ArrayList<>();
		accounts.add(new MinMaxProduct(121, "label1"));
		accounts.add(new MinMaxProduct(122, "label2"));
		accounts.add(new MinMaxProduct(221, "label3"));
		accounts.add(new MinMaxProduct(321, "label4"));
		accounts.add(new MinMaxProduct(421, "label5"));
		return accounts;
	}

	public static List<BalanceItem> mockBalanceItems() {
		return Arrays.asList(mockBalanceItem("05111001", "ort", "0100", "test1", 1),
				mockBalanceItem("05111002", "ort", "1000", "test2", 2),
				mockBalanceItem("05111003", "ort", "2000", "test3", 3));
	}

	public static BalanceItem mockBalanceItem(String ks, String areaLabel, String no, String label, long value) {
		BalanceItem bi = new BalanceItem(ks, areaLabel, label);
		bi.setCurrent(new BalanceValue(no, Long.valueOf(value)));
		return bi;
	}

	public static SortedSet<AccountClass> mockMainAccountClasses() {
		return new TreeSet<>(Arrays.asList(new AccountClass("0", "imma"), new AccountClass("1", "finan"),
				new AccountClass("2", "eigen"), new AccountClass("3", "verb")));
	}

	public static SortedSet<AccountClass> mockSubAccountClasses() {
		return new TreeSet<>(Arrays.asList(new AccountClass("01", "test1"), new AccountClass("10", "test2"),
				new AccountClass("20", "test3")));
	}

	public static List<String[]> mockAccountCsvData() {
		return Arrays.asList(new String[] { "GENESIS-Tabelle: Temporär" }, new String[] {
				"Auszahlungen insgesamt nach Produktgruppen", "", "", "", "" }, new String[] {
				"- Land, Gemeinden, Gemeindeverbände - Jahr", "", "", "", "" }, new String[] {
				"Finanzrechnungsstatistik der Gemeinden/GV", "", "", "", "" }, new String[] { "Auszahlungen (EUR)", "",
				"", "", "" }, new String[] { "Auszahlungskonten: Auszahlungen insgesamt", "", "", "", "" },
				new String[] { "", "", "", "", "Jahr" }, new String[] { "", "", "", "", "2009" }, new String[] { "05",
						"Nordrhein-Westfalen", "111", "Verwaltungssteuerung und Service", "7950660525" }, new String[] {
						"05", "Nordrhein-Westfalen", "121", "Statistik und Wahlen", "72717205" }, new String[] { "05",
						"Nordrhein-Westfalen", "122", "Ordnungsangelegenheiten", "929640752" }, new String[] { "05",
						"Nordrhein-Westfalen", "126", "Brandschutz", "706599561" }, new String[] { "05978040",
						"Werne, Stadt", "611", "Steuern, allg. Zuweisungen u. allg. Umlagen", "18525219" },
				new String[] { "05978040", "Werne, Stadt", "612", "Sonstige allgemeine Finanzwirtschaft", "12678523" },
				new String[] { "05978040", "Werne, Stadt", "999", "Summe aller Produktgruppen", "70535060" });
	}

	public static MergedData mockMergedData() {
		Map<Integer, InOutProduct> productsPerArea = new HashMap<>();
		productsPerArea.put(100, new InOutProduct(100));
		List<AccountsPerArea> areas = Arrays
				.asList(new AccountsPerArea("areakey", "arealabel", 10, 20, productsPerArea));
		Map<Integer, MinMaxProduct> products = new HashMap<>();
		products.put(100, new MinMaxProduct(1234, "label"));
		Map<Integer, List<Integer>> tree = new HashMap<>();
		tree.put(1, Arrays.asList(100));
		Set<KeyAccount> productLabels = new HashSet<>();
		productLabels.add(new KeyAccount(100, "Product_100"));
		Set<KeyAccount> incomeLabels = new HashSet<>();
		Set<KeyAccount> spendingsLabels = new HashSet<>();
		return new MergedData(areas, products, tree, productLabels, incomeLabels, spendingsLabels);
	}
}


text:
package experiment

import (
	"fmt"
	"reflect"

	"github.com/samsalisbury/psyringe"
)

// OptionalFieldHandler validates that all injectable fields in a struct value
// must be filled
// unless they are marked optional by a field tag `inject:"optional"`.
func OptionalFieldHandler() psyringe.NoValueForStructFieldFunc {
	return func(parentType string, field reflect.StructField) error {
		if field.Tag.Get("inject") == "optional" {
			return nil
		}
		return fmt.Errorf("no constructor or value of type %s available (for field %s.%s)",
			field.Type, parentType, field.Name)
	}
}


text:
package com.google.cloud.firestore;

import com.google.protobuf.Timestamp;
import java.util.Objects;
import javax.annotation.Nonnull;
import org.threeten.bp.Instant;

/** Preconditions that can be used to restrict update() calls. */
public final class Precondition {

  /** An empty Precondition that adds no enforcements */
  public static final Precondition NONE = new Precondition(null, null);

  private Boolean exists;
  private Instant updateTime;

  private Precondition(Boolean exists, Instant updateTime) {
    this.exists = exists;
    this.updateTime = updateTime;
  }

  /**
   * Creates a Precondition that enforces that a document exists.
   *
   * @param exists Whether the document should exist.
   * @return A new Precondition
   */
  // TODO: Make public once backend supports verify.
  @Nonnull
  static Precondition exists(Boolean exists) {
    return new Precondition(exists, null);
  }

  /**
   * Creates a Precondition that enforces that the existing document was written at the specified
   * time.
   *
   * @param updateTime The write time to enforce on the existing document.
   * @return A new Precondition
   */
  @Nonnull
  public static Precondition updatedAt(Instant updateTime) {
    return new Precondition(null, updateTime);
  }

  boolean isEmpty() {
    return exists == null && updateTime == null;
  }

  boolean hasExists() {
    return exists != null;
  }

  com.google.firestore.v1beta1.Precondition toPb() {
    com.google.firestore.v1beta1.Precondition.Builder precondition =
        com.google.firestore.v1beta1.Precondition.newBuilder();

    if (exists != null) {
      precondition.setExists(exists);
    }

    if (updateTime != null) {
      Timestamp.Builder timestamp = Timestamp.newBuilder();
      timestamp.setSeconds(updateTime.getEpochSecond());
      timestamp.setNanos(updateTime.getNano());
      precondition.setUpdateTime(timestamp.build());
    }

    return precondition.build();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    Precondition that = (Precondition) o;
    return Objects.equals(exists, that.exists) && Objects.equals(updateTime, that.updateTime);
  }

  @Override
  public int hashCode() {
    return Objects.hash(exists, updateTime);
  }
}


text:
require 'spec_helper'

provider_class = Puppet::Type.type(:rabbitmq_queue).provider(:rabbitmqadmin)
describe provider_class do
  let(:resource) do
    Puppet::Type::Rabbitmq_queue.new(
      name: 'test@/',
      durable: :true,
      auto_delete: :false,
      arguments: {}
    )
  end
  let(:provider) { provider_class.new(resource) }

  it 'returns instances' do
    provider_class.expects(:rabbitmqctl).with('list_vhosts', '-q').returns <<-EOT
/
EOT
    provider_class.expects(:rabbitmqctl).with('list_queues', '-q', '-p', '/', 'name', 'durable', 'auto_delete', 'arguments').returns <<-EOT
test  true  false []
test2 true  false [{"x-message-ttl",342423},{"x-expires",53253232},{"x-max-length",2332},{"x-max-length-bytes",32563324242},{"x-dead-letter-exchange","amq.direct"},{"x-dead-letter-routing-key","test.routing"}]
EOT
    instances = provider_class.instances
    expect(instances.size).to eq(2)
  end

  it 'calls rabbitmqadmin to create' do
    provider.expects(:rabbitmqadmin).with('declare', 'queue', '--vhost=/', '--user=guest', '--password=guest', '-c', '/etc/rabbitmq/rabbitmqadmin.conf', 'name=test', 'durable=true', 'auto_delete=false', 'arguments={}')
    provider.create
  end

  it 'calls rabbitmqadmin to destroy' do
    provider.expects(:rabbitmqadmin).with('delete', 'queue', '--vhost=/', '--user=guest', '--password=guest', '-c', '/etc/rabbitmq/rabbitmqadmin.conf', 'name=test')
    provider.destroy
  end

  context 'specifying credentials' do
    let(:resource) do
      Puppet::Type::Rabbitmq_queue.new(
        name: 'test@/',
        durable: 'true',
        auto_delete: 'false',
        arguments: {},
        user: 'colin',
        password: 'secret'
      )
    end
    let(:provider) { provider_class.new(resource) }

    it 'calls rabbitmqadmin to create' do
      provider.expects(:rabbitmqadmin).with('declare', 'queue', '--vhost=/', '--user=colin', '--password=secret', '-c', '/etc/rabbitmq/rabbitmqadmin.conf', 'name=test', 'durable=true', 'auto_delete=false', 'arguments={}')
      provider.create
    end
  end
end


text:
package com.tyrfing.games.id17.gui.technology;

import com.tyrfing.games.id17.EmpireFrameListener;
import com.tyrfing.games.id17.gui.TabGUI;
import com.tyrfing.games.id17.gui.holding.OverviewGUI;
import com.tyrfing.games.id17.gui.war.ArmyBuilderGUI;
import com.tyrfing.games.id17.gui.war.FormationWindow;
import com.tyrfing.games.id17.houses.House;
import com.tyrfing.games.id17.networking.RequestDisplayData;
import com.tyrfing.games.id17.technology.Technology;
import com.tyrfing.games.id17.technology.TechnologyTree;
import com.tyrfing.games.id17.world.World;
import com.tyrlib2.gui.IEventListener;
import com.tyrlib2.gui.ImageBox;
import com.tyrlib2.gui.ScaledVector2;
import com.tyrlib2.gui.Window;
import com.tyrlib2.gui.WindowEvent;
import com.tyrlib2.gui.WindowEvent.WindowEventType;
import com.tyrlib2.gui.WindowManager;
import com.tyrlib2.math.Vector2;
import com.tyrlib2.util.Color;

public class TechnologyGUI extends TabGUI<House> {

	private ImageBox[] icons;
	private TechArrow[][] techArrows;

	public TechnologyGUI() {
		super("TECH");

		Window bg = WindowManager.getInstance().createImageBox("TECH_TREE", OverviewGUI.HOLDING_INFO_POS, "MAIN_GUI", "PAPER2", ArmyBuilderGUI.FORMATION_SIZE);
		main.addChild(bg);

		TechnologyTree t = World.getInstance().techTreeSet.trees[0];
		String treeName = "TECH/" + t.name;
		icons = new ImageBox[t.techs.length];
		techArrows = new TechArrow[t.techs.length][];

		for (int i = 0; i < t.techs.length; ++i) {
			final Technology tech = t.techs[i];
			icons[i] = (ImageBox) WindowManager.getInstance().createImageBox(treeName + tech.name, new Vector2((tech.iconPos.get().x+0.05f) * WINDOW_SIZE.x, tech.iconPos.get().y * WINDOW_SIZE.y), "TECH", tech.name, FormationWindow.ICON_SIZE_SMALL);
			icons[i].setSizeRelaxation(new ScaledVector2(2.5f, 2.5f, 2).get());
			WindowManager.getInstance().addTextTooltip(icons[i], tech.name);
			icons[i].addEventListener(WindowEventType.TOUCH_DOWN, new IEventListener() {
				@Override
				public void onEvent(WindowEvent event) {
					TechMail.createMail(tech, displayed);
				}
			});

			if (tech.pre != null) {
				techArrows[i] = new TechArrow[tech.pre.length];
				for (int j = 0; j < tech.pre.length; ++j) {
					try {
					TechArrow arrow = new TechArrow(icons[tech.pre[j].ID], icons[i], bg, this, tech, tech.pre[j]);
					techArrows[i][j] = arrow;
					World.getInstance().getUpdater().addItem( arrow );
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			} else {
				techArrows[i] = new TechArrow[1];
				TechArrow arrow = new TechArrow(icons[i], bg, this, tech);
				techArrows[i][0] = arrow;
				World.getInstance().getUpdater().addItem( arrow );
			}
		}

		for (int i = 0; i < t.techs.length; ++i) {
			bg.addChild(icons[i]);
		}
	}

//_ /\
//:/  \)

	@Override
	public void display() {
		//sigil.setAtlasRegion(displayed.getName());
		TechnologyTree t = World.getInstance().techTreeSet.trees[0];

		for (int i = 0; i < t.techs.length; ++i) {
			icons[i].setReceiveTouchEvents(true);
		}

		for (int i = 0; i < t.techs.length; ++i) {
			boolean reqMet = true;
			if (t.techs[i].pre != null) {
				for (int j = 0; j < t.techs[i].pre.length; ++j) {
					if (!displayed.hasResearched(t.techs[i].pre[j])) {
						reqMet = false;
						break;
					}
				}
			}

			if (t.techs[i].pre != null) {
				if (displayed.hasResearched(t.techs[i])) {
					for (int j = 0; j < t.techs[i].pre.length; ++j) {
						techArrows[i][j].mat.setProgress(1);
					}
				} else if (displayed.techProject != null && displayed.techProject.tech == t.techs[i]) {
					for (int j = 0; j < t.techs[i].pre.length; ++j) {
						techArrows[i][j].mat.setProgress(displayed.techProject.getProgress());
					}
				} else {
					for (int j = 0; j < t.techs[i].pre.length; ++j) {
						techArrows[i][j].mat.setProgress(0);
					}
				}
			}

			if (reqMet) {
				icons[i].getMaterial().setColor(new Color(1, 1, 1, 1));
			} else {
				icons[i].getMaterial().setColor(new Color(0.5f, 0.5f, 0.5f, 1));
			}
		}

		if (EmpireFrameListener.MAIN_FRAME.getNetwork().isClient()) {
			EmpireFrameListener.MAIN_FRAME.getNetwork().broadcast(new RequestDisplayData(RequestDisplayData.TECH_DATA,
																						 (short) displayed.id));
		}

	}

	@Override
	public void hide() {
		super.hide();

		TechnologyTree t = World.getInstance().techTreeSet.trees[0];
		for (int i = 0; i < t.techs.length; ++i) {
			icons[i].setReceiveTouchEvents(false);
		}

	}

	public House getDisplayed() {
		return displayed;
	}

	@Override
	public boolean isFinished() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void update() {
		// TODO Auto-generated method stub

	}

}


text:
import os

import logging
import unittest
import time
from TestUtils import TestUtilsMixin, ROOT, ROOT_PASSWORD, ACCUMULO_HOME
from subprocess import Popen as BasePopen, PIPE

log = logging.getLogger('test.shell')

class ShellTest(TestUtilsMixin,unittest.TestCase):
    """Start a clean accumulo, and test different shell functions.
    Some other shell functions are tests in the systemp and tablep tests"""

    command_list = [ "help", "tables", "table", "createtable", "deletetable",
                    "insert", "scan", "user", "users", "delete",
                    "flush", "config", "setiter", "deleteiter", "whoami", "debug",
                    "tablepermissions", "userpermissions", "authenticate", "createuser",
                    "dropuser", "passwd", "setauths", "getauths", "grant", "revoke" ]

    def setUp(self):
        TestUtilsMixin.setUp(self)

    def runTest(self):
        self.badLoginTest()
        self.setIterTest()
        self.setScanIterTest()
        self.iteratorsTest()
        self.createtableTestSplits()
        self.createtableTestCopyConfig()
        self.classpathTest()
        self.tableTest()
        self.configTest()
        self.helpTest()
        self.tablesTest()
        self.createtableTest()
        self.deletetableTest()
        self.scanTest()
        self.insertTest()
        self.flushTest()
        self.whoamiTest()
        self.getauthsTest()

    def badLoginTest(self, **opts):
      log.debug("Running shell with bad password")
      handle = self.runOn(self.masterHost(), [self.accumulo_sh(), 'shell', '-u', ROOT, '-p', "ThisWouldBeATerriblePasswordToHave"], stdin=PIPE, **opts)
      handle.communicate("quit\n")
      self.failUnless(handle.returncode != 0, "Was able to create a shell with bad credentials")

    def setIterTest(self):
        input = 'setiter -t setitertest -n mymax -scan -p 10 -class org.apache.accumulo.core.iterators.user.MaxCombiner\n\ncf\n\nSTRING\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.failUnless(out.find("TableNotFoundException") >= 0,
                        "Was able to setiter a table that didn't exist")
        input = 'createtable setitertest\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'table setitertest\nsetiter -n mymax -scan -p 10 -class org.apache.accumulo.core.iterators.user.MaxCombiner\n\ncf1\n\nSTRING\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'setiter -t setitertest -n mymax -scan -p 10 -class org.apache.accumulo.core.iterators.user.MinCombiner\n\ncf2\n\nSTRING\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.failUnless(out.find("IllegalArgumentException") >= 0,
                        "Was able to configure same iter name twice")
        input = 'setiter -t setitertest -n mymin -scan -p 10 -class org.apache.accumulo.core.iterators.user.MinCombiner\n\ncf2\n\nSTRING\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.failUnless(out.find("IllegalArgumentException") >= 0,
                        "Was able to configure same priority twice")
        input = 'setiter -t setitertest -n mymin -scan -p 11 -class org.apache.accumulo.core.iterators.user.MinCombiner\n\ncf2\n\nSTRING\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'table setitertest\ninsert row1 cf1 cq 10\ninsert row1 cf1 cq 30\ninsert row1 cf1 cq 20\ninsert row1 cf2 cq 10\ninsert row1 cf2 cq 30\nscan -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failIf(out.find("row1 cf1:cq []    30") == -1 or out.find("row1 cf2:cq []    10") == -1,
                        "SetIter Failed:  combining failed")

    def setScanIterTest(self):
        input = 'createtable setscanitertest\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'table setscanitertest\ninsert row cf cq val1\ninsert row cf cq val2\nscan -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failIf(out.find("row cf:cq []    val1") == 1 or out.find("row cf:cq []    val2") == -1,
                        "SetScanIter Failed:  default versioning failed")
        input = 'setscaniter -t setscanitertest -n vers -p 20 -class org.apache.accumulo.core.iterators.user.VersioningIterator\n2\ntable setscanitertest\nscan -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failIf(out.find("row cf:cq []    val1") == -1 or out.find("row cf:cq []    val2") == -1,
                        "SetScanIter Failed:  versioning override failed")
        input = 'table setscanitertest\nsetscaniter -n vers -p 20 -class org.apache.accumulo.core.iterators.user.VersioningIterator\n2\nscan -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failIf(out.find("row cf:cq []    val1") == -1 or out.find("row cf:cq []    val2") == -1,
                        "SetScanIter Failed:  set on current table failed")
        input = 'setscaniter -t setscanitertest -n vers -p 20 -class org.apache.accumulo.core.iterators.user.VersioningIterator\n2\ndeletescaniter -t setscanitertest -n vers\ntable setscanitertest\nscan -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failIf(out.find("row cf:cq []    val1") == 1 or out.find("row cf:cq []    val2") == -1,
                        "SetScanIter Failed:  deletescaniter (single) failed")
        input = 'table setscanitertest\nsetscaniter -n vers -p 20 -class org.apache.accumulo.core.iterators.user.VersioningIterator\n2\ndeletescaniter -n vers\ntable setscanitertest\nscan -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failIf(out.find("row cf:cq []    val1") == 1 or out.find("row cf:cq []    val2") == -1,
                        "SetScanIter Failed:  deletescaniter on current table failed")
        input = 'setscaniter -t setscanitertest -n vers -p 20 -class org.apache.accumulo.core.iterators.user.VersioningIterator\n2\ndeletescaniter -t setscanitertest -a\ntable setscanitertest\nscan -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failIf(out.find("row cf:cq []    val1") == 1 or out.find("row cf:cq []    val2") == -1,
                        "SetScanIter Failed:  deletescaniter (all) failed")
        input = 'setscaniter -t setscanitertest -n vers -p 20 -class org.apache.accumulo.core.iterators.user.VersioningIterator\n2\nsetscaniter -t setscanitertest -n vers -p 10 -class org.apache.accumulo.core.iterators.user.VersioningIterator\n2\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failUnless(out.find("IllegalArgumentException") >= 0,
                        "Was able to configure same iter name twice")
        input = 'setscaniter -t setscanitertest -n vers -p 20 -class org.apache.accumulo.core.iterators.user.VersioningIterator\n2\nsetscaniter -t setscanitertest -n vers2 -p 20 -class org.apache.accumulo.core.iterators.user.VersioningIterator\n2\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failUnless(out.find("IllegalArgumentException") >= 0,
                        "Was able to configure same priority twice")

    def classpathTest(self):
        input = 'classpath\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        lines = out.split()
        for line in lines:
            self.failUnless(line.startswith("file:") >= 0 or
                            line.startswith("List of classpath items are:") >= 0,
                            "Classpath command: Command didn't work or classpath items were formatted incorrectly");

    def iteratorsTest(self):
        input = 'createtable filtertest\nsetiter -t filtertest -n myfilter -scan -p 10 -class org.apache.accumulo.core.iterators.user.AgeOffFilter\n\n4000\n\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'config -t filtertest -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failIf(out.find("table.iterator.scan.myfilter.opt.ttl") == -1,
                        "Config Failed:  Iterator doesn't exist in the config")
        input = 'table filtertest\ninsert foo a b c\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'table filtertest\nscan\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failUnless(out.find("foo a:b") >= 0, "Scan Failed:  Entries don't exist")
        # Wait until ageoff happens
        self.sleep(5)
        input = 'table filtertest\nscan\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failUnless(out.find("foo a:b") == -1, "Scan Failed:  Entries didn't ageoff")
        input = 'deleteiter -t filtertest -n myfilter -scan\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'config filtertest -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failUnless(out.find("table.iterator.scan.myfilter.opt.ttl") == -1,
                        "Config Failed:  Iterator doesn't exist in the config")
        input = 'table filtertest\nsetiter -n myfilter -scan -p 10 -class org.apache.accumulo.core.iterators.user.AgeOffFilter\n\n4000\n\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'config -t filtertest -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failIf(out.find("table.iterator.scan.myfilter.opt.ttl") == -1,
                        "Config Failed:  Iterator doesn't exist in the config")
        input = 'table filtertest\ndeleteiter -n myfilter -scan\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'config filtertest -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failUnless(out.find("table.iterator.scan.myfilter.opt.ttl") == -1,
                        "Config Failed:  Iterator doesn't exist in the config")

    def configTest(self):
        cf_option = "table.scan.max.memory"
        cf_value = "9361234"
        input = 'createtable t1\nconfig -t t1 -s %s=%s -np\n' % (cf_option, cf_value)
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'config -t t1 -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        lines = out.split("\n")
        foundConfig = False
        foundOverride = False
        for line in lines:
            if foundConfig:
                self.failUnless(line.startswith("table") and line.find("@override") >= 0 and line.find(cf_value),
                                 "Error setting or retrieving config values")
                foundOverride = True
                break
            if line.find(cf_option) >= 0:
                foundConfig = True
        self.failUnless(foundConfig and foundOverride, "Did not find the configuration that was set")
        input = 'config -t t1 -d %s -np\n' % cf_option
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'config -t t1 -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        lines = out.split("\n")
        for line in lines:
            self.failIf(line.find(cf_value) >= 0, "Could not delete the value")

    def helpTest(self):
        commands = self.command_list
        input = "help -np\n"
        startLooking = False
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        lines = out.split("\n")
        for line in lines:
            line = line.rstrip()
            if startLooking:
                command = line.split("-")[0].rstrip()
                if not command.startswith("\t") and command in commands:
                    commands.remove(command)
            else:
                if line[-10:] == "> help -np":
                    startLooking = True
        log.debug("missing commands:" + ", ".join(commands))
        self.failIf(len(commands) > 0, "help command doesn't cover all the commands")

    def tablesTest(self):
        input = "tables\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failUnless(out.find("!METADATA"),
                        "tables command does not return the correct tables" )

    def tableTest(self):
        input = "table !METADATA\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failUnless(out.split("\n")[-1].find("!METADATA >"),
                        "table command does not switch context to the table")
        input = "table null\n"
        out2, err2, code2 = self.rootShell(self.masterHost(), input)
        self.failUnless(out2.find("TableNotFoundException") >= 0,
                        "Was able to connect to a table that didn't exist")

    def createtableTest(self):
        input = "createtable test_table\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        input = "tables\n"
        out2, err2, code2 = self.rootShell(self.masterHost(), input)
        self.processResult(out2, err2, code2)
        self.failUnless(out2.find("test_table"),
                        "createtable command did not correctly create the table")
        self.failUnless(out.split("\n")[-1].find("test_table >"),
                        "createtable command did not switch contexts to the new table")

    def createtableTestCopyConfig(self):
        input = 'createtable cttest\nsetiter -t cttest -n myfilter -scan -p 10 -class org.apache.accumulo.core.iterators.user.AgeOffFilter\n\n2000\n\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'config -t cttest -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failIf(out.find("table.iterator.scan.myfilter.opt.ttl") == -1,
                        "CreateTable Failed:  Iterator doesn't exist in the config")
        input = 'createtable cttest2 -cc cttest\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        input = 'config -t cttest2 -np\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        self.failIf(out.find("table.iterator.scan.myfilter.opt.ttl") == -1,
                        "CreateTable Failed:  Iterator doesn't exist in the config after copying the table config")

    def createtableTestSplits(self):
        splits_file = os.path.join(ACCUMULO_HOME, 'test','system','bench','lib','splits')
        input = 'createtable splits_test -sf %s\n' % splits_file
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'table !METADATA\nscan\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        splitTestID = self.getTableId('splits_test')
        splits = []
        for a in out.split("\n"):
            if a.startswith(splitTestID+';'):
                split = a.split()[0].split(";",1)[1]
                splits.append(split)
        self.failUnless(len(splits) == 190*5,
                        "CreateTable Failed:  Splits were not created correctly")
        input = 'createtable test_splits -cs splits_test\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'table !METADATA\nscan\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        testSplitsID = self.getTableId('test_splits')
        for a in out.split("\n"):
            if a.startswith(testSplitsID+';'):
                split = a.split()[0].split(";",1)[1]
                splits.remove(split)
        self.failUnless(len(splits) == 0,
                        "CreateTable Failed:  Splits were not copied correctly")
        input = 'createtable test_splits_2\naddsplits one\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'table !METADATA\nscan\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        splitTestID = self.getTableId('test_splits_2')
        splits = []
        for a in out.split("\n"):
            if a.startswith(splitTestID+';'):
                split = a.split()[0].split(";",1)[1]
                splits.append(split)
        log.debug(splits)
        self.failUnless(len(splits) == 1*5 and splits[0] == 'one',
                        "CreateTable Failed:  Splits were not created correctly (add one split)")
        input = 'createtable test_splits_3\naddsplits -sf %s\n' % splits_file
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        input = 'table !METADATA\nscan\n'
        out,err,code = self.rootShell(self.masterHost(),input)
        self.processResult(out, err, code)
        splitTestID = self.getTableId('test_splits_3')
        splits = []
        for a in out.split("\n"):
            if a.startswith(splitTestID+';'):
                split = a.split()[0].split(";",1)[1]
                splits.append(split)
        self.failUnless(len(splits) == 190*5,
                        "CreateTable Failed:  Splits were not created correctly (addsplits from file)")

    def deletetableTest(self):
        create = "createtable test_delete_table\n"
        out, err, code = self.rootShell(self.masterHost(), create)
        self.processResult(out, err, code)
        self.failUnless(out.split("\n")[-1].find("test_table >"),
                        "createtable command did not switch contexts to the new table")
        delete = "deletetable -t test_delete_table\ny\n"
        out, err, code = self.rootShell(self.masterHost(), delete)
        self.processResult(out, err, code)
        input = "tables\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failIf(out.find("test_delete_table") >= 0,
                        "deletetable command did not delete the table" )
        delete = "createtable test_delete_table1\ncreatetable test_delete_table2\ndeletetable -p test_delete_table.* -f\n"
        out, err, code = self.rootShell(self.masterHost(), delete)
        self.processResult(out, err, code)
        input = "tables\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failIf(out.find("test_delete_table") >= 0,
                        "deletetable -p command did not delete the tables" )
        delete = "createtable test_delete_table\ndeletetable\ny\n"
        out, err, code = self.rootShell(self.masterHost(), delete)
        self.processResult(out, err, code)
        input = "tables\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failIf(out.find("test_delete_table") >= 0,
                        "deletetable command did not delete the current table" )
        delete = "createtable test_delete_table\ndeletetable test_delete_table -f\n"
        out, err, code = self.rootShell(self.masterHost(), delete)
        self.processResult(out, err, code)
        input = "tables\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failIf(out.find("test_delete_table") >= 0,
                        "deletetable command did not delete the current table" )

    def scanTest(self):
        input = "createtable test_scan_table\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        input = "table test_scan_table\ninsert one two three four\nscan\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failUnless(out.find("one") >= 0 and out.find("two") >= 0 and
                        out.find("three") >= 0 and out.find("four") >= 0 and
                        out.find("one") < out.find("two") <
                        out.find("three") < out.find("four"),
                                    "scan command did not return the correct results")
        input = "table test_scan_table\ndelete one two three\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        input = "table test_scan_table\nscan\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failIf((out.find("one") >= 0) or (out.find("two") >= 0) or (out.find("three") >= 0),
                                    "scan command did not return the correct results")
        input = "table test_scan_table\ninsert one two three four -ts 42\nscan\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failUnless(out.find("one") >= 0 and out.find("two") >= 0 and
                        out.find("three") >= 0 and out.find("four") >= 0 and
                        out.find("one") < out.find("two") <
                        out.find("three") < out.find("four"),
                                    "scan command did not return the correct results")
        input = "table test_scan_table\ndelete one two three -ts 42\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        input = "table test_scan_table\nscan\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failIf(out.find("one") >= 0 or out.find("two") >= 0 or out.find("three") >= 0,
                                    "scan command did not return the correct results")

    def insertTest(self):
        input = "createtable test_insert_table\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        input = "table test_insert_table\ninsert a b c d\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)

    def flushTest(self):
        input = "flush -t !METADATA -w\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failUnless(out.find("Flush of table !METADATA completed") >= 0,
                        "flush command did not flush the tables")
        input = "flush !METADATA -w\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failUnless(out.find("Flush of table !METADATA completed") >= 0,
                        "flush command did not flush the tables")
        input = "table !METADATA\nflush -w\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failUnless(out.find("Flush of table !METADATA completed") >= 0,
                        "flush command did not flush the tables")

    def whoamiTest(self):
        input = "whoami\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failUnless(out.find("root") >= 0,
                        "whoami command did not return the correct values")
    def getauthsTest(self):
        passwd = 'secret'
        input = "createuser test_user\n%s\n%s\nsetauths -u test_user -s 12,3,4\n" % (passwd, passwd)
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        input = "getauths -u test_user\n"
        out, err, code = self.rootShell(self.masterHost(), input)
        self.processResult(out, err, code)
        self.failUnless(out.find("3") >= 0 and out.find("4") >= 0 and out.find("12") >= 0,
                        "getauths command did not return the correct values")

def suite():
    result = unittest.TestSuite()
    result.addTest(ShellTest())
    return result


text:
<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">
	<parent>
		<artifactId>gully</artifactId>
		<groupId>com.thehellings.gully</groupId>
		<version>0.9-SNAPSHOT</version>
		<relativePath>..</relativePath>
	</parent>
	<modelVersion>4.0.0</modelVersion>
	<artifactId>css</artifactId>
	<packaging>jar</packaging>
	<name>css</name>

	<description>
		Basic CSS files, the ability to serve them, and the ability to minify them on-the-fly.
	</description>

	<dependencies>
		<dependency>
			<groupId>com.thehellings.gully</groupId>
			<artifactId>gully-server</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>com.thehellings</groupId>
			<artifactId>agglutinator</artifactId>
			<version>${agglutinator-version}</version>
		</dependency>
	</dependencies>
</project>


text:
rm mincircle.sqlite

geoc vector mincircle -i naturalearth.gpkg -l places -o mincircle.sqlite -r envelope
geoc vector mincircles -i naturalearth.gpkg -l countries -o mincircle.sqlite -r envelopes

geoc vector defaultstyle --color "#0066FF" -o 0.15 -g linestring > mincircle.sld
geoc vector defaultstyle --color navy -o 0.15 -g polygon > mincircles.sld

geoc map draw -f vector_mincircle.png -b "-180,-90,180,90" \
    -l "layertype=layer file=naturalearth.gpkg layername=ocean style=ocean.sld" \
    -l "layertype=layer file=naturalearth.gpkg layername=countries style=countries.sld" \
    -l "layertype=layer dbtype=spatialite database=mincircle.sqlite layername=envelope style=mincircle.sld" \
    -l "layertype=layer dbtype=spatialite database=mincircle.sqlite layername=envelopes style=mincircles.sld"


text:
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */

import { expect } from 'chai';
import nock from 'nock';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';

import { SERVER_URL } from '../../../utils/config';
import * as DUCKS from './auth.js';

describe('Auth Actions:', () => {

  describe('Signup Actions:', () => {
    afterEach(() => {
      nock.cleanAll();
    });

    beforeEach(() => {
      localStorage.removeItem('token');
    });

    it('signupSuccess should create SIGNUP_SUCCESS action', () => {
      expect(DUCKS.signupSuccess('0121f44d1b62d950280a5df81eb474e0ab33725c72c6b685f0da1ecd8f090d56', {})).to.eql({
        type: DUCKS.SIGNUP_SUCCESS,
        payload: {
          token: '0121f44d1b62d950280a5df81eb474e0ab33725c72c6b685f0da1ecd8f090d56',
          user: {}
        }
      });
    });

    it('signupFailure should create SIGNUP_FAILURE action', () => {
      expect(DUCKS.signupFailure(404, 'Not Found')).to.eql({
        type: DUCKS.SIGNUP_FAILURE,
        payload: {
          errorCode: 404,
          errorMessage: 'Not Found'
        }
      });
    });

    it('signupRequest should create SIGNUP_REQUEST action', () => {
      expect(DUCKS.signupRequest()).to.eql({
        type: DUCKS.SIGNUP_REQUEST
      });
    });

    it('signup should create SIGNUP_REQUEST, SIGNUP_SUCCESS, ' +
    'actions when API returns 200', (done) => {
      const expectedActions = [
        {
          type: DUCKS.SIGNUP_REQUEST
        },
        {
          type: DUCKS.SIGNUP_SUCCESS,
          payload: {
            token: '0121f44d1b62d950280a5df81eb474e0ab33725c72c6b685f0da1ecd8f090d56',
            user: {}
          }
        }
      ];

      nock(SERVER_URL)
      .post('/api/accounts/register/')
      .reply(200, {
        token: '0121f44d1b62d950280a5df81eb474e0ab33725c72c6b685f0da1ecd8f090d56',
        user: {}
      });

      const middlewares = [thunk];
      const mockStore = configureStore(middlewares);
      const store = mockStore({});

      store.dispatch(DUCKS.signup())
      .then(() => {
        expect(store.getActions()).to.deep.equal(expectedActions);
      }).then(done).catch(done);
    });

    it('signup should create SIGNUP_REQUEST and SIGNUP_FAILURE when API returns 401', (done) => {
      const expectedActions = [
        {
          type: DUCKS.SIGNUP_REQUEST
        }, {
          type: DUCKS.SIGNUP_FAILURE,
          payload: {
            errorCode: 'Connection Error',
            errorMessage: 'An error occurred while sending your data!'
          }
        }
      ];

      nock(SERVER_URL)
      .post('/api/accounts/register/')
      .reply('Connection Error', 'An error occurred while sending your data!');

      const middlewares = [thunk];
      const mockStore = configureStore(middlewares);
      const store = mockStore({});

      store.dispatch(DUCKS.signup())
      .then(() => {
        expect(store.getActions()).to.deep.equal(expectedActions);
      }).then(done).catch(done);
    });

    it('signup should create SIGNUP_REQUEST and SIGNUP_FAILURE actions when API ' +
    'has no response', (done) => {
      const expectedActions = [
        {
          type: DUCKS.SIGNUP_REQUEST
        }, {
          type: DUCKS.SIGNUP_FAILURE,
          payload: {
            errorCode: 'Connection Error',
            errorMessage: 'An error occurred while sending your data!'
          }
        }
      ];

      nock(SERVER_URL)
      .post('/api/v1/accounts/register/')
      .reply();

      const middlewares = [thunk];
      const mockStore = configureStore(middlewares);
      const store = mockStore({});

      store.dispatch(DUCKS.signup())
      .then(() => {
        expect(store.getActions()).to.deep.equal(expectedActions);
      }).then(done).catch(done);
    });
  });

  describe('Login, Logout Actions:', () => {
    afterEach(() => {
      nock.cleanAll();
    });

    beforeEach(() => {
      localStorage.removeItem('token');
    });

    it('loginSuccess should create LOGIN_SUCCESS action', () => {
      expect(DUCKS.loginSuccess('token', {})).to.eql({
        type: DUCKS.LOGIN_SUCCESS,
        payload: {
          token: 'token',
          user: {}
        }
      });
    });

    it('loginFailure should create LOGIN_FAILURE action', () => {
      expect(DUCKS.loginFailure(404, 'Not Found')).to.eql({
        type: DUCKS.LOGIN_FAILURE,
        payload: {
          errorCode: 404,
          errorMessage: 'Not Found'
        }
      });
    });

    it('loginRequest should create LOGIN_REQUEST action', () => {
      expect(DUCKS.loginRequest()).to.eql({
        type: DUCKS.LOGIN_REQUEST
      });
    });

    it('logout should create LOGOUT action', () => {
      expect(DUCKS.logout()).to.eql({
        type: DUCKS.LOGOUT
      });
    });

    it('login should create LOGIN_REQUEST, LOGIN_SUCCESS, ' +
    'actions when API returns 200', (done) => {
      const expectedActions = [
        {
          type: DUCKS.LOGIN_REQUEST
        }, {
          type: DUCKS.LOGIN_SUCCESS,
          payload: {
            token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyTmFtZSI6IlRlc3QgVXNlciJ9.J6n4-v0I85' +
            'zk9MkxBHroZ9ZPZEES-IKeul9ozxYnoZ8',
            user: {}
          }
        }
      ];

      nock(SERVER_URL)
      .post('/api/accounts/login/')
      .reply(200, {
        token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyTmFtZSI6IlRlc3QgVXNlciJ9.J6n4-v0I85' +
        'zk9MkxBHroZ9ZPZEES-IKeul9ozxYnoZ8',
        user: {}
      });

      const middlewares = [thunk];
      const mockStore = configureStore(middlewares);
      const store = mockStore({});

      store.dispatch(DUCKS.login())
      .then(() => {
        expect(store.getActions()).to.deep.equal(expectedActions);
      }).then(done).catch(done);
    });

    it('login should create LOGIN_REQUEST and LOGIN_FAILURE when API returns 401', (done) => {
      const expectedActions = [
        {
          type: DUCKS.LOGIN_REQUEST
        }, {
          type: DUCKS.LOGIN_FAILURE,
          payload: {
            errorCode: 401,
            errorMessage: 'Unauthorized'
          }
        }
      ];

      nock(SERVER_URL)
      .post('/api/accounts/login/')
      .reply(401, { non_field_errors: ['Unauthorized']});

      const middlewares = [thunk];
      const mockStore = configureStore(middlewares);
      const store = mockStore({});

      store.dispatch(DUCKS.login())
      .then(() => {
        expect(store.getActions()).to.deep.equal(expectedActions);
      }).then(done).catch(done);
    });

    it('login should create LOGIN_REQUEST and LOGIN_FAILURE actions when API returns 500', (done) => {
      const expectedActions = [
        {
          type: DUCKS.LOGIN_REQUEST
        }, {
          type: DUCKS.LOGIN_FAILURE,
          payload: {
            errorCode: 500,
            errorMessage: 'A server error occurred while sending your data!'
          }
        }
      ];

      nock(SERVER_URL)
      .post('/api/accounts/login/')
      .reply(500);

      const middlewares = [thunk];
      const mockStore = configureStore(middlewares);
      const store = mockStore({});

      store.dispatch(DUCKS.login())
      .then(() => {
        expect(store.getActions()).to.deep.equal(expectedActions);
      }).then(done).catch(done);
    });

    it('login should create LOGIN_REQUEST and LOGIN_FAILURE actions when API ' +
    'has no response', (done) => {
      const expectedActions = [
        {
          type: DUCKS.LOGIN_REQUEST
        }, {
          type: DUCKS.LOGIN_FAILURE,
          payload: {
            errorCode: 'Connection Error',
            errorMessage: 'An error occurred while sending your data!'
          }
        }
      ];

      nock(SERVER_URL)
      .post('/api/v1/accounts/login/')
      .reply();

      const middlewares = [thunk];
      const mockStore = configureStore(middlewares);
      const store = mockStore({});

      store.dispatch(DUCKS.login())
      .then(() => {
        expect(store.getActions()).to.deep.equal(expectedActions);
      }).then(done).catch(done);
    });
  });

});


text:
package org.pentaho.di.plugins.fileopensave.api.providers;

import org.pentaho.di.plugins.fileopensave.api.providers.exception.FileException;

import java.io.InputStream;
import java.util.List;

/**
 * Created by bmorrise on 2/14/19.
 */
public interface FileProvider<T extends File> {

  Class<T> getFileClass();

  String getName();

  String getType();

  boolean isAvailable();

  /**
   * Get entire tree (no filter)
   *
   * @return
   */
  Tree getTree();

  /**
   * Optional method to get a filtered tree based on the connection type
   *
   * @param connectionTypes
   * @return filteredTree
   */
  default Tree getTree( List<String> connectionTypes ) {
    return getTree();
  }

  List<T> getFiles( T file, String filters ) throws FileException;

  List<T> delete( List<T> files ) throws FileException;

  T add( T folder ) throws FileException;

  T getFile( T file );

  boolean fileExists( T dir, String path ) throws FileException;

  String getNewName( T destDir, String newPath ) throws FileException;

  String sanitizeName( T destDir, String newPath );

  boolean isSame( File file1, File file2 );

  T rename( T file, String newPath, boolean overwrite ) throws FileException;

  T copy( T file, String toPath, boolean overwrite ) throws FileException;

  T move( T file, String toPath, boolean overwrite ) throws FileException;

  InputStream readFile( T file ) throws FileException;

  T writeFile( InputStream inputStream, T destDir, String path, boolean overwrite ) throws FileException;

  T getParent( T file );

  void clearProviderCache();
}


text:
package test;

import io.github.repir.Repository.Repository;
import io.github.repir.tools.hadoop.Configuration;
import io.github.repir.tools.Lib.Log;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

/**
 * The mapper is generic, and collects data for a query request, using the
 * passed retrieval model, scoring function and query string. The common
 * approach is that each node processes all queries for one index partition. The
 * collected results are reshuffled to one reducer per query where all results
 * for a single query are aggregated.
 * <p/>
 * @author jeroen
 */
public class TestMap extends Mapper<IntWritable, Text, NullWritable, NullWritable> {

   public static Log log = new Log(TestMap.class);
   Configuration conf;
   Repository repository;

   @Override
   protected void setup(Mapper.Context context) throws IOException, InterruptedException {
      repository = new Repository(context.getConfiguration());
      conf = repository.getConfiguration();
   }

   @Override
   public void map(IntWritable inkey, Text invalue, Context context) throws IOException, InterruptedException {
      log.info("term %s", invalue.toString());
      test t = (test)repository.getFeature(test.class);
      t.openWrite();
      test.Record newRecord = t.newRecord();
      newRecord.word = invalue.toString();
      t.write(newRecord);
      t.closeWrite();
   }
}


text:
package com.github.gtache.lsp.contributors.inspection

import java.awt.GridBagLayout

import com.intellij.codeInspection.InspectionProfileEntry
import javax.swing.JPanel

/**
  * The Options panel for the LSP inspection
  *
  * @param label
  * @param owner
  */
class LSPInspectionPanel(label: String, owner: InspectionProfileEntry) extends JPanel(new GridBagLayout) {
}


text:
var app = app || {};

(function(){
  'use strict';

  app.ContactBookView = Backbone.View.extend({
    el: '#contact-list',

    initialize: function() {
      this.collection = new app.ContactBook();
      this.collection.fetch({reset: true});
      this.render();
      this.listenTo( this.collection, 'add', this.renderContact);
      this.listenTo( this.collection, 'reset', this.render);
      this.listenTo( this.collection, 'change', this.render);
      this.listenTo( this.collection, 'sort', this.render);
    },

    events:{
      'click #add':'addContact',
      'click .sortContact': 'sortContact'
    },

    render: function() {
      $('#generated-contact-list').html("");
      this.collection.each(function(item) {
        this.renderContact(item);
      }, this);
    },

    addContact: function(e) {
      e.preventDefault();

      var formData = {};

        var inputs = $('#addContact')[0];
        _.each(inputs,function(el) {
        if( $(el).val() !== '' ) {
          formData[ el.id ] = $(el).val();
        }
      }, this);

      if(formData.id && formData.id != ''){
        var contact = this.collection.get(formData.id);
        contact.set(formData);
        contact.save();
        this.collection.set(contact,{remove:false});
      }else{
        this.collection.create(formData);
      }
      $('input').val('');
      $('#close-modal').click();
    },

    renderContact: function(item) {
      var contactView = new app.ContactView({
        model: item
      });
      $('#generated-contact-list').append(contactView.render().el);
    },

    sortContact: function(e){
      e.preventDefault();
      this.collection.changeSort(e.currentTarget.getAttribute("data-sort-by"));
      this.collection.sort();
    }
  });

})();


text:
<?php

/**
 * @file
 * Definition of Drupal\Core\Routing\RouteBuildEvent.
 */

namespace Drupal\Core\Routing;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Routing\RouteCollection;

/**
 * Represents route building information as event.
 */
class RouteBuildEvent extends Event {

  /**
   * The route collection.
   *
   * @var \Symfony\Component\Routing\RouteCollection
   */
  protected $routeCollection;

  /**
   * The module name that provides the route.
   *
   * @var string
   */
  protected $module;

  /**
   * Constructs a RouteBuildEvent object.
   */
  public function __construct(RouteCollection $route_collection, $module) {
    $this->routeCollection = $route_collection;
    $this->module = $module;
  }

  /**
   * Gets the route collection.
   */
  public function getRouteCollection() {
    return $this->routeCollection;
  }

  /**
   * Gets the module that provides the route.
   */
  public function getModule() {
    return $this->module;
  }

}


text:
using Synology.Attributes;
using System;
using System.ComponentModel;

namespace Synology.FileStation.FileShare.Parameters
{
	[Flags]
	public enum FileShareDetailsType
	{
		[Description("real_path")]
		RealPath = 1 << 0,
		[Description("size")]
		Size = 1 << 1,
		[Description("owner")]
		Owner = 1 << 2,
		[Description("time")]
		Time = 1 << 3,
		[Description("perm")]
		Perm = 1 << 4,
		[Description("mount_point_type")]
		MountPointType = 1 << 5,
		[Description("volume_status")]
		VolumeStatus = 1 << 6
	}
}


text:
from wxPython.wx import *

class MyFrame(wxFrame):
    def __init__(self, parent, ID, title, pos=wxDefaultPosition,
                 size=(200, 200), style=wxDEFAULT_FRAME_STYLE):
        wxFrame.__init__(self, parent, ID, title, pos, size, style)
        panel = wxPanel(self, -1)

        button = wxButton(panel, 1003, "Close Me")
        button.SetPosition(wxPoint(15, 15))
        EVT_BUTTON(self, 1003, self.OnCloseMe)
        EVT_CLOSE(self, self.OnCloseWindow)

        button = wxButton(panel, 1004, "Press Me")
        button.SetPosition(wxPoint(15, 45))
        EVT_BUTTON(self, 1004, self.OnPressMe)

    def OnCloseMe(self, event):
        self.Close(True)

    def OnPressMe(self, event):
        # This raises an exception
        x = 1 / 0

    def OnCloseWindow(self, event):
        self.Destroy()

class MyApp(wxApp):
    def OnInit(self):
        frame = MyFrame(NULL, -1, "Hello from wxPython")
        frame.Show(true)
        self.SetTopWindow(frame)
        return true

app = MyApp(0)
app.MainLoop()


text:
<?php
namespace Kunstmaan\MediaBundle\Tests\Helper\RemoteVideo;

use Kunstmaan\MediaBundle\Entity\Media;

use Kunstmaan\MediaBundle\Helper\RemoteVideo\RemoteVideoHandler;
use Kunstmaan\MediaBundle\Helper\RemoteVideo\RemoteVideoHelper;

/**
 * Generated by PHPUnit_SkeletonGenerator on 2012-09-28 at 14:19:22.
 */
class RemoteVideoHelperTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var Media
     */
    protected $media;

    /**
     * @var RemoteVideoHelper
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     * @covers Kunstmaan\MediaBundle\Helper\RemoteVideo\RemoteVideoHelper::__construct
     */
    protected function setUp()
    {
        $this->media  = new Media();
        $this->object = new RemoteVideoHelper($this->media);
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    /**
     * @covers Kunstmaan\MediaBundle\Helper\RemoteVideo\RemoteVideoHelper::getMedia
     */
    public function testGetMedia()
    {
        $this->assertEquals(RemoteVideoHandler::CONTENT_TYPE, $this->object->getMedia()->getContentType());
    }
}


text:
using System.Collections.Generic;

namespace AspNetMvcEasyRouting.Routes.Infrastructures
{
    /// <summary>
    ///     Area list that gives an entry point to visit
    /// </summary>
    public class AreaSectionLocalizedList : List<AreaSectionLocalized>
    {
        public void AcceptRouteVisitor(IRouteVisitor visitor)
        {
            foreach (var element in this)
            {
                ((IRouteElement) element).AcceptRouteVisitor(visitor);
                if (visitor.HasFoundRoute)
                {
                    break;
                }
            }
        }
    }
}


text:
var LtiAppSearchDetailsIndexController = Ember.ObjectController.extend({

});

export default LtiAppSearchDetailsIndexController;


text:
package org.apache.ambari.infra.solr;

import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpClientUtil;
import org.apache.solr.client.solrj.impl.Krb5HttpClientConfigurer;
import org.apache.solr.common.cloud.SolrZkClient;

public class AmbariSolrCloudClientBuilder {
  private static final String KEYSTORE_LOCATION_ARG = "javax.net.ssl.keyStore";
  private static final String KEYSTORE_PASSWORD_ARG = "javax.net.ssl.keyStorePassword";
  private static final String KEYSTORE_TYPE_ARG = "javax.net.ssl.keyStoreType";
  private static final String TRUSTSTORE_LOCATION_ARG = "javax.net.ssl.trustStore";
  private static final String TRUSTSTORE_PASSWORD_ARG = "javax.net.ssl.trustStorePassword";
  private static final String TRUSTSTORE_TYPE_ARG = "javax.net.ssl.trustStoreType";

  String zkConnectString;
  String collection;
  String configSet;
  String configDir;
  int shards = 1;
  int replication = 1;
  int retryTimes = 10;
  int interval = 5;
  int maxShardsPerNode = replication * shards;
  String routerName = "implicit";
  String routerField = "_router_field_";
  CloudSolrClient solrCloudClient;
  SolrZkClient solrZkClient;
  boolean splitting;
  String jaasFile;
  String znode;
  String saslUsers;
  String propName;
  String propValue;
  String securityJsonLocation;
  boolean secure;

  public AmbariSolrCloudClient build() {
    return new AmbariSolrCloudClient(this);
  }

  public AmbariSolrCloudClientBuilder withZkConnectString(String zkConnectString) {
    this.zkConnectString = zkConnectString;
    return this;
  }

  public AmbariSolrCloudClientBuilder withCollection(String collection) {
    this.collection = collection;
    return this;
  }

  public AmbariSolrCloudClientBuilder withConfigSet(String configSet) {
    this.configSet = configSet;
    return this;
  }

  public AmbariSolrCloudClientBuilder withConfigDir(String configDir) {
    this.configDir = configDir;
    return this;
  }

  public AmbariSolrCloudClientBuilder withShards(int shards) {
    this.shards = shards;
    return this;
  }

  public AmbariSolrCloudClientBuilder withReplication(int replication) {
    this.replication = replication;
    return this;
  }

  public AmbariSolrCloudClientBuilder withRetry(int retryTimes) {
    this.retryTimes = retryTimes;
    return this;
  }

  public AmbariSolrCloudClientBuilder withInterval(int interval) {
    this.interval = interval;
    return this;
  }

  public AmbariSolrCloudClientBuilder withMaxShardsPerNode(int maxShardsPerNode) {
    this.maxShardsPerNode = maxShardsPerNode;
    return this;
  }

  public AmbariSolrCloudClientBuilder withRouterName(String routerName) {
    this.routerName = routerName;
    return this;
  }

  public AmbariSolrCloudClientBuilder withRouterField(String routerField) {
    this.routerField = routerField;
    return this;
  }

  public AmbariSolrCloudClientBuilder withSplitting(boolean splitting) {
    this.splitting = splitting;
    return this;
  }

  public AmbariSolrCloudClientBuilder withJaasFile(String jaasFile) {
    this.jaasFile = jaasFile;
    setupSecurity(jaasFile);
    return this;
  }

  public AmbariSolrCloudClientBuilder withSolrCloudClient() {
    this.solrCloudClient = new CloudSolrClient(this.zkConnectString);
    return this;
  }

  public AmbariSolrCloudClientBuilder withSolrZkClient(int zkClientTimeout, int zkClientConnectTimeout) {
    this.solrZkClient = new SolrZkClient(this.zkConnectString, zkClientTimeout, zkClientConnectTimeout);
    return this;
  }

  public AmbariSolrCloudClientBuilder withKeyStoreLocation(String keyStoreLocation) {
    if (keyStoreLocation != null) {
      System.setProperty(KEYSTORE_LOCATION_ARG, keyStoreLocation);
    }
    return this;
  }

  public AmbariSolrCloudClientBuilder withKeyStorePassword(String keyStorePassword) {
    if (keyStorePassword != null) {
      System.setProperty(KEYSTORE_PASSWORD_ARG, keyStorePassword);
    }
    return this;
  }

  public AmbariSolrCloudClientBuilder withKeyStoreType(String keyStoreType) {
    if (keyStoreType != null) {
      System.setProperty(KEYSTORE_TYPE_ARG, keyStoreType);
    }
    return this;
  }

  public AmbariSolrCloudClientBuilder withTrustStoreLocation(String trustStoreLocation) {
    if (trustStoreLocation != null) {
      System.setProperty(TRUSTSTORE_LOCATION_ARG, trustStoreLocation);
    }
    return this;
  }

  public AmbariSolrCloudClientBuilder withTrustStorePassword(String trustStorePassword) {
    if (trustStorePassword != null) {
      System.setProperty(TRUSTSTORE_PASSWORD_ARG, trustStorePassword);
    }
    return this;
  }

  public AmbariSolrCloudClientBuilder withTrustStoreType(String trustStoreType) {
    if (trustStoreType != null) {
      System.setProperty(TRUSTSTORE_TYPE_ARG, trustStoreType);
    }
    return this;
  }

  public AmbariSolrCloudClientBuilder withSaslUsers(String saslUsers) {
    this.saslUsers = saslUsers;
    return this;
  }

  public AmbariSolrCloudClientBuilder withZnode(String znode) {
    this.znode = znode;
    return this;
  }

  public AmbariSolrCloudClientBuilder withClusterPropName(String clusterPropName) {
    this.propName = clusterPropName;
    return this;
  }

  public AmbariSolrCloudClientBuilder withClusterPropValue(String clusterPropValue) {
    this.propValue = clusterPropValue;
    return this;
  }

  public AmbariSolrCloudClientBuilder withSecurityJsonLocation(String securityJson) {
    this.securityJsonLocation = securityJson;
    return this;
  }

  public AmbariSolrCloudClientBuilder withSecure(boolean isSecure) {
    this.secure = isSecure;
    return this;
  }

  private void setupSecurity(String jaasFile) {
    if (jaasFile != null) {
      System.setProperty("java.security.auth.login.config", jaasFile);
      HttpClientUtil.setConfigurer(new Krb5HttpClientConfigurer());
    }
  }
}