text:
import logging
import telnetlib
import time
import uuid

import fixtures
from keystoneclient.v2_0 import client as keystone_client
from neutronclient.v2_0 import client as neutron_client
from novaclient.v1_1 import client as nova_client
from oslo.utils import excutils
from oslotest import base
from saharaclient.api import base as client_base
import saharaclient.client as sahara_client
import six
from swiftclient import client as swift_client
from testtools import testcase

from sahara.tests.integration.configs import config as cfg
import sahara.utils.openstack.images as imgs
from sahara.utils import ssh_remote

logger = logging.getLogger('swiftclient')
logger.setLevel(logging.WARNING)

def errormsg(message):
    def decorator(fct):
        def wrapper(*args, **kwargs):
            try:
                fct(*args, **kwargs)
            except Exception as e:
                with excutils.save_and_reraise_exception():
                    ITestCase.print_error_log(message, e)

        return wrapper
    return decorator

def skip_test(config_name, message=''):
    def handle(func):
        def call(self, *args, **kwargs):
            if getattr(self, config_name):
                print(
                    '\n======================================================='
                )
                print('INFO: ' + message)
                print(
                    '=======================================================\n'
                )

            else:
                return func(self, *args, **kwargs)
        return call
    return handle

class ITestCase(testcase.WithAttributes, base.BaseTestCase):
    def setUp(self):
        super(ITestCase, self).setUp()
        self.common_config = cfg.ITConfig().common_config
        self.vanilla_config = cfg.ITConfig().vanilla_config
        self.vanilla_two_config = cfg.ITConfig().vanilla_two_config
        self.hdp_config = cfg.ITConfig().hdp_config

        telnetlib.Telnet(
            self.common_config.SAHARA_HOST, self.common_config.SAHARA_PORT
        )

        keystone = keystone_client.Client(
            username=self.common_config.OS_USERNAME,
            password=self.common_config.OS_PASSWORD,
            tenant_name=self.common_config.OS_TENANT_NAME,
            auth_url=self.common_config.OS_AUTH_URL)

        keystone.management_url = self.common_config.OS_AUTH_URL

        self.common_config.OS_TENANT_ID = [
            tenant.id for tenant in keystone.tenants.list()
            if tenant.name == self.common_config.OS_TENANT_NAME][0]

        self.sahara = sahara_client.Client(
            version=self.common_config.SAHARA_API_VERSION,
            username=self.common_config.OS_USERNAME,
            api_key=self.common_config.OS_PASSWORD,
            project_name=self.common_config.OS_TENANT_NAME,
            auth_url=self.common_config.OS_AUTH_URL,
            sahara_url='http://%s:%s/v%s/%s' % (
                self.common_config.SAHARA_HOST,
                self.common_config.SAHARA_PORT,
                self.common_config.SAHARA_API_VERSION,
                self.common_config.OS_TENANT_ID
            ))

        self.nova = nova_client.Client(
            username=self.common_config.OS_USERNAME,
            api_key=self.common_config.OS_PASSWORD,
            project_id=self.common_config.OS_TENANT_NAME,
            auth_url=self.common_config.OS_AUTH_URL)

        self.neutron = neutron_client.Client(
            username=self.common_config.OS_USERNAME,
            password=self.common_config.OS_PASSWORD,
            tenant_name=self.common_config.OS_TENANT_NAME,
            auth_url=self.common_config.OS_AUTH_URL)

        if not self.common_config.FLAVOR_ID:
            self.flavor_id = self.nova.flavors.create(
                name='i-test-flavor-%s' % str(uuid.uuid4())[:8],
                ram=1024,
                vcpus=1,
                disk=10,
                ephemeral=10).id

        else:
            self.flavor_id = self.common_config.FLAVOR_ID

        if not self.common_config.PATH_TO_SSH_KEY:
            self.common_config.USER_KEYPAIR_ID += str(uuid.uuid4())[:8]
            self.private_key = self.nova.keypairs.create(
                self.common_config.USER_KEYPAIR_ID).private_key

        else:
            self.private_key = open(self.common_config.PATH_TO_SSH_KEY).read()

# ------------------------Methods for object creation--------------------------

    def create_node_group_template(self, name, plugin_config, description,
                                   node_processes, node_configs,
                                   volumes_per_node=0, volume_size=0,
                                   floating_ip_pool=None):
        data = self.sahara.node_group_templates.create(
            name, plugin_config.PLUGIN_NAME, plugin_config.HADOOP_VERSION,
            self.flavor_id, description, volumes_per_node, volume_size,
            node_processes, node_configs, floating_ip_pool)
        node_group_template_id = data.id
        return node_group_template_id

    def create_cluster_template(self, name, plugin_config, description,
                                cluster_configs, node_groups,
                                anti_affinity=None, net_id=None):
        for node_group in node_groups:
            for key, value in node_group.items():
                if value is None:
                    del node_group[key]
        data = self.sahara.cluster_templates.create(
            name, plugin_config.PLUGIN_NAME, plugin_config.HADOOP_VERSION,
            description, cluster_configs, node_groups, anti_affinity, net_id)
        cluster_template_id = data.id
        return cluster_template_id

    def create_cluster(self, name, plugin_config, cluster_template_id,
                       description, cluster_configs,
                       node_groups=None, anti_affinity=None,
                       net_id=None, is_transient=False):
        self.cluster_id = None

        data = self.sahara.clusters.create(
            name, plugin_config.PLUGIN_NAME, plugin_config.HADOOP_VERSION,
            cluster_template_id, plugin_config.IMAGE_ID, is_transient,
            description, cluster_configs, node_groups,
            self.common_config.USER_KEYPAIR_ID, anti_affinity, net_id)
        self.cluster_id = data.id
        self.poll_cluster_state(self.cluster_id)

    def get_cluster_info(self, plugin_config):
        node_ip_list_with_node_processes = (
            self.get_cluster_node_ip_list_with_node_processes(self.cluster_id))
        try:
            node_info = self.get_node_info(node_ip_list_with_node_processes,
                                           plugin_config)

        except Exception as e:
            with excutils.save_and_reraise_exception():
                print(
                    '\nFailure during check of node process deployment '
                    'on cluster node: ' + six.text_type(e)
                )

        # For example: method "create_cluster_and_get_info" return
        # {
        #       'node_info': {
        #               'tasktracker_count': 3,
        #               'node_count': 6,
        #               'namenode_ip': '172.18.168.242',
        #               'datanode_count': 3
        #               },
        #       'cluster_id': 'bee5c6a1-411a-4e88-95fc-d1fbdff2bb9d',
        #       'node_ip_list': {
        #               '172.18.168.153': ['tasktracker', 'datanode'],
        #               '172.18.168.208': ['secondarynamenode', 'oozie'],
        #               '172.18.168.93': ['tasktracker'],
        #               '172.18.168.101': ['tasktracker', 'datanode'],
        #               '172.18.168.242': ['namenode', 'jobtracker'],
        #               '172.18.168.167': ['datanode']
        #       },
        #       'plugin_config': <oslo.config.cfg.GroupAttr object at 0x215d9d>
        # }
        return {
            'cluster_id': self.cluster_id,
            'node_ip_list': node_ip_list_with_node_processes,
            'node_info': node_info,
            'plugin_config': plugin_config
        }

# --------Helper methods for cluster info obtaining and its processing---------

    def poll_cluster_state(self, cluster_id):
        data = self.sahara.clusters.get(cluster_id)
        timeout = self.common_config.CLUSTER_CREATION_TIMEOUT * 60

        try:
            with fixtures.Timeout(timeout, gentle=True):
                while True:
                    status = str(data.status)
                    if status == 'Active':
                        break
                    if status == 'Error':
                        self.fail('Cluster state == \'Error\'.')

                    time.sleep(10)
                    data = self.sahara.clusters.get(cluster_id)

        except fixtures.TimeoutException:
            self.fail("Cluster did not return to 'Active' state "
                      "within %d minutes." %
                      self.common_config.CLUSTER_CREATION_TIMEOUT)

        return status

    def get_cluster_node_ip_list_with_node_processes(self, cluster_id):
        data = self.sahara.clusters.get(cluster_id)
        node_groups = data.node_groups
        node_ip_list_with_node_processes = {}
        for node_group in node_groups:
            instances = node_group['instances']
            for instance in instances:
                node_ip = instance['management_ip']
                node_ip_list_with_node_processes[node_ip] = node_group[
                    'node_processes']
        # For example:
        # node_ip_list_with_node_processes = {
        #       '172.18.168.181': ['tasktracker'],
        #       '172.18.168.94': ['secondarynamenode'],
        #       '172.18.168.208': ['namenode', 'jobtracker'],
        #       '172.18.168.93': ['tasktracker', 'datanode'],
        #       '172.18.168.44': ['tasktracker', 'datanode'],
        #       '172.18.168.233': ['datanode']
        # }
        return node_ip_list_with_node_processes

    def try_telnet(self, host, port):
        try:
            telnetlib.Telnet(host, port)

        except Exception as e:
            with excutils.save_and_reraise_exception():
                print(
                    '\nTelnet has failed: ' + six.text_type(e) +
                    '  NODE IP: %s, PORT: %s. Passed %s minute(s).'
                    % (host, port, self.common_config.TELNET_TIMEOUT)
                )

    def get_node_info(self, node_ip_list_with_node_processes, plugin_config):
        tasktracker_count = 0
        datanode_count = 0
        timeout = self.common_config.TELNET_TIMEOUT * 60
        with fixtures.Timeout(timeout, gentle=True):
            accessible = False
            proc_with_ports = plugin_config.HADOOP_PROCESSES_WITH_PORTS
            while not accessible:
                accessible = True
                for node_ip, processes in six.iteritems(
                        node_ip_list_with_node_processes):
                    try:
                        self.try_telnet(node_ip, '22')
                    except Exception:
                        accessible = False

                    for process in processes:
                        if process in proc_with_ports:
                            try:
                                self.try_telnet(node_ip,
                                                proc_with_ports[process])
                            except Exception:
                                print('Connection attempt. NODE PROCESS: %s, '
                                      'PORT: %s.' % (
                                          process, proc_with_ports[process]))
                                accessible = False

                if not accessible:
                    time.sleep(1)

        for node_ip, processes in six.iteritems(
                node_ip_list_with_node_processes):
            if plugin_config.PROCESS_NAMES['tt'] in processes:
                tasktracker_count += 1
            if plugin_config.PROCESS_NAMES['dn'] in processes:
                datanode_count += 1
            if plugin_config.PROCESS_NAMES['nn'] in processes:
                namenode_ip = node_ip

        return {
            'namenode_ip': namenode_ip,
            'tasktracker_count': tasktracker_count,
            'datanode_count': datanode_count,
            'node_count': len(node_ip_list_with_node_processes)
        }

    def await_active_workers_for_namenode(self, node_info, plugin_config):
        self.open_ssh_connection(
            node_info['namenode_ip'], plugin_config.SSH_USERNAME)
        timeout = self.common_config.HDFS_INITIALIZATION_TIMEOUT * 60
        try:
            with fixtures.Timeout(timeout, gentle=True):
                while True:
                    active_tasktracker_count = self.execute_command(
                        'sudo -u %s bash -lc "hadoop job -list-active-trackers'
                        '" | grep "^tracker_" | wc -l'
                        % plugin_config.HADOOP_USER)[1]
                    try:
                        active_tasktracker_count = int(
                            active_tasktracker_count)
                    except ValueError:
                        active_tasktracker_count = -1

                    active_datanode_count = self.execute_command(
                        'sudo -u %s bash -lc "hadoop dfsadmin -report" | '
                        'grep -e "Datanodes available:.*" '
                        '-e "Live datanodes.*" | grep -o "[0-9]*" | head -1'
                        % plugin_config.HADOOP_USER)[1]
                    try:
                        active_datanode_count = int(active_datanode_count)
                    except ValueError:
                        active_datanode_count = -1

                    if (active_tasktracker_count ==
                            node_info['tasktracker_count'] and
                            active_datanode_count ==
                            node_info['datanode_count']):
                        break

                    time.sleep(10)

        except fixtures.TimeoutException:
            self.fail(
                'Tasktracker or datanode cannot be started within '
                '%s minute(s) for namenode.'
                % self.common_config.HDFS_INITIALIZATION_TIMEOUT
            )
        finally:
            self.close_ssh_connection()

# --------------------------------Remote---------------------------------------

    def connect_to_swift(self):
        return swift_client.Connection(
            authurl=self.common_config.OS_AUTH_URL,
            user=self.common_config.OS_USERNAME,
            key=self.common_config.OS_PASSWORD,
            tenant_name=self.common_config.OS_TENANT_NAME,
            auth_version=self.common_config.SWIFT_AUTH_VERSION
        )

    def open_ssh_connection(self, host, ssh_username):
        ssh_remote._connect(host, ssh_username, self.private_key)

    @staticmethod
    def execute_command(cmd):
        return ssh_remote._execute_command(cmd, get_stderr=True)

    @staticmethod
    def write_file_to(remote_file, data):
        ssh_remote._write_file_to(remote_file, data)

    @staticmethod
    def read_file_from(remote_file):
        return ssh_remote._read_file_from(remote_file)

    @staticmethod
    def close_ssh_connection():
        ssh_remote._cleanup()

    def transfer_helper_script_to_node(self, script_name, parameter_list=None):
        script = open('sahara/tests/integration/tests/resources/%s'
                      % script_name).read()
        if parameter_list:
            for parameter, value in parameter_list.items():
                script = script.replace(
                    '%s=""' % parameter, '%s=%s' % (parameter, value))
        try:
            self.write_file_to('script.sh', script)

        except Exception as e:
            with excutils.save_and_reraise_exception():
                print(
                    '\nFailure while helper script transferring '
                    'to cluster node: ' + six.text_type(e)
                )
        self.execute_command('chmod 777 script.sh')

    def transfer_helper_script_to_nodes(self, node_ip_list, ssh_username,
                                        script_name, parameter_list=None):
        for node_ip in node_ip_list:
            self.open_ssh_connection(node_ip, ssh_username)
            self.transfer_helper_script_to_node(script_name, parameter_list)
            self.close_ssh_connection()

# -------------------------------Helper methods--------------------------------

    def get_image_id_and_ssh_username(self, plugin_config):
        def print_error_log(parameter, value):
            print(
                '\nImage with %s "%s" was found in image list but it was '
                'possibly not registered for Sahara. Please, make sure image '
                'was correctly registered.' % (parameter, value)
            )

        def try_get_image_id_and_ssh_username(parameter, value):
            try:
                return image.id, image.metadata[imgs.PROP_USERNAME]

            except KeyError:
                with excutils.save_and_reraise_exception():
                    print_error_log(parameter, value)

        images = self.nova.images.list()
        # If plugin_config.IMAGE_ID is not None then find corresponding image
        # and return its ID and username. If image not found then handle error
        if plugin_config.IMAGE_ID:
            for image in images:
                if image.id == plugin_config.IMAGE_ID:
                    return try_get_image_id_and_ssh_username(
                        'ID', plugin_config.IMAGE_ID
                    )
            self.fail(
                '\n\nImage with ID "%s" not found in image list. Please, make '
                'sure you specified right image ID.\n' % plugin_config.IMAGE_ID
            )
        # If plugin_config.IMAGE_NAME is not None then find corresponding image
        # and return its ID and username. If image not found then handle error
        if plugin_config.IMAGE_NAME:
            for image in images:
                if image.name == plugin_config.IMAGE_NAME:
                    return try_get_image_id_and_ssh_username(
                        'name', plugin_config.IMAGE_NAME
                    )
            self.fail(
                '\n\nImage with name "%s" not found in image list. Please, '
                'make sure you specified right image name.\n'
                % plugin_config.IMAGE_NAME
            )
        # If plugin_config.IMAGE_TAG is not None then find corresponding image
        # and return its ID and username. If image not found then handle error
        if plugin_config.IMAGE_TAG:
            for image in images:
                if (image.metadata.get(imgs.PROP_TAG + '%s'
                    % plugin_config.IMAGE_TAG)) and (
                        image.metadata.get(imgs.PROP_TAG + (
                                           '%s' % plugin_config.PLUGIN_NAME))):
                    return try_get_image_id_and_ssh_username(
                        'tag', plugin_config.IMAGE_TAG
                    )
            self.fail(
                '\n\nImage with tag "%s" not found in list of registered '
                'images for Sahara. Please, make sure tag "%s" was added to '
                'image and image was correctly registered.\n'
                % (plugin_config.IMAGE_TAG, plugin_config.IMAGE_TAG)
            )
        # If plugin_config.IMAGE_ID, plugin_config.IMAGE_NAME and
        # plugin_config.IMAGE_TAG are None then image is chosen
        # by tag "sahara_i_tests". If image has tag "sahara_i_tests"
        # (at the same time image ID, image name and image tag were not
        # specified in configuration file of integration tests) then return
        # its ID and username. Found image will be chosen as image for tests.
        # If image with tag "sahara_i_tests" not found then handle error
        for image in images:
            if (image.metadata.get(imgs.PROP_TAG + 'sahara_i_tests')) and (
                    image.metadata.get(imgs.PROP_TAG + (
                                       '%s' % plugin_config.PLUGIN_NAME))):
                try:
                    return image.id, image.metadata[imgs.PROP_USERNAME]

                except KeyError:
                        with excutils.save_and_reraise_exception():
                            print(
                                '\nNone of parameters of image (ID, name, tag)'
                                ' was specified in configuration file of '
                                'integration tests. That is why there was '
                                'attempt to choose image by tag '
                                '"sahara_i_tests" and image with such tag '
                                'was found in image list but it was possibly '
                                'not registered for Sahara. Please, make '
                                'sure image was correctly registered.'
                            )
        self.fail(
            '\n\nNone of parameters of image (ID, name, tag) was specified in '
            'configuration file of integration tests. That is why there was '
            'attempt to choose image by tag "sahara_i_tests" but image with '
            'such tag not found in list of registered images for Sahara. '
            'Please, make sure image was correctly registered. Please, '
            'specify one of parameters of image (ID, name or tag) in '
            'configuration file of integration tests.\n'
        )

    def get_floating_ip_pool_id_for_neutron_net(self):
        # Find corresponding floating IP pool by its name and get its ID.
        # If pool not found then handle error
        try:
            floating_ip_pool = self.neutron.list_networks(
                name=self.common_config.FLOATING_IP_POOL)
            floating_ip_pool_id = floating_ip_pool['networks'][0]['id']
            return floating_ip_pool_id

        except IndexError:
            with excutils.save_and_reraise_exception():
                raise Exception(
                    '\nFloating IP pool \'%s\' not found in pool list. '
                    'Please, make sure you specified right floating IP pool.'
                    % self.common_config.FLOATING_IP_POOL
                )

    def get_internal_neutron_net_id(self):
        # Find corresponding internal Neutron network by its name and get
        # its ID. If network not found then handle error
        try:
            internal_neutron_net = self.neutron.list_networks(
                name=self.common_config.INTERNAL_NEUTRON_NETWORK)
            internal_neutron_net_id = internal_neutron_net['networks'][0]['id']
            return internal_neutron_net_id

        except IndexError:
            with excutils.save_and_reraise_exception():
                raise Exception(
                    '\nInternal Neutron network \'%s\' not found in network '
                    'list. Please, make sure you specified right network name.'
                    % self.common_config.INTERNAL_NEUTRON_NETWORK
                )

    def delete_objects(self, cluster_id=None,
                       cluster_template_id=None,
                       node_group_template_id_list=None):
        if not self.common_config.RETAIN_CLUSTER_AFTER_TEST:
            if cluster_id:
                self.sahara.clusters.delete(cluster_id)

                try:
                    # waiting roughly for 300 seconds for cluster to terminate
                    with fixtures.Timeout(300, gentle=True):
                        while True:
                            try:
                                self.sahara.clusters.get(cluster_id)
                            except client_base.APIException:
                                # Cluster is finally deleted
                                break

                            time.sleep(5)

                except fixtures.TimeoutException:
                    self.fail('Cluster failed to terminate in 300 seconds: '
                              '%s' % cluster_id)

            if cluster_template_id:
                self.sahara.cluster_templates.delete(cluster_template_id)
            if node_group_template_id_list:
                for node_group_template_id in node_group_template_id_list:
                    self.sahara.node_group_templates.delete(
                        node_group_template_id
                    )

    @staticmethod
    def delete_swift_container(swift, container):
        objects = [obj['name'] for obj in swift.get_container(container)[1]]
        for obj in objects:
            swift.delete_object(container, obj)
        swift.delete_container(container)

    @staticmethod
    def print_error_log(message, exception=None):
        print(
            '\n\n!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!* '
            'ERROR LOG *!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*'
            '!*!\n'
        )
        print(message + six.text_type(exception))
        print(
            '\n!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!* END OF '
            'ERROR LOG *!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*'
            '!*!\n\n'
        )

    def capture_error_log_from_cluster_node(self, log_file):
        print(
            '\n\n!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!* CAPTURED ERROR '
            'LOG FROM CLUSTER NODE *!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*'
            '!*!\n'
        )
        print(self.read_file_from(log_file))
        print(
            '\n!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!* END OF CAPTURED ERROR '
            'LOG FROM CLUSTER NODE *!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*'
            '!*!\n\n'
        )

    def tearDown(self):
        if not self.common_config.PATH_TO_SSH_KEY:
            self.nova.keypairs.delete(self.common_config.USER_KEYPAIR_ID)
        if not self.common_config.FLAVOR_ID:
            self.nova.flavors.delete(self.flavor_id)

        super(ITestCase, self).tearDown()


text:
"""
arfile - A module to parse GNU ar archives.

Copyright (c) 2006-7 Paul Sokolovsky
This file is released under the terms
of GNU General Public License v2 or later.
"""
import sys
import os
import tarfile

class FileSection:
    "A class which allows to treat portion of file as separate file object."

    def __init__(self, f, offset, size):
        self.f = f
        self.offset = offset
        self.size = size
        self.seek(0, 0)

    def seek(self, offset, whence = 0):
#        print "seek(%x, %d)" % (offset, whence)
        if whence == 0:
            return self.f.seek(offset + self.offset, whence)
        elif whence == 1:
            return self.f.seek(offset, whence)
        elif whence == 2:
            return self.f.seek(self.offset + self.size + offset, 0)
        else:
            assert False

    def tell(self):
#        print "tell()"
        return self.f.tell() - self.offset

    def read(self, size = -1):
#        print "read(%d)" % size
        return self.f.read(size)

class ArFile:

    def __init__(self, f):
        self.f = f
        self.directory = {}
        self.directoryRead = False

        signature = self.f.readline()
        assert signature == "!<arch>\n"
        self.directoryOffset = self.f.tell()

    def open(self, fname):
        if self.directory.has_key(fname):
            return FileSection(self.f, self.directory[fname][-1], int(self.directory[fname][5]))

        if self.directoryRead:
            raise IOError, (2, "AR member not found: " + fname)

        f = self._scan(fname)
        if f == None:
            raise IOError, (2, "AR member not found: " + fname)
        return f

    def _scan(self, fname):
        self.f.seek(self.directoryOffset, 0)

        while True:
            l = self.f.readline()
            if not l:
                self.directoryRead = True
                return None

            if l == "\n":
                l = self.f.readline()
                if not l: break
            l = l.replace('`', '')
            descriptor = l.split()
#            print descriptor
            size = int(descriptor[5])
            memberName = descriptor[0][:-1]
            self.directory[memberName] = descriptor + [self.f.tell()]
#            print "read:", memberName
            if memberName == fname:
                # Record directory offset to start from next time
                self.directoryOffset = self.f.tell() + size
                return FileSection(self.f, self.f.tell(), size)

            # Skip data and loop
            if size % 2:
                size = size + 1
            data = self.f.seek(size, 1)
#            print hex(f.tell())

if __name__ == "__main__":
    if None:
        f = open(sys.argv[1], "rb")

        ar = ArFile(f)
        tarStream = ar.open("data.tar.gz")
        print "--------"
        tarStream = ar.open("data.tar.gz")
        print "--------"
        tarStream = ar.open("control.tar.gz")
        print "--------"
        tarStream = ar.open("control.tar.gz2")

        sys.exit(0)

    dir = "."
    if len(sys.argv) > 1:
        dir = sys.argv[1]
    for f in os.listdir(dir):
        if not f.endswith(".opk") and not f.endswith(".ipk"): continue

        print "=== %s ===" % f
        f = open(dir + "/" + f, "rb")

        ar = ArFile(f)
        tarStream = ar.open("control.tar.gz")
        tarf = tarfile.open("control.tar.gz", "r", tarStream)
        #tarf.list()

        f2 = tarf.extractfile("control")
        print f2.read()

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
                  http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="MQM\BlogBundle\Entity\Blog" table="mqm_blog">

        <!--
        <indexes>
            <index name="name_idx" columns="name"/>
            <index columns="user_email"/>
        </indexes>

        <unique-constraints>
            <unique-constraint columns="name,user_email" name="search_idx" />
        </unique-constraints>

        <lifecycle-callbacks>
            <lifecycle-callback type="prePersist" method="doStuffOnPrePersist"/>
            <lifecycle-callback type="prePersist" method="doOtherStuffOnPrePersistToo"/>
            <lifecycle-callback type="postPersist" method="doStuffOnPostPersist"/>
        </lifecycle-callbacks>
        -->

        <id name="id" column="id" type="integer">
            <generator strategy="AUTO"/>
        </id>
        <field name="name" column="name" type="string" length="255" unique="true" />
        <field name="slug" column="slug" type="string" length="255"/>
        <field name="createdAt" column="created_at" type="datetime"/>
        <one-to-many field="topics" target-entity="MQM\BlogBundle\Entity\Topic" mapped-by="blog" />
    </entity>
</doctrine-mapping>


text:
YACY_HOME=/usr/share/yacy

# [AUR] Funilrys: 24.06.2020 ==> Old version. Reason: https://aur.archlinux.org/packages/yacy/#comment-752601
# JAVA_ARGS="-server -Xss256k -XX:MaxPermSize=256m -XX:ReservedCodeCacheSize=1024m -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:-UseGCOverheadLimit -XX:+UseAdaptiveSizePolicy -Djava.net.preferIPv4Stack=true -Djava.awt.headless=true -Dfile.encoding=UTF-8"

JAVA_ARGS="-server -Xss256k -XX:ReservedCodeCacheSize=1024m -XX:-UseGCOverheadLimit -XX:+UseAdaptiveSizePolicy -Djava.net.preferIPv4Stack=true -Djava.awt.headless=true -Dfile.encoding=UTF-8"

#check if system supports large memory pages and enable it if possible
HUGEPAGESTOTAL="$(cat /proc/meminfo | grep HugePages_Total | sed s/[^0-9]//g)"
if [ -n "$HUGEPAGESTOTAL" ] && [ $HUGEPAGESTOTAL -ne 0 ]
then
	JAVA_ARGS="$JAVA_ARGS -XX:+UseLargePages"
fi

[ -f /etc/profile.d/jre.sh ] && . /etc/profile.d/jre.sh

[ -f /etc/conf.d/yacy ] && . /etc/conf.d/yacy

if [ "$(id -u)" != "0" -a "$(whoami)" != "$USER" ] ; then
	echo "please run this script as root!"
	exit 4
fi

JAVA=$(which java 2> /dev/null)
if [ ! -x "$JAVA" ]; then
	echo "The 'java' command is not executable."
	echo "Either you have not installed java or it is not in your PATH"
	if [ $1 == "stop" -a $2 == "--force" ]; then exit 0; else exit 1; fi
fi

cd $YACY_HOME

#get javastart args
if [ -s DATA/SETTINGS/yacy.conf ]
then
	# startup memory
	for i in Xmx Xms; do
		j=$(grep javastart_$i DATA/SETTINGS/yacy.conf | sed 's/^[^=]*=//')
		if [ -n $j ]; then JAVA_ARGS="-$j $JAVA_ARGS"
		fi
	done

	# Priority
	j=$(grep javastart_priority DATA/SETTINGS/yacy.conf | sed 's/^[^=]*=//')

	if [ ! -z "$j" ];
	then
		if [ -n $j ]
		then NICE_VAL=$j
		fi
	fi

else
	JAVA_ARGS="-Xmx120m -Xms120m $JAVA_ARGS"
fi

CP=/usr/share/java/yacy.jar:$YACY_HOME/htroot
for name in /usr/share/java/yacy/*.jar; do
	CP=$CP:$name
done
CLASSPATH=$CP

case "$1" in
	start)
		printf "Starting YaCy Daemon\n"
		ARGS="$JAVA_ARGS -classpath $CLASSPATH net.yacy.yacy"
		$JAVA $ARGS
		;;
	stop)
		$JAVA $JAVA_ARGS -cp $CLASSPATH net.yacy.yacy -shutdown
		;;
	restart)
		$0 stop
		sleep 3
		$0 start
		;;
esac


text:
public interface Prototype {

	public Prototype doClone();

}


text:
title: get_parentView()
page_title: get_parentView() | RadGrid for ASP.NET AJAX Documentation
description: get_parentView()
slug: grid/client-side-programming/gridtableview-object/properties/get_parentview()
tags: get_parentview()
published: True
position: 18
---

# get_parentView()

##

If called from a nested GridTableView returns the parent GridTableView in the grid hierarchy. Returns null if called from the MasterTableView.


text:
<?php

class Commentary extends Crud_controller
{

  function __construct()
  {
    parent::__construct();
    $this->load->model('Commentary_model', 'model');

  }

  function single_get($id)
  {
    $res['commentary'] = @$this->model->get($id)[0];

    $this->load->model('cpm_model');
    $res['first_half'] = $this->cpm_model->getAllByType($id, 'first_half');
    $res['second_half'] = $this->cpm_model->getAllByType($id, 'second_half');

    if($res['commentary'] !== null){ # Respond with 404 when the resource is not found
      $this->response($res, 200);
    }else{
      $this->response(['message' => 'Not found'], 404);
    }
  }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 53: 74 (1913)

#### Original name
Favolus megaloporus var. megaloporus (Mont.) Bres.

### Remarks
null


text:
'use strict';

/**
 * This file checks for different configs and merges them in correct order.
 * There are following configs
 *   - config-development.js: The default config parameters
 *   - config-production.js: Parameters of going live. Minifies and removes debug informations like source maps
 *   - config-user.js: Parameters override the default config-development.js and are for your development
 *                     environment. Don't add this to the repository. It's for you, not your team!
 *
 *  Config overrides: config-production > config-user > config-development
 */

var args = require('yargs').argv;
var _ = require('lodash');

var defaultConfigDev = require('./config-development');
var defaultConfigProd = require('./config-production');
var isProductionEnv = args.env === 'production' || args.env === 'prod';

module.exports = function(config){
  var mergedConfig;

  // Create empty configuration container for defaults if no config submitted
  if(!config){
    config = {
      dev: null,
      prod: null,
      user: null
    };
  }

  // Merge submitted configs where needed with defaults
  if(config.dev){
    config.dev = _.merge(defaultConfigDev, config.dev);
  } else {
    config.dev = defaultConfigDev;
  }

  if(config.prod){
    config.prod = _.merge(defaultConfigProd, config.prod);
  } else {
    config.prod = defaultConfigProd;
  }

  // Create concrete config for compilation
  // Take Development Config as a base, start with user config
  var mergedConfig = config.dev;
  if(config.user) {
    mergedConfig = _.merge(mergedConfig, config.user);
  }

  if(isProductionEnv) {
    mergedConfig = _.merge(mergedConfig, config.user);
  }

  return mergedConfig;
};


text:
FROM amazonlinux:2.0.20220912.1

COPY /install_apps install_golang_apps install_go.sh generate_system_bazelrc .bazelversion /scripts/

RUN  \
  /scripts/install_apps && \
  /scripts/generate_system_bazelrc --user-root build_kvserver_amazonlinux2 && \
  /scripts/install_golang_apps && \
  rm -rf /scripts

ENV WORKSPACE=/src/workspace \
    PATH="${PATH}:/usr/local/go/bin"


text:
<?php

/** Internally used classes */
#require_once 'Zend/Pdf/Element/Array.php';
#require_once 'Zend/Pdf/Element/Name.php';
#require_once 'Zend/Pdf/Element/Numeric.php';

/** Zend_Pdf_Destination_Explicit */
#require_once 'Zend/Pdf/Destination/Explicit.php';

/**
 * Zend_Pdf_Destination_FitRectangle explicit detination
 *
 * Destination array: [page /FitR left bottom right top]
 *
 * Display the page designated by page, with its contents magnified just enough
 * to fit the rectangle specified by the coordinates left, bottom, right, and top
 * entirely within the window both horizontally and vertically. If the required
 * horizontal and vertical magnification factors are different, use the smaller of
 * the two, centering the rectangle within the window in the other dimension.
 *
 * @package    Zend_Pdf
 * @subpackage Destination
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Destination_FitRectangle extends Zend_Pdf_Destination_Explicit
{
    /**
     * Create destination object
     *
     * @param Zend_Pdf_Page|integer $page  Page object or page number
     * @param float $left    Left edge of displayed page
     * @param float $bottom  Bottom edge of displayed page
     * @param float $right   Right edge of displayed page
     * @param float $top     Top edge of displayed page
     * @return Zend_Pdf_Destination_FitRectangle
     * @throws Zend_Pdf_Exception
     */
    public static function create($page, $left, $bottom, $right, $top)
    {
        $destinationArray = new Zend_Pdf_Element_Array();

        if ($page instanceof Zend_Pdf_Page) {
            $destinationArray->items[] = $page->getPageDictionary();
        } else if (is_integer($page)) {
            $destinationArray->items[] = new Zend_Pdf_Element_Numeric($page);
        } else {
            #require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception('Page entry must be a Zend_Pdf_Page object or a page number.');
        }

        $destinationArray->items[] = new Zend_Pdf_Element_Name('FitR');
        $destinationArray->items[] = new Zend_Pdf_Element_Numeric($left);
        $destinationArray->items[] = new Zend_Pdf_Element_Numeric($bottom);
        $destinationArray->items[] = new Zend_Pdf_Element_Numeric($right);
        $destinationArray->items[] = new Zend_Pdf_Element_Numeric($top);

        return new Zend_Pdf_Destination_FitRectangle($destinationArray);
    }

    /**
     * Get left edge of the displayed page
     *
     * @return float
     */
    public function getLeftEdge()
    {
        return $this->_destinationArray->items[2]->value;
    }

    /**
     * Set left edge of the displayed page
     *
     * @param float $left
     * @return Zend_Pdf_Action_FitRectangle
     */
    public function setLeftEdge($left)
    {
        $this->_destinationArray->items[2] = new Zend_Pdf_Element_Numeric($left);
        return $this;
    }

    /**
     * Get bottom edge of the displayed page
     *
     * @return float
     */
    public function getBottomEdge()
    {
        return $this->_destinationArray->items[3]->value;
    }

    /**
     * Set bottom edge of the displayed page
     *
     * @param float $bottom
     * @return Zend_Pdf_Action_FitRectangle
     */
    public function setBottomEdge($bottom)
    {
        $this->_destinationArray->items[3] = new Zend_Pdf_Element_Numeric($bottom);
        return $this;
    }

    /**
     * Get right edge of the displayed page
     *
     * @return float
     */
    public function getRightEdge()
    {
        return $this->_destinationArray->items[4]->value;
    }

    /**
     * Set right edge of the displayed page
     *
     * @param float $right
     * @return Zend_Pdf_Action_FitRectangle
     */
    public function setRightEdge($right)
    {
        $this->_destinationArray->items[4] = new Zend_Pdf_Element_Numeric($right);
        return $this;
    }

    /**
     * Get top edge of the displayed page
     *
     * @return float
     */
    public function getTopEdge()
    {
        return $this->_destinationArray->items[5]->value;
    }

    /**
     * Set top edge of the displayed page
     *
     * @param float $top
     * @return Zend_Pdf_Action_FitRectangle
     */
    public function setTopEdge($top)
    {
        $this->_destinationArray->items[5] = new Zend_Pdf_Element_Numeric($top);
        return $this;
    }
}


text:
package v3

import (
	"context"

	"github.com/rancher/norman/controller"
	"github.com/rancher/norman/objectclient"
	"github.com/rancher/norman/resource"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/tools/cache"
)

var (
	GlobalRoleGroupVersionKind = schema.GroupVersionKind{
		Version: Version,
		Group:   GroupName,
		Kind:    "GlobalRole",
	}
	GlobalRoleResource = metav1.APIResource{
		Name:         "globalroles",
		SingularName: "globalrole",
		Namespaced:   false,
		Kind:         GlobalRoleGroupVersionKind.Kind,
	}

	GlobalRoleGroupVersionResource = schema.GroupVersionResource{
		Group:    GroupName,
		Version:  Version,
		Resource: "globalroles",
	}
)

func init() {
	resource.Put(GlobalRoleGroupVersionResource)
}

func NewGlobalRole(namespace, name string, obj GlobalRole) *GlobalRole {
	obj.APIVersion, obj.Kind = GlobalRoleGroupVersionKind.ToAPIVersionAndKind()
	obj.Name = name
	obj.Namespace = namespace
	return &obj
}

type GlobalRoleList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata,omitempty"`
	Items           []GlobalRole `json:"items"`
}

type GlobalRoleHandlerFunc func(key string, obj *GlobalRole) (runtime.Object, error)

type GlobalRoleChangeHandlerFunc func(obj *GlobalRole) (runtime.Object, error)

type GlobalRoleLister interface {
	List(namespace string, selector labels.Selector) (ret []*GlobalRole, err error)
	Get(namespace, name string) (*GlobalRole, error)
}

type GlobalRoleController interface {
	Generic() controller.GenericController
	Informer() cache.SharedIndexInformer
	Lister() GlobalRoleLister
	AddHandler(ctx context.Context, name string, handler GlobalRoleHandlerFunc)
	AddFeatureHandler(ctx context.Context, enabled func() bool, name string, sync GlobalRoleHandlerFunc)
	AddClusterScopedHandler(ctx context.Context, name, clusterName string, handler GlobalRoleHandlerFunc)
	AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name, clusterName string, handler GlobalRoleHandlerFunc)
	Enqueue(namespace, name string)
	Sync(ctx context.Context) error
	Start(ctx context.Context, threadiness int) error
}

type GlobalRoleInterface interface {
	ObjectClient() *objectclient.ObjectClient
	Create(*GlobalRole) (*GlobalRole, error)
	GetNamespaced(namespace, name string, opts metav1.GetOptions) (*GlobalRole, error)
	Get(name string, opts metav1.GetOptions) (*GlobalRole, error)
	Update(*GlobalRole) (*GlobalRole, error)
	Delete(name string, options *metav1.DeleteOptions) error
	DeleteNamespaced(namespace, name string, options *metav1.DeleteOptions) error
	List(opts metav1.ListOptions) (*GlobalRoleList, error)
	Watch(opts metav1.ListOptions) (watch.Interface, error)
	DeleteCollection(deleteOpts *metav1.DeleteOptions, listOpts metav1.ListOptions) error
	Controller() GlobalRoleController
	AddHandler(ctx context.Context, name string, sync GlobalRoleHandlerFunc)
	AddFeatureHandler(ctx context.Context, enabled func() bool, name string, sync GlobalRoleHandlerFunc)
	AddLifecycle(ctx context.Context, name string, lifecycle GlobalRoleLifecycle)
	AddFeatureLifecycle(ctx context.Context, enabled func() bool, name string, lifecycle GlobalRoleLifecycle)
	AddClusterScopedHandler(ctx context.Context, name, clusterName string, sync GlobalRoleHandlerFunc)
	AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name, clusterName string, sync GlobalRoleHandlerFunc)
	AddClusterScopedLifecycle(ctx context.Context, name, clusterName string, lifecycle GlobalRoleLifecycle)
	AddClusterScopedFeatureLifecycle(ctx context.Context, enabled func() bool, name, clusterName string, lifecycle GlobalRoleLifecycle)
}

type globalRoleLister struct {
	controller *globalRoleController
}

func (l *globalRoleLister) List(namespace string, selector labels.Selector) (ret []*GlobalRole, err error) {
	err = cache.ListAllByNamespace(l.controller.Informer().GetIndexer(), namespace, selector, func(obj interface{}) {
		ret = append(ret, obj.(*GlobalRole))
	})
	return
}

func (l *globalRoleLister) Get(namespace, name string) (*GlobalRole, error) {
	var key string
	if namespace != "" {
		key = namespace + "/" + name
	} else {
		key = name
	}
	obj, exists, err := l.controller.Informer().GetIndexer().GetByKey(key)
	if err != nil {
		return nil, err
	}
	if !exists {
		return nil, errors.NewNotFound(schema.GroupResource{
			Group:    GlobalRoleGroupVersionKind.Group,
			Resource: "globalRole",
		}, key)
	}
	return obj.(*GlobalRole), nil
}

type globalRoleController struct {
	controller.GenericController
}

func (c *globalRoleController) Generic() controller.GenericController {
	return c.GenericController
}

func (c *globalRoleController) Lister() GlobalRoleLister {
	return &globalRoleLister{
		controller: c,
	}
}

func (c *globalRoleController) AddHandler(ctx context.Context, name string, handler GlobalRoleHandlerFunc) {
	c.GenericController.AddHandler(ctx, name, func(key string, obj interface{}) (interface{}, error) {
		if obj == nil {
			return handler(key, nil)
		} else if v, ok := obj.(*GlobalRole); ok {
			return handler(key, v)
		} else {
			return nil, nil
		}
	})
}

func (c *globalRoleController) AddFeatureHandler(ctx context.Context, enabled func() bool, name string, handler GlobalRoleHandlerFunc) {
	c.GenericController.AddHandler(ctx, name, func(key string, obj interface{}) (interface{}, error) {
		if !enabled() {
			return nil, nil
		} else if obj == nil {
			return handler(key, nil)
		} else if v, ok := obj.(*GlobalRole); ok {
			return handler(key, v)
		} else {
			return nil, nil
		}
	})
}

func (c *globalRoleController) AddClusterScopedHandler(ctx context.Context, name, cluster string, handler GlobalRoleHandlerFunc) {
	c.GenericController.AddHandler(ctx, name, func(key string, obj interface{}) (interface{}, error) {
		if obj == nil {
			return handler(key, nil)
		} else if v, ok := obj.(*GlobalRole); ok && controller.ObjectInCluster(cluster, obj) {
			return handler(key, v)
		} else {
			return nil, nil
		}
	})
}

func (c *globalRoleController) AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name, cluster string, handler GlobalRoleHandlerFunc) {
	c.GenericController.AddHandler(ctx, name, func(key string, obj interface{}) (interface{}, error) {
		if !enabled() {
			return nil, nil
		} else if obj == nil {
			return handler(key, nil)
		} else if v, ok := obj.(*GlobalRole); ok && controller.ObjectInCluster(cluster, obj) {
			return handler(key, v)
		} else {
			return nil, nil
		}
	})
}

type globalRoleFactory struct {
}

func (c globalRoleFactory) Object() runtime.Object {
	return &GlobalRole{}
}

func (c globalRoleFactory) List() runtime.Object {
	return &GlobalRoleList{}
}

func (s *globalRoleClient) Controller() GlobalRoleController {
	s.client.Lock()
	defer s.client.Unlock()

	c, ok := s.client.globalRoleControllers[s.ns]
	if ok {
		return c
	}

	genericController := controller.NewGenericController(GlobalRoleGroupVersionKind.Kind+"Controller",
		s.objectClient)

	c = &globalRoleController{
		GenericController: genericController,
	}

	s.client.globalRoleControllers[s.ns] = c
	s.client.starters = append(s.client.starters, c)

	return c
}

type globalRoleClient struct {
	client       *Client
	ns           string
	objectClient *objectclient.ObjectClient
	controller   GlobalRoleController
}

func (s *globalRoleClient) ObjectClient() *objectclient.ObjectClient {
	return s.objectClient
}

func (s *globalRoleClient) Create(o *GlobalRole) (*GlobalRole, error) {
	obj, err := s.objectClient.Create(o)
	return obj.(*GlobalRole), err
}

func (s *globalRoleClient) Get(name string, opts metav1.GetOptions) (*GlobalRole, error) {
	obj, err := s.objectClient.Get(name, opts)
	return obj.(*GlobalRole), err
}

func (s *globalRoleClient) GetNamespaced(namespace, name string, opts metav1.GetOptions) (*GlobalRole, error) {
	obj, err := s.objectClient.GetNamespaced(namespace, name, opts)
	return obj.(*GlobalRole), err
}

func (s *globalRoleClient) Update(o *GlobalRole) (*GlobalRole, error) {
	obj, err := s.objectClient.Update(o.Name, o)
	return obj.(*GlobalRole), err
}

func (s *globalRoleClient) Delete(name string, options *metav1.DeleteOptions) error {
	return s.objectClient.Delete(name, options)
}

func (s *globalRoleClient) DeleteNamespaced(namespace, name string, options *metav1.DeleteOptions) error {
	return s.objectClient.DeleteNamespaced(namespace, name, options)
}

func (s *globalRoleClient) List(opts metav1.ListOptions) (*GlobalRoleList, error) {
	obj, err := s.objectClient.List(opts)
	return obj.(*GlobalRoleList), err
}

func (s *globalRoleClient) Watch(opts metav1.ListOptions) (watch.Interface, error) {
	return s.objectClient.Watch(opts)
}

// Patch applies the patch and returns the patched deployment.
func (s *globalRoleClient) Patch(o *GlobalRole, patchType types.PatchType, data []byte, subresources ...string) (*GlobalRole, error) {
	obj, err := s.objectClient.Patch(o.Name, o, patchType, data, subresources...)
	return obj.(*GlobalRole), err
}

func (s *globalRoleClient) DeleteCollection(deleteOpts *metav1.DeleteOptions, listOpts metav1.ListOptions) error {
	return s.objectClient.DeleteCollection(deleteOpts, listOpts)
}

func (s *globalRoleClient) AddHandler(ctx context.Context, name string, sync GlobalRoleHandlerFunc) {
	s.Controller().AddHandler(ctx, name, sync)
}

func (s *globalRoleClient) AddFeatureHandler(ctx context.Context, enabled func() bool, name string, sync GlobalRoleHandlerFunc) {
	s.Controller().AddFeatureHandler(ctx, enabled, name, sync)
}

func (s *globalRoleClient) AddLifecycle(ctx context.Context, name string, lifecycle GlobalRoleLifecycle) {
	sync := NewGlobalRoleLifecycleAdapter(name, false, s, lifecycle)
	s.Controller().AddHandler(ctx, name, sync)
}

func (s *globalRoleClient) AddFeatureLifecycle(ctx context.Context, enabled func() bool, name string, lifecycle GlobalRoleLifecycle) {
	sync := NewGlobalRoleLifecycleAdapter(name, false, s, lifecycle)
	s.Controller().AddFeatureHandler(ctx, enabled, name, sync)
}

func (s *globalRoleClient) AddClusterScopedHandler(ctx context.Context, name, clusterName string, sync GlobalRoleHandlerFunc) {
	s.Controller().AddClusterScopedHandler(ctx, name, clusterName, sync)
}

func (s *globalRoleClient) AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name, clusterName string, sync GlobalRoleHandlerFunc) {
	s.Controller().AddClusterScopedFeatureHandler(ctx, enabled, name, clusterName, sync)
}

func (s *globalRoleClient) AddClusterScopedLifecycle(ctx context.Context, name, clusterName string, lifecycle GlobalRoleLifecycle) {
	sync := NewGlobalRoleLifecycleAdapter(name+"_"+clusterName, true, s, lifecycle)
	s.Controller().AddClusterScopedHandler(ctx, name, clusterName, sync)
}

func (s *globalRoleClient) AddClusterScopedFeatureLifecycle(ctx context.Context, enabled func() bool, name, clusterName string, lifecycle GlobalRoleLifecycle) {
	sync := NewGlobalRoleLifecycleAdapter(name+"_"+clusterName, true, s, lifecycle)
	s.Controller().AddClusterScopedFeatureHandler(ctx, enabled, name, clusterName, sync)
}

type GlobalRoleIndexer func(obj *GlobalRole) ([]string, error)

type GlobalRoleClientCache interface {
	Get(namespace, name string) (*GlobalRole, error)
	List(namespace string, selector labels.Selector) ([]*GlobalRole, error)

	Index(name string, indexer GlobalRoleIndexer)
	GetIndexed(name, key string) ([]*GlobalRole, error)
}

type GlobalRoleClient interface {
	Create(*GlobalRole) (*GlobalRole, error)
	Get(namespace, name string, opts metav1.GetOptions) (*GlobalRole, error)
	Update(*GlobalRole) (*GlobalRole, error)
	Delete(namespace, name string, options *metav1.DeleteOptions) error
	List(namespace string, opts metav1.ListOptions) (*GlobalRoleList, error)
	Watch(opts metav1.ListOptions) (watch.Interface, error)

	Cache() GlobalRoleClientCache

	OnCreate(ctx context.Context, name string, sync GlobalRoleChangeHandlerFunc)
	OnChange(ctx context.Context, name string, sync GlobalRoleChangeHandlerFunc)
	OnRemove(ctx context.Context, name string, sync GlobalRoleChangeHandlerFunc)
	Enqueue(namespace, name string)

	Generic() controller.GenericController
	ObjectClient() *objectclient.ObjectClient
	Interface() GlobalRoleInterface
}

type globalRoleClientCache struct {
	client *globalRoleClient2
}

type globalRoleClient2 struct {
	iface      GlobalRoleInterface
	controller GlobalRoleController
}

func (n *globalRoleClient2) Interface() GlobalRoleInterface {
	return n.iface
}

func (n *globalRoleClient2) Generic() controller.GenericController {
	return n.iface.Controller().Generic()
}

func (n *globalRoleClient2) ObjectClient() *objectclient.ObjectClient {
	return n.Interface().ObjectClient()
}

func (n *globalRoleClient2) Enqueue(namespace, name string) {
	n.iface.Controller().Enqueue(namespace, name)
}

func (n *globalRoleClient2) Create(obj *GlobalRole) (*GlobalRole, error) {
	return n.iface.Create(obj)
}

func (n *globalRoleClient2) Get(namespace, name string, opts metav1.GetOptions) (*GlobalRole, error) {
	return n.iface.GetNamespaced(namespace, name, opts)
}

func (n *globalRoleClient2) Update(obj *GlobalRole) (*GlobalRole, error) {
	return n.iface.Update(obj)
}

func (n *globalRoleClient2) Delete(namespace, name string, options *metav1.DeleteOptions) error {
	return n.iface.DeleteNamespaced(namespace, name, options)
}

func (n *globalRoleClient2) List(namespace string, opts metav1.ListOptions) (*GlobalRoleList, error) {
	return n.iface.List(opts)
}

func (n *globalRoleClient2) Watch(opts metav1.ListOptions) (watch.Interface, error) {
	return n.iface.Watch(opts)
}

func (n *globalRoleClientCache) Get(namespace, name string) (*GlobalRole, error) {
	return n.client.controller.Lister().Get(namespace, name)
}

func (n *globalRoleClientCache) List(namespace string, selector labels.Selector) ([]*GlobalRole, error) {
	return n.client.controller.Lister().List(namespace, selector)
}

func (n *globalRoleClient2) Cache() GlobalRoleClientCache {
	n.loadController()
	return &globalRoleClientCache{
		client: n,
	}
}

func (n *globalRoleClient2) OnCreate(ctx context.Context, name string, sync GlobalRoleChangeHandlerFunc) {
	n.loadController()
	n.iface.AddLifecycle(ctx, name+"-create", &globalRoleLifecycleDelegate{create: sync})
}

func (n *globalRoleClient2) OnChange(ctx context.Context, name string, sync GlobalRoleChangeHandlerFunc) {
	n.loadController()
	n.iface.AddLifecycle(ctx, name+"-change", &globalRoleLifecycleDelegate{update: sync})
}

func (n *globalRoleClient2) OnRemove(ctx context.Context, name string, sync GlobalRoleChangeHandlerFunc) {
	n.loadController()
	n.iface.AddLifecycle(ctx, name, &globalRoleLifecycleDelegate{remove: sync})
}

func (n *globalRoleClientCache) Index(name string, indexer GlobalRoleIndexer) {
	err := n.client.controller.Informer().GetIndexer().AddIndexers(map[string]cache.IndexFunc{
		name: func(obj interface{}) ([]string, error) {
			if v, ok := obj.(*GlobalRole); ok {
				return indexer(v)
			}
			return nil, nil
		},
	})

	if err != nil {
		panic(err)
	}
}

func (n *globalRoleClientCache) GetIndexed(name, key string) ([]*GlobalRole, error) {
	var result []*GlobalRole
	objs, err := n.client.controller.Informer().GetIndexer().ByIndex(name, key)
	if err != nil {
		return nil, err
	}
	for _, obj := range objs {
		if v, ok := obj.(*GlobalRole); ok {
			result = append(result, v)
		}
	}

	return result, nil
}

func (n *globalRoleClient2) loadController() {
	if n.controller == nil {
		n.controller = n.iface.Controller()
	}
}

type globalRoleLifecycleDelegate struct {
	create GlobalRoleChangeHandlerFunc
	update GlobalRoleChangeHandlerFunc
	remove GlobalRoleChangeHandlerFunc
}

func (n *globalRoleLifecycleDelegate) HasCreate() bool {
	return n.create != nil
}

func (n *globalRoleLifecycleDelegate) Create(obj *GlobalRole) (runtime.Object, error) {
	if n.create == nil {
		return obj, nil
	}
	return n.create(obj)
}

func (n *globalRoleLifecycleDelegate) HasFinalize() bool {
	return n.remove != nil
}

func (n *globalRoleLifecycleDelegate) Remove(obj *GlobalRole) (runtime.Object, error) {
	if n.remove == nil {
		return obj, nil
	}
	return n.remove(obj)
}

func (n *globalRoleLifecycleDelegate) Updated(obj *GlobalRole) (runtime.Object, error) {
	if n.update == nil {
		return obj, nil
	}
	return n.update(obj)
}


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.completion;

import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.openapi.progress.ProgressManager;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;

public abstract class PrefixMatcher {
  public static final PrefixMatcher ALWAYS_TRUE = new PlainPrefixMatcher("");
  protected final String myPrefix;

  protected PrefixMatcher(String prefix) {
    myPrefix = prefix;
  }

  public boolean prefixMatches(@NotNull LookupElement element) {
    for (String s : element.getAllLookupStrings()) {
      if (prefixMatches(s)) {
        return true;
      }
    }
    return false;
  }

  public boolean isStartMatch(LookupElement element) {
    for (String s : element.getAllLookupStrings()) {
      if (isStartMatch(s)) {
        return true;
      }
    }
    return false;
  }

  public boolean isStartMatch(String name) {
    return prefixMatches(name);
  }

  public abstract boolean prefixMatches(@NotNull String name);

  @NotNull
  public final String getPrefix() {
    return myPrefix;
  }

  @NotNull public abstract PrefixMatcher cloneWithPrefix(@NotNull String prefix);

  public int matchingDegree(String string) {
    return 0;
  }

  /**
   * Filters _names for strings that match given matcher and sorts them.
   * "Start matching" items go first, then others.
   * Within both groups, names are sorted lexicographically in a case-insensitive way.
   */
  public LinkedHashSet<String> sortMatching(Collection<String> _names) {
    ProgressManager.checkCanceled();
    if (getPrefix().isEmpty()) {
      return new LinkedHashSet<>(_names);
    }

    List<String> sorted = new ArrayList<>();
    for (String name : _names) {
      if (prefixMatches(name)) {
        sorted.add(name);
      }
    }

    ProgressManager.checkCanceled();
    sorted.sort(String.CASE_INSENSITIVE_ORDER);
    ProgressManager.checkCanceled();

    LinkedHashSet<String> result = new LinkedHashSet<>();
    for (String name : sorted) {
      if (isStartMatch(name)) {
        result.add(name);
      }
    }

    ProgressManager.checkCanceled();

    result.addAll(sorted);
    return result;
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//Dtd XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/Dtd/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link rel="stylesheet" type="text/css" href="../shiny.css"/>
<title>IKEqC Score Detail for A.S. XXXV</title>

Interkingdom Equestrian Competition

Home

AS XXXV (35)

AS XXXVI (36)

AS XXXVII (37)

AS XXXVIII (38)

AS XXXIX (39)

AS XL (40)

AS XLI (41)

AS XLII (42)

AS XLIII (43)

AS XLIV (44)

AS XLV (45)

AS XLVI (46)

AS XLVII (47)

AS XLVIII (48)

AS XLIX (49)

AS L (50)

Score Detail for
AS XXXV

Score Details for Tracy

Participant:

Horse:

Kingdom:

Event:

Division:

Tracy

.

Artemesia

Destriers Bralse

Intermediate, 30 feet

Behead the Target!

Course Time in Seconds: 35.02

 Penalty: 10 Bonus:

Behead the Target Score:

Tilting at the Rings!

Number of rings of each size collected:

1" Rings: 0 2" Rings: 0 3" Rings: 1

4" Rings: 0 5" Rings: 0 6" Rings: 1

Rings Score:

Total Score: 70

This page, and its scripts, are based on code created by Sandor Dosa.

Emails sent to lord (dot) sandor (dot) dosa (at) gmail (dot) com will find him.

This is version 0.93a of the scorekeeper script, last updated 27 August 2001. ©2001 ADG

HTML and CSS by Doucette de Verdun, chestnutmare at gmail (dot) com, ©2015

Site last updated 13 June 2015


text:
package database

import (
	"bytes"
	"encoding/gob"
	"fmt"
	"os"
	"path"
	"time"

	"github.com/boltdb/bolt"
)

// BoltDB database structure
type BoltDB struct {
	Name string
	DB   *bolt.DB
}

func newBoltDb() *BoltDB {
	return &BoltDB{
		Name: "bolt.DB",
	}
}

//NewBoltDBProvider returns a bolt based database that conforms
//to the DBProvider interface
func NewBoltDBProvider() *BoltDB {
	return newBoltDb()
}

// DbInit initialize Bolt database
func (db *BoltDB) DbInit(dbDir, dbFile string) error {

	if err := os.MkdirAll(dbDir, 0755); err != nil {
		return fmt.Errorf("Unable to create db directory (%s) %v", dbDir, err)
	}

	dbPath := path.Join(dbDir, dbFile)

	options := bolt.Options{
		Timeout: 3 * time.Second,
	}

	var err error
	db.DB, err = bolt.Open(dbPath, 0644, &options)
	if err != nil {
		return fmt.Errorf("initDb failed %v", err)
	}

	return err
}

// DbClose closes Bolt database
func (db *BoltDB) DbClose() error {
	return db.DB.Close()
}

// DbTableRebuild builds bolt table into memory
func (db *BoltDB) DbTableRebuild(table DbTable) error {
	tables := []string{table.Name()}
	if err := db.DbTablesInit(tables); err != nil {
		return fmt.Errorf("dbInit failed %v", err)
	}

	table.NewTable()

	err := db.DB.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(table.Name()))

		err := b.ForEach(func(k, v []byte) error {
			vr := bytes.NewReader(v)

			val := table.NewElement()
			if err := gob.NewDecoder(vr).Decode(val); err != nil {
				return fmt.Errorf("Decode Error: %v %v %v", string(k), string(v), err)
			}
			Logger.Infof("%v key=%v, value=%v\n", table, string(k), val)

			return table.Add(string(k), val)
		})
		return err
	})
	return err
}

// DbTablesInit initializes list of tables in Bolt
func (db *BoltDB) DbTablesInit(tables []string) (err error) {

	Logger.Infof("dbInit Tables")
	for i, table := range tables {
		Logger.Infof("table[%v] := %v, %v", i, table, []byte(table))
	}

	err = db.DB.Update(func(tx *bolt.Tx) error {
		for _, table := range tables {
			_, err := tx.CreateBucketIfNotExists([]byte(table))
			if err != nil {
				return fmt.Errorf("Bucket creation error: %v %v", table, err)
			}
		}
		return nil
	})

	if err != nil {
		Logger.Errorf("Table creation error %v", err)
	}

	return err
}

// DbAdd adds a new element to table in Bolt database
func (db *BoltDB) DbAdd(table string, key string, value interface{}) (err error) {
	err = db.DB.Update(func(tx *bolt.Tx) error {
		var v bytes.Buffer

		if err := gob.NewEncoder(&v).Encode(value); err != nil {
			Logger.Errorf("Encode Error: %v %v", err, value)
			return err
		}

		bucket := tx.Bucket([]byte(table))
		if bucket == nil {
			bucket, err = tx.CreateBucketIfNotExists([]byte(table))
			if err != nil {
				return fmt.Errorf("Bucket %v creation failed", table)
			}
		}

		err = bucket.Put([]byte(key), v.Bytes())
		if err != nil {
			return fmt.Errorf("Key Store error: %v %v %v %v", table, key, value, err)
		}
		return nil
	})

	return err
}

// DbDelete deletes an element from table in Bolt database
func (db *BoltDB) DbDelete(table string, key string) (err error) {

	err = db.DB.Update(func(tx *bolt.Tx) error {
		bucket := tx.Bucket([]byte(table))
		if bucket == nil {
			return fmt.Errorf("Bucket %v not found", table)
		}

		data := bucket.Get([]byte(key))
		if len(data) == 0 {
			return fmt.Errorf("Key is not found: %v", key)
		}

		err = bucket.Delete([]byte(key))
		if err != nil {
			return fmt.Errorf("Key Delete error: %v %v ", key, err)
		}
		return nil
	})

	return err
}

// DbGet obtains value by key from table
func (db *BoltDB) DbGet(table string, key string, dbTable DbTable) (interface{}, error) {

	var elem interface{}

	err := db.DB.View(func(tx *bolt.Tx) error {
		bucket := tx.Bucket([]byte(table))
		if bucket == nil {
			return fmt.Errorf("Bucket %v not found", table)
		}
		elem = dbTable.NewElement()
		data := bucket.Get([]byte(key))

		if data == nil {
			return nil
		}

		vr := bytes.NewReader(data)
		if err := gob.NewDecoder(vr).Decode(elem); err != nil {
			return err
		}
		return nil
	})

	return elem, err
}

// DbGetAll gets all elements from specific table
func (db *BoltDB) DbGetAll(table string, dbTable DbTable) (elements []interface{}, err error) {
	err = db.DB.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(table))

		if b != nil {
			err := b.ForEach(func(key, value []byte) error {
				vr := bytes.NewReader(value)
				elem := dbTable.NewElement()
				if err := gob.NewDecoder(vr).Decode(elem); err != nil {
					return err
				}
				elements = append(elements, elem)
				return nil
			})
			return err
		}
		return nil
	})

	return elements, err
}


text:
<?php

/*****************************************************************
* CaptchaSecurityImages
******************************************************************/

class CaptchaSecurityImages {
	var $font = 'monofont.ttf';

	function generateCode($characters) {
		/* list all possible characters, similar looking characters and vowels have been removed */
		$possible = '23456789bcdfghjkmnpqrstvwxyz';
		$code = '';
		$i = 0;

		while ($i < $characters) {
			$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1); $i++;
		}
		return $code;
	}

	function generateSecurityImage($width='120',$height='40',$characters='6', $font = 'monofont.ttf') {
		$this->font = $font;
		$code = $this->generateCode($characters);
		/* font size will be 75% of the image height */
		$font_size = $height * 0.75;
		$image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
		/* set the colours */
		$background_color = imagecolorallocate($image, 255, 255, 255);
		$text_color = imagecolorallocate($image, 20, 40, 100);
		$noise_color = imagecolorallocate($image, 100, 120, 180);
		/* generate random dots in background */
		for( $i=0; $i<($width*$height)/3; $i++ ) {
			imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
		}
		/* generate random lines in background */
		for( $i=0; $i<($width*$height)/150; $i++ ) {
			imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
		}
		/* create textbox and add text */
		$textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
		$x = ($width - $textbox[4])/2;
		$y = ($height - $textbox[5])/2;
		imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
		/* output captcha image to browser */
		header('Content-Type: text');
		imagejpeg($image);
		imagedestroy($image);
		return $code;
	}
}


text:
@class BrandOpenSpecificViewHandler, ClickCommandRequestInfo, CustomMenuToolView, CustomSubMenuFloatView, MMBizMenuInfo, NSMutableArray, NSString;

@interface BrandCustomStyleUILogicController : BrandStyleUILogicController <CustomMenuToolViewDelegate, CustomSubMenuFloatViewDelegate, CameraScanLogicDelegate, CameraScanUIDelegate, WCActionSheetDelegate, IBrandCustomReportExt, BrandOpenSpecificViewHandlerDelegate, IUiUtilExt>
{
    CustomMenuToolView *m_menuToolView;
    CustomSubMenuFloatView *m_subMenuFloatView;
    MMBizMenuInfo *m_menuData;
    _Bool m_isInMenuMode;
    _Bool m_isMsgReceiving;
    BrandOpenSpecificViewHandler *_openSpecificViewHandler;
    _Bool m_hasInit;
    ClickCommandRequestInfo *m_reportInfo;
    _Bool m_hasSendCgiSuccess;
    NSMutableArray *m_pickImageMd5List;
}

@property(retain, nonatomic) NSMutableArray *m_pickImageMd5List; // @synthesize m_pickImageMd5List;
@property(retain, nonatomic) ClickCommandRequestInfo *m_reportInfo; // @synthesize m_reportInfo;
@property(retain, nonatomic) MMBizMenuInfo *m_menuData; // @synthesize m_menuData;
@property(retain, nonatomic) CustomSubMenuFloatView *m_subMenuFloatView; // @synthesize m_subMenuFloatView;
@property(retain, nonatomic) CustomMenuToolView *m_menuToolView; // @synthesize m_menuToolView;
- (void).cxx_destruct;
- (_Bool)isNoNeedShowNormalToolView;
- (void)updateIfCreateToolView:(id)arg1;
- (void)showAlertViewForMenuUpdated;
- (void)removeCustomToolView;
- (void)updateIfViewDidAppear;
- (void)updateIfViewWillAppear;
- (void)addMsgForUsr:(id)arg1;
- (void)processLocationDidFinish;
- (void)saveAchievedImageMd5:(id)arg1;
- (_Bool)shouldSaveAchievedImageMd5;
- (void)processImageDidFinish;
- (void)processImageDidCancel;
- (_Bool)shouldHideOrginInputToolView;
- (double)getCustomizedAreaWidth;
- (void)setLastMenuMode:(_Bool)arg1;
- (_Bool)getLastMenuMode;
- (_Bool)canReloadViewIfMemoryWarning;
- (_Bool)CanRotateOrientation;
- (_Bool)isShakeEnabled;
- (void)onTopBarFrameChanged;
- (void)updateFloatContentView;
- (_Bool)hasDraft;
- (id)buttonListFromArr:(id)arg1;
- (id)getSubMenuInfoByIndex:(long long)arg1;
- (id)getMenuInfo;
- (void)stopReceiveMsg;
- (void)startReceiveMsg;
- (_Bool)shouldDismissCurrentViewController;
- (void)cleanPickImageMd5List;
- (void)addItem2PickImageMd5List:(id)arg1;
- (id)getPickImageMd5List;
- (void)createCameraScanViewController;
- (void)SendClickNotify:(id)arg1 ClickCommandRequestInfo:(id)arg2;
- (void)onReportActionEventAndContentXML:(id)arg1;
- (id)getCDATAWithJSON:(id)arg1;
- (void)onRecordActionEvent:(id)arg1 toBrand:(id)arg2;
- (void)onReportClickEvent:(id)arg1 toBrand:(id)arg2;
- (void)finishedChangeToInputMode;
- (void)onChangeToInputMode;
- (void)finishedChangeToMenuMode;
- (void)swichToolViewToCustomView;
- (void)changeToMenuMode;
- (_Bool)shouldShowChangeModeBtn;
- (void)actionSheet:(id)arg1 clickedButtonAtIndex:(long long)arg2;
- (_Bool)shouldDirectShowImagePicker;
- (void)obtainScanResultDidFinish:(id)arg1;
- (_Bool)shouldBackToSessionImmediately;
- (_Bool)shouldObtainScanResult;
- (void)onJumpToPOIView:(id)arg1;
- (void)onJumpToPicView:(id)arg1;
- (void)onJumpToScanView:(id)arg1;
- (void)handleOpenSpecificView:(id)arg1;
- (_Bool)isOpenNativeUrl:(id)arg1;
- (_Bool)isWeGoRecommed:(id)arg1;
- (_Bool)isOpenSpecificView:(id)arg1;
- (void)onDisconnectDevice;
- (void)onConnectDevice;
- (_Bool)onJumpToNativeView:(id)arg1;
- (void)onJumpToWebView:(id)arg1;
- (void)onRecordActionEvent:(id)arg1;
- (void)onReportClickEvent:(id)arg1;
- (void)onChangeToMenuMode:(id)arg1;
- (void)onSubMenuDismiss;
- (void)onSubMenuPresentWithIndex:(long long)arg1 ArrowX:(double)arg2;
- (void)createMenuToolView;
- (void)loadMenuData;
- (id)initWithContact:(id)arg1 WithDelegate:(id)arg2;
- (void)dealloc;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
from django.apps import AppConfig

class CowConfig(AppConfig):
    name = 'cow'


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Kinect;
using System.Windows.Media.Media3D;

namespace KinectWithHomeAssistant
{
    class ObjLine
    {
        private Point3D objPoint = new Point3D();
        private Vector3D objVector = new Vector3D();

        // Takes in elbow point and hand point to determine vectors
        public ObjLine(CameraSpacePoint Point_1, CameraSpacePoint Point_2)
        {
            objPoint.X = Point_1.X;
            objPoint.Y = Point_1.Y;
            objPoint.Z = Point_1.Z;

            objVector.X = Point_2.X - Point_1.X;
            objVector.Y = Point_2.Y - Point_1.Y;
            objVector.Z = Point_2.Z - Point_2.Z;
        }

        public Point3D Point { get { return objPoint; } }

        public Vector3D Vector { get { return objVector; } }

        public Point3D LineIntersect(ObjLine Line)
        {
            // Find new cross product of the lines
            Vector3D perpendicularFromLine1ToLine2 = Vector3D.CrossProduct(Line.Vector, Vector3D.CrossProduct(this.Vector, Line.Vector));
            Vector3D perpendicularFromLine2ToLine1 = Vector3D.CrossProduct(this.Vector, Vector3D.CrossProduct(Line.Vector, this.Vector));

            // Use Max Coordinates if lines are parallel
            if (perpendicularFromLine1ToLine2 == new Vector3D(0, 0, 0))
            {
                return new Point3D(double.MaxValue, double.MaxValue, double.MaxValue);
            }

            // Finds ths othogonal projections, QP and PQ
            Vector3D orthoVector1 = new Vector3D(Line.Point.X - this.Point.X, Line.Point.Y - this.Point.Y, Line.Point.Z - Line.Point.Z);
            Vector3D orthoVector2 = new Vector3D(this.Point.X - Line.Point.X, this.Point.Y - Line.Point.Y, this.Point.Z - Line.Point.Z);

            // Create dot product of two lines
            double dotProduct1 = Vector3D.DotProduct(perpendicularFromLine1ToLine2, orthoVector1);
            double dotProduct2 = Vector3D.DotProduct(perpendicularFromLine2ToLine1, orthoVector2);

            // Find positions of points
            Point3D point1 = Line.Point + Vector3D.Multiply(Line.Vector, dotProduct1);
            Point3D point2 = Line.Point + Vector3D.Multiply(Line.Vector, dotProduct2);

            double midX = (point1.X + point2.X) / 2;
            double midY = (point1.Y + point2.Y) / 2;
            double midZ = (point1.Z + point2.Z) / 2;

            // Return mid point
            return new Point3D(midX, midY, midZ);
        }
    }
}


text:
@interface MOBProjectionEPSG6577 : MOBProjection

@end


text:
package Characters;

import Item.Armor;
import Item.ArmorType;
import Item.Weapon;
import Item.WeaponType;
import PartyManagement.Party;
import Utilities.Display;
import Utilities.TestString;

import java.util.Scanner;

/**
 * Created by SaraPage on 4/29/2016.
 */
public abstract class A_Hero extends A_Character
{
	public A_Hero(String name, int health, int power, int cunning, ArmorType armorType,
				  Armor armor, WeaponType weaponType, Weapon weapon)
	{
		super(name, health, power, cunning, armorType, armor, weaponType, weapon, CreatureType.Humanoid);
	}

	public abstract boolean specialAbility(Party heroes, Party monsters);

	public boolean takeAction(Party heroes, Party monsters)
	{
		int choice;
		boolean cancel, noTurn, noSpecial;

		noTurn = conditions.cannotAttack();
		noSpecial = conditions.cannotUseSpecial();

		if(conditions.confusedEffect(this, heroes, monsters))
		{
			noTurn = true;
		}

		if(getDefeated())
		{
			return false;
		}

		resetTurn();

		if(noTurn)
		{
			endTurn();
			return false;
		}

		monsters.sortDefeated();
		heroes.sortDefeated();

		do
		{
			cancel = false;
			Display.displayMessage("It's " + getName() + "'s turn!\n" + battleDisplay());
			System.out.print("1.) Attack\n" +
					                   "2.) Defend\n" +
					                   "3.) Use Special\n" +
					                   "4.) Use Item\n" +
									   "5.) View Stats\n" +
					                   "6.) Run\n");
			choice = TestString.ensureInt(7);
			switch(choice)
			{
				case 1:
					cancel = doAttack(heroes, monsters);
					break;
				case 2:
					conditions.defend();
					break;
				case 3:
					if(noSpecial)
					{
						Display.displayMessage(getName() + " is exhausted and can't use their special abilities!");
						cancel = true;
					}
					else
					{
						cancel = specialAbility(heroes, monsters);
					}
					break;
				case 4:
					cancel = heroes.consumePotion();
					break;
				case 5:
					displayPartyStats(heroes);
					cancel = true;
					break;
				case 6:
					return tryToRun(heroes, monsters);
				case 7:
					dealLotsOfDamage(monsters);
					break;
			}

		}
		while(choice < 1 || choice > 7 || cancel);
		endTurn();
		return false;
	}

	private void dealLotsOfDamage(Party party)
	{
		for(A_Character character : party)
		{
			if(!character.getDefeated())
			{
				character.takeDamage(100);
			}
		}
	}

	private void displayPartyStats(Party party)
	{
		party.displayStats();
	}

	protected int pickCharacter(Party party)
	{
		int index = 1;
		for(int x = 0; x < party.size(); x++)
		{
			Display.displayMessage(index + ".)" + party.getCharacter(x).battleDisplay());
			index++;
		}
		return index;
	}

	protected int ensureInput(Scanner input, int itemIndex)
	{
		String validInput;
		int toUse = -1;
		do {
			validInput = input.nextLine();

			try
			{
				toUse = Integer.parseInt(validInput);
			}
			catch (NumberFormatException e)
			{
				toUse = -1;
			}

		}while(toUse < 1 || toUse > itemIndex);
		return toUse;
	}

	private boolean tryToRun(Party heroes, Party monsters)
	{
		Display.displayMessage("You attempt to run!");
		int chanceToRun = 0;//rand.nextInt(3*monsters.size()/heroes.size());
		if(chanceToRun == 0)
		{
			Display.displayMessage("You successfully escaped!");
			heroes.fixParty();
			return true;
		}
		Display.displayMessage("But they caught you!");
		return false;
	}

	private boolean doAttack(Party heroes, Party monsters)
	{
		int index = 1;
		int toAttack;
		for(int x = 0; x < monsters.size(); x++)
		{
			Display.displayMessage(index + ".) " + monsters.getCharacter(x).battleDisplay());
			index++;
		}

		Display.displayMessage(index + ".) cancel");
		toAttack = TestString.ensureInt(index);

		if(toAttack >= index)
		{
			return true;
		}
		else
		{
			this.attack(monsters.getCharacter(toAttack - 1));
			monsters.sortDefeated();
		}
		return false;
	}

	public void gainExperience(int experience)
	{
		Display.displayMessage(getName() + " gained " + experience +" experience!");
		super.gainExperience(experience);
	}

	public boolean canLevel()
	{
		if(super.canLevel())
		{
			Display.displayMessage(getName() + " leveled up!");
		}
		return super.canLevel();
	}
}


text:
require "test_helper"
require "gds_api/test_helpers/content_store"

class TravelAdviceControllerTest < ActionController::TestCase
  include GdsApi::TestHelpers::ContentStore

  context "GET index" do
    context "given countries exist" do
      setup do
        @content_item = GovukSchemas::Example.find("travel_advice_index", example_name: "index")
        base_path = @content_item.fetch("base_path")

        stub_content_store_has_item(base_path, @content_item)
      end

      should "be a successful request" do
        get :index

        assert response.successful?
      end

      should "render the index template" do
        get :index

        assert_template "index"
      end

      should "set cache-control headers" do
        get :index

        honours_content_store_ttl
      end

      context "requesting atom" do
        setup do
          get :index, format: "atom"
        end

        should "return an aggregate of country atom feeds" do
          assert_equal 200, response.status
          assert_equal "application/atom+xml; charset=utf-8", response.headers["Content-Type"]
        end

        should "set cache-control headers to 5 mins" do
          assert_equal "max-age=#{5.minutes.to_i}, public", response.headers["Cache-Control"]
        end

        should "set Access-Control-Allow-Origin header" do
          assert_equal "*", response.headers["Access-Control-Allow-Origin"]
        end
      end
    end
  end
end


text:
from mock import call, patch, MagicMock

from test_utils import CharmTestCase

import nova_compute_utils as utils

_reg = utils.register_configs
_map = utils.restart_map

utils.register_configs = MagicMock()
utils.restart_map = MagicMock()

import nova_compute_hooks as hooks

utils.register_configs = _reg
utils.restart_map = _map

TO_PATCH = [
    # charmhelpers.core.hookenv
    'Hooks',
    'config',
    'log',
    'relation_get',
    'relation_ids',
    'relation_set',
    'service_name',
    'unit_get',
    # charmhelpers.core.host
    'apt_install',
    'apt_update',
    'filter_installed_packages',
    'restart_on_change',
    # charmhelpers.contrib.openstack.utils
    'configure_installation_source',
    'openstack_upgrade_available',
    # nova_compute_utils
    #'PACKAGES',
    'create_libvirt_secret',
    'restart_map',
    'determine_packages',
    'import_authorized_keys',
    'import_keystone_ca_cert',
    'initialize_ssh_keys',
    'migration_enabled',
    'do_openstack_upgrade',
    'network_manager',
    'neutron_plugin_attribute',
    'neutron_plugin',
    'public_ssh_key',
    'register_configs',
    # misc_utils
    'ensure_ceph_keyring',
    'execd_preinstall'
]

def fake_filter(packages):
    return packages

class NovaComputeRelationsTests(CharmTestCase):

    def setUp(self):
        super(NovaComputeRelationsTests, self).setUp(hooks,
                                                     TO_PATCH)
        self.config.side_effect = self.test_config.get
        self.filter_installed_packages.side_effect = fake_filter

    def test_install_hook(self):
        repo = 'cloud:precise-grizzly'
        self.test_config.set('openstack-origin', repo)
        self.determine_packages.return_value = ['foo', 'bar']
        hooks.install()
        self.configure_installation_source.assert_called_with(repo)
        self.assertTrue(self.apt_update.called)
        self.apt_install.assert_called_with(['foo', 'bar'], fatal=True)
        self.execd_preinstall.assert_called()

    def test_config_changed_with_upgrade(self):
        self.openstack_upgrade_available.return_value = True
        hooks.config_changed()
        self.assertTrue(self.do_openstack_upgrade.called)

    @patch.object(hooks, 'compute_joined')
    def test_config_changed_with_migration(self, compute_joined):
        self.migration_enabled.return_value = True
        self.test_config.set('migration-auth-type', 'ssh')
        self.relation_ids.return_value = [
            'cloud-compute:0',
            'cloud-compute:1'
        ]
        hooks.config_changed()
        ex = [
            call('cloud-compute:0'),
            call('cloud-compute:1'),
        ]
        self.assertEquals(ex, compute_joined.call_args_list)

    @patch.object(hooks, 'compute_joined')
    def test_config_changed_no_upgrade_no_migration(self, compute_joined):
        self.openstack_upgrade_available.return_value = False
        self.migration_enabled.return_value = False
        hooks.config_changed()
        self.assertFalse(self.do_openstack_upgrade.called)
        self.assertFalse(compute_joined.called)

    def test_amqp_joined(self):
        hooks.amqp_joined()
        self.relation_set.assert_called_with(
            username='nova', vhost='openstack',
            relation_id=None)

    @patch.object(hooks, 'CONFIGS')
    def test_amqp_changed_missing_relation_data(self, configs):
        configs.complete_contexts = MagicMock()
        configs.complete_contexts.return_value = []
        hooks.amqp_changed()
        self.log.assert_called_with(
            'amqp relation incomplete. Peer not ready?'
        )

    def _amqp_test(self, configs, quantum=False):
        configs.complete_contexts = MagicMock()
        configs.complete_contexts.return_value = ['amqp']
        configs.write = MagicMock()
        if quantum:
            self.network_manager.return_value = 'quantum'
            self.neutron_plugin.return_value = 'ovs'
        hooks.amqp_changed()

    @patch.object(hooks, 'CONFIGS')
    def test_amqp_changed_with_data_no_quantum(self, configs):
        self._amqp_test(configs, quantum=False)
        self.assertEquals([call('/etc/nova/nova.conf')],
                          configs.write.call_args_list)

    @patch.object(hooks, 'CONFIGS')
    def test_amqp_changed_with_data_and_quantum(self, configs):
        self._amqp_test(configs, quantum=True)
        self.assertEquals([call('/etc/nova/nova.conf'),
                           call('/etc/quantum/quantum.conf')],
                          configs.write.call_args_list)

    def test_db_joined(self):
        self.unit_get.return_value = 'nova.foohost.com'
        hooks.db_joined()
        self.relation_set.assert_called_with(relation_id=None,
                                             nova_database='nova',
                                             nova_username='nova',
                                             nova_hostname='nova.foohost.com')
        self.unit_get.assert_called_with('private-address')

    def test_db_joined_quantum_ovs(self):
        self.unit_get.return_value = 'nova.foohost.com'
        self.network_manager.return_value = 'quantum'
        self.neutron_plugin.return_value = 'ovs'
        hooks.db_joined(rid='shared-db:0')
        calls = [call(nova_database='nova',
                      nova_username='nova',
                      nova_hostname='nova.foohost.com',
                      relation_id='shared-db:0'),
                 call(neutron_database='neutron',
                      neutron_username='neutron',
                      neutron_hostname='nova.foohost.com',
                      relation_id='shared-db:0')]
        [self.assertIn(c, self.relation_set.call_args_list)
         for c in calls]
        self.unit_get.assert_called_with('private-address')

    def test_db_joined_quantum_nvp(self):
        self.unit_get.return_value = 'nova.foohost.com'
        self.network_manager.return_value = 'quantum'
        self.neutron_plugin.return_value = 'nvp'
        hooks.db_joined(rid='shared-db:0')
        calls = [call(nova_database='nova',
                      nova_username='nova',
                      nova_hostname='nova.foohost.com',
                      relation_id='shared-db:0')]
        # NVP plugin requires no DB access - check it was not
        # requested
        [self.assertIn(c, self.relation_set.call_args_list)
         for c in calls]
        self.unit_get.assert_called_with('private-address')

    @patch.object(hooks, 'CONFIGS')
    def test_db_changed_missing_relation_data(self, configs):
        configs.complete_contexts = MagicMock()
        configs.complete_contexts.return_value = []
        hooks.db_changed()
        self.log.assert_called_with(
            'shared-db relation incomplete. Peer not ready?'
        )

    def _shared_db_test(self, configs, quantum=False):
        configs.complete_contexts = MagicMock()
        configs.complete_contexts.return_value = ['shared-db']
        configs.write = MagicMock()
        if quantum:
            self.network_manager.return_value = 'quantum'
        hooks.db_changed()

    @patch.object(hooks, 'CONFIGS')
    def test_db_changed_with_data_no_quantum(self, configs):
        self._shared_db_test(configs, quantum=False)
        self.assertEquals([call('/etc/nova/nova.conf')],
                          configs.write.call_args_list)

    @patch.object(hooks, 'CONFIGS')
    def test_db_changed_with_data_and_quantum_ovs(self, configs):
        self.neutron_plugin_attribute.return_value = '/etc/quantum/plugin.conf'
        self.neutron_plugin.return_value = 'ovs'
        self._shared_db_test(configs, quantum=True)
        ex = [call('/etc/nova/nova.conf'), call('/etc/quantum/plugin.conf')]
        self.assertEquals(ex, configs.write.call_args_list)

    @patch.object(hooks, 'CONFIGS')
    def test_db_changed_with_data_and_quantum_nvp(self, configs):
        self.neutron_plugin_attribute.return_value = '/etc/quantum/plugin.conf'
        self.neutron_plugin.return_value = 'nvp'
        self._shared_db_test(configs, quantum=True)
        ex = [call('/etc/nova/nova.conf')]
        # NVP has no compute agent for neutron; check no config files generated
        self.assertEquals(ex, configs.write.call_args_list)

    @patch.object(hooks, 'CONFIGS')
    def test_image_service_missing_relation_data(self, configs):
        configs.complete_contexts = MagicMock()
        configs.complete_contexts.return_value = []
        hooks.image_service_changed()
        self.log.assert_called_with(
            'image-service relation incomplete. Peer not ready?'
        )

    @patch.object(hooks, 'CONFIGS')
    def test_image_service_with_relation_data(self, configs):
        configs.complete_contexts = MagicMock()
        configs.write = MagicMock()
        configs.complete_contexts.return_value = ['image-service']
        hooks.image_service_changed()
        configs.write.assert_called_with('/etc/nova/nova.conf')

    def test_compute_joined_no_migration(self):
        self.migration_enabled.return_value = False
        hooks.compute_joined()
        self.assertFalse(self.relation_set.called)

    def test_compute_joined_with_ssh_migration(self):
        self.migration_enabled.return_value = True
        self.test_config.set('migration-auth-type', 'ssh')
        self.public_ssh_key.return_value = 'foo'
        hooks.compute_joined()
        self.relation_set.assert_called_with(
            relation_id=None,
            ssh_public_key='foo',
            migration_auth_type='ssh'
        )
        hooks.compute_joined(rid='cloud-compute:2')
        self.relation_set.assert_called_with(
            relation_id='cloud-compute:2',
            ssh_public_key='foo',
            migration_auth_type='ssh'
        )

    def test_compute_changed(self):
        hooks.compute_changed()
        expected_funcs = [
            self.import_authorized_keys,
            self.import_keystone_ca_cert,
        ]
        for func in expected_funcs:
            self.assertTrue(func.called)

    def test_ceph_joined(self):
        hooks.ceph_joined()
        self.apt_install.assert_called_with(['ceph-common'], fatal=True)

    @patch.object(hooks, 'CONFIGS')
    def test_ceph_changed_missing_relation_data(self, configs):
        configs.complete_contexts = MagicMock()
        configs.complete_contexts.return_value = []
        hooks.ceph_changed()
        self.log.assert_called_with(
            'ceph relation incomplete. Peer not ready?'
        )

    @patch.object(hooks, 'CONFIGS')
    def test_ceph_changed_no_keyring(self, configs):
        configs.complete_contexts = MagicMock()
        configs.complete_contexts.return_value = ['ceph']
        self.ensure_ceph_keyring.return_value = False
        hooks.ceph_changed()
        self.log.assert_called_with(
            'Could not create ceph keyring: peer not ready?'
        )

    @patch.object(utils, 'service_name')
    @patch.object(hooks, 'CONFIGS')
    def test_ceph_changed_with_key_and_relation_data(self, configs,
                                                     service_name):
        configs.complete_contexts = MagicMock()
        configs.complete_contexts.return_value = ['ceph']
        configs.write = MagicMock()
        service_name.return_value = 'nova-compute'
        self.ensure_ceph_keyring.return_value = True
        hooks.ceph_changed()
        ex = [
            call('/var/lib/charm/nova-compute/ceph.conf'),
            call('/etc/ceph/secret.xml'),
            call('/etc/nova/nova.conf'),
        ]
        self.assertEquals(ex, configs.write.call_args_list)