text:
<?php

namespace PhpInk\Nami\CoreBundle\Plugin;

use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\RouteCollection;

class RoutingLoader extends Loader
{
    /**
     * Route is loaded
     * @var boolean
     */
    private $loaded = false;

    private $pluginPath;

    public function __construct($pluginPath)
    {
        $this->pluginPath = $pluginPath;
    }

    public function supports($resource, $type = null)
    {
        return $type === 'namiplugin';
    }

    public function load($resource, $type = null)
    {
        if ($this->loaded) {
            throw new \RuntimeException(
                'The plugin routing loader must not be run twice'
            );
        }

        // Add the plugin routes
        $routes   = new RouteCollection();
        $plugins = Registry::getInstance($this->pluginPath)->getRoutedPlugins();
        foreach ($plugins as $plugin => $routerFile) {
            $routes->addCollection(
                $this->import($routerFile)
            );
        }
        $this->loaded = true;
        return $routes;
    }
}


text:
<?php

require_once '../config/config-default.php';
require_once '../lib/database.php';
require_once '../lib/checkversion.php';
$input = json_decode(file_get_contents('php://input'));
if(isset($input->action) && $input->action == "getVersions") {
    $retval['from'] = getVersion($db);
    $retval['to'] = getExpectedVersion();
}
if(isset($input->action) && $input->action == "requestUpgrade") {
    $currentVersion = getVersion($db);
    $dbType = $config['db_type'];
    if($currentVersion < 1) {
        $sql["mysql"] = "
            CREATE TABLE IF NOT EXISTS remote (
                id int(11) NOT NULL AUTO_INCREMENT,
                record int(11) NOT NULL,
                description varchar(255) NOT NULL,
                type varchar(20) NOT NULL,
                security varchar(2000) NOT NULL,
                nonce varchar(255) DEFAULT NULL,
                PRIMARY KEY (id),
                KEY record (record)
            ) ENGINE=InnoDB  DEFAULT CHARSET=latin1;
            ALTER TABLE `remote`
                ADD CONSTRAINT `remote_ibfk_1` FOREIGN KEY (`record`) REFERENCES `records` (`id`);
            CREATE TABLE IF NOT EXISTS options (
                name varchar(255) NOT NULL,
                value varchar(2000) DEFAULT NULL,
                PRIMARY KEY (name)
            ) ENGINE=InnoDB  DEFAULT CHARSET=latin1;
            INSERT INTO options(name,value) VALUES ('schema_version', 1);
        ";
        $sql["pgsql"] = "INSERT INTO options(name,value) VALUES ('schema_version', 1);";
        $queries = explode(";", $sql[$dbType]);
        $db->beginTransaction();
        foreach ($queries as $query) {
            if (preg_replace('/\s+/', '', $query) != '') {
                $db->exec($query);
            }
        }
        $db->commit();
    }
    if($currentVersion < 2) {
        $sql["mysql"] = "
            ALTER TABLE permissions
              DROP FOREIGN KEY permissions_ibfk_1;
            ALTER TABLE permissions
              DROP FOREIGN KEY permissions_ibfk_2;
            ALTER TABLE permissions
              ADD CONSTRAINT permissions_ibfk_1 FOREIGN KEY (domain) REFERENCES domains (id) ON DELETE CASCADE;
            ALTER TABLE permissions
              ADD CONSTRAINT permissions_ibfk_2 FOREIGN KEY (user) REFERENCES user (id) ON DELETE CASCADE;
            ALTER TABLE remote
              DROP FOREIGN KEY remote_ibfk_1;
            ALTER TABLE remote
              ADD CONSTRAINT remote_ibfk_1 FOREIGN KEY (record) REFERENCES records (id) ON DELETE CASCADE;
            ALTER TABLE records
              ADD CONSTRAINT records_ibfk_1 FOREIGN KEY (domain_id) REFERENCES domains (id) ON DELETE CASCADE;
            UPDATE options SET value=2 WHERE name='schema_version';
        ";
        $sql["pgsql"] = "UPDATE options SET value=2 WHERE name='schema_version';";
        $queries = explode(";", $sql[$dbType]);
        $db->beginTransaction();
        foreach ($queries as $query) {
            if (preg_replace('/\s+/', '', $query) != '') {
                $db->exec($query);
            }
        }
        $db->commit();
    }
    if($currentVersion < 3) {
        $sql["mysql"] = "
            CREATE TABLE IF NOT EXISTS domainmetadata (
                id INT AUTO_INCREMENT,
                domain_id INT NOT NULL,
                kind VARCHAR(32),
                content TEXT,
                PRIMARY KEY (id)
            ) Engine=InnoDB;
            ALTER TABLE records ADD disabled TINYINT(1) DEFAULT 0;
            ALTER TABLE records ADD auth TINYINT(1) DEFAULT 1;
            UPDATE options SET value=3 WHERE name='schema_version';
        ";
        $sql["pgsql"] = "UPDATE options SET value=3 WHERE name='schema_version';";
        $queries = explode(";", $sql[$dbType]);
        $db->beginTransaction();
        foreach ($queries as $query) {
            if (preg_replace('/\s+/', '', $query) != '') {
                $db->exec($query);
            }
        }
        $db->commit();
    }
    if($currentVersion < 4) {
        $sql["mysql"] = "
            ALTER TABLE permissions DROP FOREIGN KEY permissions_ibfk_2;
            RENAME TABLE user TO users;
            ALTER TABLE permissions CHANGE user userid INT(11);
            ALTER TABLE permissions
              ADD CONSTRAINT permissions_ibfk_2 FOREIGN KEY (userid) REFERENCES users (id) ON DELETE CASCADE;
            ALTER TABLE users ADD CONSTRAINT UNIQUE KEY user_name_index (name);
            UPDATE options SET value=4 WHERE name='schema_version';
        ";
        $sql["pgsql"] = "UPDATE options SET value=4 WHERE name='schema_version';";
        $queries = explode(";", $sql[$dbType]);
        $db->beginTransaction();
        foreach ($queries as $query) {
            if (preg_replace('/\s+/', '', $query) != '') {
                $db->exec($query);
            }
        }
        $db->commit();
    }
    $retval['status'] = "success";
}
if(isset($retval)) {
    echo json_encode($retval);
} else {
    echo "{}";
}

redpajama_set_name: RedPajamaGithub


text:
<?php

	// Load Elgg engine
		require_once(dirname(dirname(dirname(__FILE__))) . "/engine/start.php");

	// If we're not logged in, forward to the front page
		if (!isloggedin()) forward();

	// Get the logged in user
		$page_owner = $_SESSION['user'];
		set_page_owner($page_owner->guid);

	// Get offset
		$offset = get_input('offset',0);

	// Set limit
		$limit = 10;

    // Display all the messages a user owns, these will make up the sentbox
		$messages = get_entities_from_metadata('fromId',$_SESSION['user']->guid,'object','messages', $page_owner->guid, $limit, $offset);
		//$page_owner->getObjects('messages');

    // Set the page title
	    $area2 = elgg_view_title(elgg_echo("messages:sentmessages"));

	// Set content
		// $area2 .= elgg_view("messages/view",array('entity' => $messages, 'page_view' => "sent", 'limit' => $limit, 'offset' => $offset));
		$area2 .= elgg_view("messages/forms/view",array('entity' => $messages, 'page_view' => "sent", 'limit' => $limit, 'offset' => $offset));

	// Format
		$body = elgg_view_layout("two_column_left_sidebar", '', $area2);

	// Draw page
		page_draw(sprintf(elgg_echo('messages:sentMessages'),$page_owner->name),$body);

?>


text:
from neutron_lib import constants
from neutron_lib.plugins import constants as plugin_constants
from neutron_lib.plugins import directory
from oslo_config import cfg
from oslo_db import exception as db_exc
from oslo_log import log as logging
import oslo_messaging

from neutron.agent.common import utils as agent_utils
from neutron.common import constants as l_consts
from neutron.common import utils as n_utils
from neutron.conf.db import l3_agentschedulers_db
from neutron.db import agentschedulers_db
from neutron.db.models import agent as agent_model
from neutron.db.models import l3agent as rb_model
from neutron.extensions import l3agentscheduler
from neutron.extensions import router_availability_zone as router_az
from neutron.objects import agent as ag_obj
from neutron.objects import base as base_obj
from neutron.objects import l3agent as rb_obj
from neutron.objects import router as l3_objs

LOG = logging.getLogger(__name__)

l3_agentschedulers_db.register_db_l3agentschedulers_opts()

class L3AgentSchedulerDbMixin(l3agentscheduler.L3AgentSchedulerPluginBase,
                              agentschedulers_db.AgentSchedulerDbMixin):
    """Mixin class to add l3 agent scheduler extension to plugins
    using the l3 agent for routing.
    """

    router_scheduler = None

    def add_periodic_l3_agent_status_check(self):
        if not cfg.CONF.allow_automatic_l3agent_failover:
            LOG.info("Skipping period L3 agent status check because "
                     "automatic router rescheduling is disabled.")
            return

        self.add_agent_status_check_worker(
            self.reschedule_routers_from_down_agents)

    def reschedule_routers_from_down_agents(self):
        """Reschedule routers from down l3 agents if admin state is up."""
        self.reschedule_resources_from_down_agents(
                agent_type='L3',
                get_down_bindings=self.get_down_router_bindings,
                agent_id_attr='l3_agent_id',
                resource_id_attr='router_id',
                resource_name='router',
                reschedule_resource=self.reschedule_router,
                rescheduling_failed=l3agentscheduler.RouterReschedulingFailed)

    def get_down_router_bindings(self, context, agent_dead_limit):
        cutoff = self.get_cutoff_time(agent_dead_limit)
        return rb_obj.RouterL3AgentBinding.get_down_router_bindings(
            context, cutoff)

    def _get_agent_mode(self, agent_db):
        agent_conf = self.get_configuration_dict(agent_db)
        return agent_conf.get(constants.L3_AGENT_MODE,
                              constants.L3_AGENT_MODE_LEGACY)

    def validate_agent_router_combination(self, context, agent, router):
        """Validate if the router can be correctly assigned to the agent.

        :raises: RouterL3AgentMismatch if attempting to assign DVR router
          to legacy agent.
        :raises: InvalidL3Agent if attempting to assign router to an
          unsuitable agent (disabled, type != L3, incompatible configuration)
        :raises: DVRL3CannotAssignToDvrAgent if attempting to assign a
          router to an agent in 'dvr' mode.
        """
        if agent['agent_type'] != constants.AGENT_TYPE_L3:
            raise l3agentscheduler.InvalidL3Agent(id=agent['id'])

        agent_mode = self._get_agent_mode(agent)

        if agent_mode in [constants.L3_AGENT_MODE_DVR,
                          l_consts.L3_AGENT_MODE_DVR_NO_EXTERNAL]:
            raise l3agentscheduler.DVRL3CannotAssignToDvrAgent()

        if (agent_mode == constants.L3_AGENT_MODE_LEGACY and
            router.get('distributed')):
            raise l3agentscheduler.RouterL3AgentMismatch(
                router_id=router['id'], agent_id=agent['id'])

        is_suitable_agent = (
            agentschedulers_db.services_available(agent['admin_state_up']) and
            self.get_l3_agent_candidates(context, router,
                                         [agent],
                                         ignore_admin_state=True))
        if not is_suitable_agent:
            raise l3agentscheduler.InvalidL3Agent(id=agent['id'])

    def check_agent_router_scheduling_needed(self, context, agent, router):
        """Check if the router scheduling is needed.

        :raises: RouterHostedByL3Agent if router is already assigned
          to a different agent.
        :returns: True if scheduling is needed, otherwise False
        """
        router_id = router['id']
        agent_id = agent['id']
        bindings = rb_obj.RouterL3AgentBinding.get_objects(context,
                          router_id=router_id)
        if not bindings:
            return True
        for binding in bindings:
            if binding.l3_agent_id == agent_id:
                # router already bound to the agent we need
                return False
        if router.get('ha'):
            return True
        # legacy router case: router is already bound to some agent
        raise l3agentscheduler.RouterHostedByL3Agent(
            router_id=router_id,
            agent_id=bindings[0].l3_agent_id)

    def create_router_to_agent_binding(self, context, agent, router):
        """Create router to agent binding."""
        router_id = router['id']
        agent_id = agent['id']
        if self.router_scheduler:
            plugin = directory.get_plugin(plugin_constants.L3)
            try:
                if router.get('ha'):
                    self.router_scheduler.create_ha_port_and_bind(
                        plugin, context, router['id'],
                        router['tenant_id'], agent,
                        is_manual_scheduling=True)
                else:
                    self.router_scheduler.bind_router(
                        plugin, context, router_id, agent.id)
            except db_exc.DBError:
                raise l3agentscheduler.RouterSchedulingFailed(
                    router_id=router_id, agent_id=agent_id)

    def add_router_to_l3_agent(self, context, agent_id, router_id):
        """Add a l3 agent to host a router."""
        if not self.router_supports_scheduling(context, router_id):
            raise l3agentscheduler.RouterDoesntSupportScheduling(
                router_id=router_id)
        with context.session.begin(subtransactions=True):
            router = self.get_router(context, router_id)
            agent = self._get_agent(context, agent_id)
            self.validate_agent_router_combination(context, agent, router)
            if not self.check_agent_router_scheduling_needed(
                    context, agent, router):
                return
        self.create_router_to_agent_binding(context, agent, router)

        l3_notifier = self.agent_notifiers.get(constants.AGENT_TYPE_L3)
        if l3_notifier:
            l3_notifier.router_added_to_agent(
                context, [router_id], agent.host)

    def remove_router_from_l3_agent(self, context, agent_id, router_id):
        """Remove the router from l3 agent.

        After removal, the router will be non-hosted until there is update
        which leads to re-schedule or be added to another agent manually.
        """
        agent = self._get_agent(context, agent_id)
        agent_mode = self._get_agent_mode(agent)
        if agent_mode in [constants.L3_AGENT_MODE_DVR,
                          l_consts.L3_AGENT_MODE_DVR_NO_EXTERNAL]:
            raise l3agentscheduler.DVRL3CannotRemoveFromDvrAgent()

        self._unbind_router(context, router_id, agent_id)
        router = self.get_router(context, router_id)
        plugin = directory.get_plugin(plugin_constants.L3)
        if router.get('ha'):
            plugin.delete_ha_interfaces_on_host(context, router_id, agent.host)
        # NOTE(Swami): Need to verify if there are DVR serviceable
        # ports owned by this agent. If owned by this agent, then
        # the routers should be retained. This flag will be used
        # to check if there are valid routers in this agent.
        retain_router = False
        if router.get('distributed'):
            subnet_ids = plugin.get_subnet_ids_on_router(context, router_id)
            if subnet_ids and agent.host:
                retain_router = plugin._check_dvr_serviceable_ports_on_host(
                    context, agent.host, subnet_ids)
        l3_notifier = self.agent_notifiers.get(constants.AGENT_TYPE_L3)
        if retain_router and l3_notifier:
            l3_notifier.routers_updated_on_host(
                context, [router_id], agent.host)
        elif l3_notifier:
            l3_notifier.router_removed_from_agent(
                context, router_id, agent.host)

    def _unbind_router(self, context, router_id, agent_id):
        rb_obj.RouterL3AgentBinding.delete_objects(
                context, router_id=router_id, l3_agent_id=agent_id)

    def _unschedule_router(self, context, router_id, agents_ids):
        with context.session.begin(subtransactions=True):
            for agent_id in agents_ids:
                self._unbind_router(context, router_id, agent_id)

    def reschedule_router(self, context, router_id, candidates=None):
        """Reschedule router to (a) new l3 agent(s)

        Remove the router from the agent(s) currently hosting it and
        schedule it again
        """
        cur_agents = self.list_l3_agents_hosting_router(
            context, router_id)['agents']
        with context.session.begin(subtransactions=True):
            cur_agents_ids = [agent['id'] for agent in cur_agents]
            self._unschedule_router(context, router_id, cur_agents_ids)

            self.schedule_router(context, router_id, candidates=candidates)
            new_agents = self.list_l3_agents_hosting_router(
                context, router_id)['agents']
            if not new_agents:
                raise l3agentscheduler.RouterReschedulingFailed(
                    router_id=router_id)

        self._notify_agents_router_rescheduled(context, router_id,
                                               cur_agents, new_agents)

    def _notify_agents_router_rescheduled(self, context, router_id,
                                          old_agents, new_agents):
        l3_notifier = self.agent_notifiers.get(constants.AGENT_TYPE_L3)
        if not l3_notifier:
            return

        old_hosts = [agent['host'] for agent in old_agents]
        new_hosts = [agent['host'] for agent in new_agents]
        for host in set(old_hosts) - set(new_hosts):
            l3_notifier.router_removed_from_agent(
                context, router_id, host)

        for agent in new_agents:
            try:
                l3_notifier.router_added_to_agent(
                    context, [router_id], agent['host'])
            except oslo_messaging.MessagingException:
                self._unbind_router(context, router_id, agent['id'])
                raise l3agentscheduler.RouterReschedulingFailed(
                    router_id=router_id)

    def list_routers_on_l3_agent(self, context, agent_id):
        binding_objs = rb_obj.RouterL3AgentBinding.get_objects(
                context, l3_agent_id=agent_id)

        router_ids = [item.router_id for item in binding_objs]
        if router_ids:
            return {'routers':
                    self.get_routers(context, filters={'id': router_ids})}
        else:
            # Exception will be thrown if the requested agent does not exist.
            self._get_agent(context, agent_id)
            return {'routers': []}

    def _get_active_l3_agent_routers_sync_data(self, context, host, agent,
                                               router_ids):
        if n_utils.is_extension_supported(self,
                                          constants.L3_HA_MODE_EXT_ALIAS):
            return self.get_ha_sync_data_for_host(context, host, agent,
                                                  router_ids=router_ids,
                                                  active=True)

        return self.get_sync_data(context, router_ids=router_ids, active=True)

    def list_router_ids_on_host(self, context, host, router_ids=None):
        agent = self._get_agent_by_type_and_host(
            context, constants.AGENT_TYPE_L3, host)
        if not agentschedulers_db.services_available(agent.admin_state_up):
            return []
        return self._get_router_ids_for_agent(context, agent, router_ids)

    def _get_router_ids_for_agent(self, context, agent, router_ids):
        """Get IDs of routers that the agent should host

        Overridden for DVR to handle agents in 'dvr' mode which have
        no explicit bindings with routers
        """
        filters = {'l3_agent_id': agent.id}
        if router_ids:
            filters['router_id'] = router_ids
        bindings = rb_obj.RouterL3AgentBinding.get_objects(context, **filters)
        return [item.router_id for item in bindings]

    def list_active_sync_routers_on_active_l3_agent(
            self, context, host, router_ids):
        agent = self._get_agent_by_type_and_host(
            context, constants.AGENT_TYPE_L3, host)
        if not agentschedulers_db.services_available(agent.admin_state_up):
            LOG.info("Agent has its services disabled. Returning "
                     "no active routers. Agent: %s", agent)
            return []
        scheduled_router_ids = self._get_router_ids_for_agent(
            context, agent, router_ids)
        diff = set(router_ids or []) - set(scheduled_router_ids or [])
        if diff:
            LOG.debug("Agent requested router IDs not scheduled to it. "
                      "Scheduled: %(sched)s. Unscheduled: %(diff)s. "
                      "Agent: %(agent)s.",
                      {'sched': scheduled_router_ids, 'diff': diff,
                       'agent': agent})
        if scheduled_router_ids:
            return self._get_active_l3_agent_routers_sync_data(
                context, host, agent, scheduled_router_ids)
        return []

    def get_l3_agents_hosting_routers(self, context, router_ids,
                                      admin_state_up=None,
                                      active=None):
        if not router_ids:
            return []
        record_objs = rb_obj.RouterL3AgentBinding.get_objects(
                context, router_id=router_ids)
        if admin_state_up is not None:
            l3_agents = ag_obj.Agent.get_objects(context,
                     id=[obj.l3_agent_id for obj in record_objs],
                     admin_state_up=admin_state_up)
        else:
            l3_agents = [
                ag_obj.Agent.get_object(context, id=obj.l3_agent_id)
                for obj in record_objs
            ]
        if active is not None:
            l3_agents = [l3_agent for l3_agent in
                         l3_agents if not
                         agent_utils.is_agent_down(
                             l3_agent['heartbeat_timestamp'])]
        return l3_agents

    def _get_l3_agents_hosting_routers(self, context, router_ids):
        if not router_ids:
            return []
        return (
            rb_obj.RouterL3AgentBinding.get_l3_agents_by_router_ids(
                context, router_ids))

    def list_l3_agents_hosting_router(self, context, router_id):
        with context.session.begin(subtransactions=True):
            agents = self._get_l3_agents_hosting_routers(
                context, [router_id])
        return {'agents': [self._make_agent_dict(agent)
                           for agent in agents]}

    def get_routers_l3_agents_count(self, context):
        """Return a map between routers and agent counts for all routers."""
        # TODO(sshank): This portion needs Router OVO integration when it is
        # merged.
        l3_model_list = l3_objs.RouterExtraAttributes.get_router_agents_count(
            context)
        return [(self._make_router_dict(router_model),
                 agent_count if agent_count else 0)
                for router_model, agent_count in l3_model_list]

    def get_l3_agents(self, context, active=None, filters=None):
        agent_filters = {'agent_type': constants.AGENT_TYPE_L3}
        if active is not None:
            agent_filters['admin_state_up'] = active
        config_filters = []
        if filters:
            for key, value in filters.items():
                column = getattr(agent_model.Agent, key, None)
                if column:
                    if not value:
                        return []

            agent_modes = filters.pop('agent_modes', [])
            if agent_modes:
                config_filters = set('\"agent_mode\": \"%s\"' % agent_mode
                                     for agent_mode in agent_modes)
            agent_filters.update(filters)
        agent_objs = []
        if config_filters:
            for conf_filter in config_filters:
                agent_objs.extend(ag_obj.Agent.get_objects_by_agent_mode(
                    context, conf_filter, **agent_filters))
        else:
            agent_objs = ag_obj.Agent.get_objects(context, **agent_filters)
        return [l3_agent
                for l3_agent in agent_objs
                if agentschedulers_db.AgentSchedulerDbMixin.is_eligible_agent(
                    active, l3_agent)]

    def get_l3_agent_candidates(self, context, sync_router, l3_agents,
                                ignore_admin_state=False):
        """Get the valid l3 agents for the router from a list of l3_agents.

        It will not return agents in 'dvr' mode or in 'dvr_no_external' mode
        for a dvr router as dvr routers are not explicitly scheduled to l3
        agents on compute nodes
        """
        candidates = []
        is_router_distributed = sync_router.get('distributed', False)
        for l3_agent in l3_agents:
            if not ignore_admin_state and not l3_agent.admin_state_up:
                # ignore_admin_state True comes from manual scheduling
                # where admin_state_up judgement is already done.
                continue

            agent_conf = self.get_configuration_dict(l3_agent)
            agent_mode = agent_conf.get(constants.L3_AGENT_MODE,
                                        constants.L3_AGENT_MODE_LEGACY)
            if (agent_mode == constants.L3_AGENT_MODE_DVR or
                agent_mode == l_consts.L3_AGENT_MODE_DVR_NO_EXTERNAL or
                    (agent_mode == constants.L3_AGENT_MODE_LEGACY and
                     is_router_distributed)):
                continue

            router_id = agent_conf.get('router_id', None)
            if router_id and router_id != sync_router['id']:
                continue

            handle_internal_only_routers = agent_conf.get(
                'handle_internal_only_routers', True)
            gateway_external_network_id = agent_conf.get(
                'gateway_external_network_id', None)

            ex_net_id = (sync_router['external_gateway_info'] or {}).get(
                'network_id')
            if ((not ex_net_id and not handle_internal_only_routers) or
                (ex_net_id and gateway_external_network_id and
                 ex_net_id != gateway_external_network_id)):
                continue

            candidates.append(l3_agent)
        return candidates

    def auto_schedule_routers(self, context, host, router_ids=None):
        if self.router_scheduler:
            self.router_scheduler.auto_schedule_routers(
                self, context, host, router_ids)

    def schedule_router(self, context, router, candidates=None):
        if self.router_scheduler:
            return self.router_scheduler.schedule(
                self, context, router, candidates=candidates)

    def schedule_routers(self, context, routers):
        """Schedule the routers to l3 agents."""
        for router in routers:
            self.schedule_router(context, router, candidates=None)

    def get_l3_agent_with_min_routers(self, context, agent_ids):
        if not agent_ids:
            return None
        agents = ag_obj.Agent.get_l3_agent_with_min_routers(
                context, agent_ids)
        return agents

    def get_hosts_to_notify(self, context, router_id):
        """Returns all hosts to send notification about router update"""
        state = agentschedulers_db.get_admin_state_up_filter()
        agents = self.get_l3_agents_hosting_routers(
            context, [router_id], admin_state_up=state, active=True)
        return [a.host for a in agents]

    def get_vacant_binding_index(self, context, router_id,
                                 is_manual_scheduling=False):
        """Return a vacant binding_index to use and whether or not it exists.

        Each RouterL3AgentBinding has a binding_index which is unique per
        router_id, and when creating a single binding we require to find a
        'vacant' binding_index which isn't yet used - for example if we have
        bindings with indices 1 and 3, then clearly binding_index == 2 is free.

        :returns: binding_index.
        """
        num_agents = self.get_number_of_agents_for_scheduling(context)

        pager = base_obj.Pager(sorts=[('binding_index', True)])
        bindings = rb_obj.RouterL3AgentBinding.get_objects(
                context, _pager=pager, router_id=router_id)
        binding_indices = [b.binding_index for b in bindings]
        all_indicies = set(range(rb_model.LOWEST_BINDING_INDEX,
                                 num_agents + 1))
        open_slots = sorted(list(all_indicies - set(binding_indices)))

        if open_slots:
            return open_slots[0]

        # Last chance: if this is a manual scheduling, we're gonna allow
        # creation of a binding_index even if it will exceed
        # max_l3_agents_per_router.
        if is_manual_scheduling:
            return max(all_indicies) + 1

        return -1

class AZL3AgentSchedulerDbMixin(L3AgentSchedulerDbMixin,
                                router_az.RouterAvailabilityZonePluginBase):
    """Mixin class to add availability_zone supported l3 agent scheduler."""

    def get_router_availability_zones(self, router):
        return list({agent.availability_zone for agent in router.l3_agents})


text:
package net.dries007.tfcnei;

import codechicken.nei.api.API;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiUsageRecipe;
import net.dries007.tfcnei.gui.NEIGuiHandler;
import net.dries007.tfcnei.recipeHandlers.*;
import net.minecraftforge.common.config.Configuration;

import static net.minecraftforge.common.config.Configuration.CATEGORY_GENERAL;

/**
 * @author Dries007
 */
public class ClientProxy extends CommonProxy
{
    boolean anvil, quern, kiln, loom, knapping, barrel, alloy, heat;

    private final AnvilRecipeHandler anvilRecipeHandler = new AnvilRecipeHandler();
    private final QuernRecipeHandler quernRecipeHandler = new QuernRecipeHandler();
    private final KilnRecipeHandler kilnRecipeHandler = new KilnRecipeHandler();
    private final LoomRecipeHandler loomRecipeHandler = new LoomRecipeHandler();
    private final KnappingRecipeHandler knappingRecipeHandler = new KnappingRecipeHandler();
    private final BarrelRecipeHandler barrelRecipeHandler = new BarrelRecipeHandler();
    private final AlloyRecipeHandler alloyRecipeHandler = new AlloyRecipeHandler();
    private final HeatRecipeHandler heatRecipeHandler = new HeatRecipeHandler();

    @Override
    public void config(Configuration cfg)
    {
        super.config(cfg);

        TerraFirmaCraftNEIplugin.log.info("Updating TerraFirmaCraftNEIplugin modules...");

        anvil = cfg.getBoolean("anvil", CATEGORY_GENERAL, true, "");
        quern = cfg.getBoolean("quern", CATEGORY_GENERAL, true, "");
        kiln = cfg.getBoolean("kiln", CATEGORY_GENERAL, true, "");
        loom = cfg.getBoolean("loom", CATEGORY_GENERAL, true, "");
        knapping = cfg.getBoolean("knapping", CATEGORY_GENERAL, true, "");
        barrel = cfg.getBoolean("barrel", CATEGORY_GENERAL, true, "");
        alloy = cfg.getBoolean("alloy", CATEGORY_GENERAL, true, "");
        heat = cfg.getBoolean("heat", CATEGORY_GENERAL, true, "");

        API.registerNEIGuiHandler(new NEIGuiHandler());

        if (anvil)
        {
            API.registerRecipeHandler(anvilRecipeHandler);
            API.registerUsageHandler(anvilRecipeHandler);
        }
        else
        {
            GuiCraftingRecipe.craftinghandlers.remove(anvilRecipeHandler);
            GuiUsageRecipe.usagehandlers.remove(anvilRecipeHandler);
        }
        if (quern)
        {
            API.registerRecipeHandler(quernRecipeHandler);
            API.registerUsageHandler(quernRecipeHandler);
        }
        else
        {
            GuiCraftingRecipe.craftinghandlers.remove(quernRecipeHandler);
            GuiUsageRecipe.usagehandlers.remove(quernRecipeHandler);
        }
        if (kiln)
        {
            API.registerRecipeHandler(kilnRecipeHandler);
            API.registerUsageHandler(kilnRecipeHandler);
        }
        else
        {
            GuiCraftingRecipe.craftinghandlers.remove(kilnRecipeHandler);
            GuiUsageRecipe.usagehandlers.remove(kilnRecipeHandler);
        }
        if (loom)
        {
            API.registerRecipeHandler(loomRecipeHandler);
            API.registerUsageHandler(loomRecipeHandler);
        }
        else
        {
            GuiCraftingRecipe.craftinghandlers.remove(loomRecipeHandler);
            GuiUsageRecipe.usagehandlers.remove(loomRecipeHandler);
        }
        if (knapping)
        {
            API.registerRecipeHandler(knappingRecipeHandler);
            API.registerUsageHandler(knappingRecipeHandler);
        }
        else
        {
            GuiCraftingRecipe.craftinghandlers.remove(knappingRecipeHandler);
            GuiUsageRecipe.usagehandlers.remove(knappingRecipeHandler);
        }
        if (barrel)
        {
            API.registerRecipeHandler(barrelRecipeHandler);
            API.registerUsageHandler(barrelRecipeHandler);
        }
        else
        {
            GuiCraftingRecipe.craftinghandlers.remove(barrelRecipeHandler);
            GuiUsageRecipe.usagehandlers.remove(barrelRecipeHandler);
        }
        if (alloy)
        {
            API.registerRecipeHandler(alloyRecipeHandler);
            API.registerUsageHandler(alloyRecipeHandler);
        }
        else
        {
            GuiCraftingRecipe.craftinghandlers.remove(alloyRecipeHandler);
            GuiUsageRecipe.usagehandlers.remove(alloyRecipeHandler);
        }
        if (heat)
        {
            API.registerRecipeHandler(heatRecipeHandler);
            API.registerUsageHandler(heatRecipeHandler);
        }
        else
        {
            GuiCraftingRecipe.craftinghandlers.remove(heatRecipeHandler);
            GuiUsageRecipe.usagehandlers.remove(heatRecipeHandler);
        }
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Proctor - by Creligent </title>
<link href="favicon1.ico" rel="icon" type="image/x-icon" />
<link rel="stylesheet" href="css/lib/bootstrap/bootstrap.css" />
<link rel="stylesheet" href="css/lib/font-awesome/font-awesome.min.css">
<link rel="stylesheet" href="css/lib/ionicons/ionicons.min.css">
<link rel="stylesheet" href="css/lib/daterangepicker/daterangepicker-bs3.css" />
<link rel="stylesheet" href="css/lib/tabdrop/tabdrop.css" />
<link rel="stylesheet" href="css/styles.css" id="theme-css" />

<button class="navbar-toggle navbar-toggle-settings" data-target="#top-navbar" data-toggle="collapse" type="button">
Toggle navigation

</button>

<button class="toggle-btn" type="button">

</button>

Home

 Support

 Notifications6

 Nikita Williams rejected an Action Step from you

 You accepted an Action Step from Scott Marshall

View all

 Regina Hanson

App Tour

My Profile

Account Settings

Logout

 Dashboards

Company analytics

Sales board

General

 UI Elements

Typography

Buttons

Tabs & Accordians

Panels

Alerts & Modals

Icons

Components

Calendar

List & Tree

 Forms

Basic

Advanced

Validation

Editors

 Tables

Basic

Responsive

Datatables

 Layouts

Grid system

Full-width

Blank page

Charts & Maps

 Charts

Flot

Morris.js

C3 charts

Others

 Maps

Google Maps

Vector maps

Application Pages

 App Pages

Login

Signup

Recover password

Social login

User profile

Invoice

Settings

App tour

Timeline

Support

 Extra Pages

Notifications

FAQs

404 Error

500 Error

Home

Library

Data

FAQs

Security

Internet

General

How can I get my own domain name?

The Internet Corporation for Assigned Names and Numbers (ICANN) maintains a list of accredited registrars . Any of the companies on this list can register a domain name for you.

How can I block my hosting service's advertisements?

Check the Terms of Service (TOS) agreement for your hosting service. It almost certainly prohibits interfering with the advertisements they add to your web pages. If you use some trick to block their advertisements on your own, then your hosting service may delete your account for violating its TOS.

How do I redirect someone to another page?

The most reliable way is to configure the server to send out a redirection instruction when the old URL is requested. Then the browser will automatically get the new URL. This is the fastest and most efficient way, and is the only way described here that can convince indexing robots to phase out the old URL. For configuration details consult your server admin or documentation (with NCSA or Apache servers, use a Redirect statement in .htaccess).

How do I password protect my web site?

The most reliable way is to configure the server to send out a redirection instruction when the old URL is requested. Then the browser will automatically get the new URL. This is the fastest and most efficient way, and is the only way described here that can convince indexing robots to phase out the old URL. For configuration details consult your server admin or documentation (with NCSA or Apache servers, use a Redirect statement in .htaccess).

How do I redirect someone to another page?

The most reliable way is to configure the server to send out a redirection instruction when the old URL is requested. Then the browser will automatically get the new URL. This is the fastest and most efficient way, and is the only way described here that can convince indexing robots to phase out the old URL. For configuration details consult your server admin or documentation (with NCSA or Apache servers, use a Redirect statement in .htaccess).

How can I disable the browser's right-click options?

These scripts annoy visitors who lose ready access to their browsers' normal context-menu functions (e.g., "Open in new window" or "Bookmark link"). These scripts can also interfere with features like mouse gestures. Nothing (including these scripts) can prevent anyone from copying your source or images. The browser cannot display your document without the source and images, so your web server must send them to the browser. Even without the various "save" functions in today's browsers, someone can retrieve your source or images from the browser's cache, request them from the server with some other tool, or use a screen-capture tool to copy the images. These scripts do nothing when JavaScript is disabled or unavailable, when JavaScript access to right-click events is disabled, on systems without mice, or on systems with single-button mice.

Collapsible Group Item #1

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

Collapsible Group Item #2

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

Collapsible Group Item #3

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

About Us

FAQs

Support

Blog

© Proctor by Creligent

Privacy

Security

Terms of use


text:
"""hotspots visualization."""

from apps.managers.team_mgr.models import Team

def supply(request, page_name):
    """ Handle the request for viz_hotspots widget."""

    _ = request
    _ = page_name

    all_lounges = Team.objects.order_by('name').all()

    return  {
        "all_lounges": all_lounges,
        }


text:
package org.projectodd.wunderboss.web.undertow;

import io.undertow.server.HttpHandler;
import io.undertow.util.AbstractAttachable;

public abstract class AttachableHttpHandler extends AbstractAttachable implements HttpHandler {

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Premise.Data.EntityFramework
{
    /// <summary>
    /// A generic entity framework data repository
    /// </summary>
    public class EntityRepository<K, T> : IRepository<K, T> where T : class, IEntity<K>
    {
        protected DbContext Context { get; set; }

        /// <summary>
        /// Constructs a new repository instance
        /// </summary>
        /// <param name="context">The database context</param>
        public EntityRepository(DbContext context)
        {
            Context = context;
        }

        #region Select

        /// <summary>
        /// Retrieves a given record by its key from the data store
        /// </summary>
        /// <param name="id">The identifier of the record</param>
        /// <returns></returns>
        public virtual T Get(K id)
        {
            return Context.Set<T>().FirstOrDefault(record => record.Id.Equals(id));
        }

        /// <summary>
        /// Retrieves a given record by its key from the data store (async)
        /// </summary>
        /// <param name="id">The identifier of the record</param>
        /// <param name="cancelToken">A cancellation token used to cancel the task</param>
        /// <returns></returns>
        public virtual async Task<T> GetAsync(K id, CancellationToken cancelToken = default(CancellationToken))
        {
            return await Context.Set<T>().FirstOrDefaultAsync(record => record.Id.Equals(id), cancelToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Retrieves all records from the data store
        /// </summary>
        /// <returns></returns>
        public virtual IQueryable<T> GetAll()
        {
            return Context.Set<T>();
        }

        /// <summary>
        /// Retrieves all records from the data store (async)
        /// </summary>
        /// <param name="cancelToken">A cancellation token used to cancel the task</param>
        /// <returns></returns>
        public virtual async Task<IQueryable<T>> GetAllAsync(CancellationToken cancelToken = default(CancellationToken))
        {
            return (await Context.Set<T>().ToListAsync(cancelToken).ConfigureAwait(false)).AsQueryable();
        }

        #endregion

        #region Insert

        /// <summary>
        /// /// Inserts a record into the data store
        /// </summary>
        /// <param name="record">The record to insert</param>
        public virtual void Insert(T record)
        {
            TryGenerateIds(record);

            Context.Set<T>().Add(record);
        }

        /// <summary>
        /// Inserts a record into the data store (async)
        /// </summary>
        /// <param name="record">The record to insert</param>
        /// <param name="cancelToken">A cancellation token used to cancel the task</param>
        /// <returns></returns>
        public virtual async Task InsertAsync(T record, CancellationToken cancelToken = default(CancellationToken))
        {
            TryGenerateIds(record);

            await Task.Run(() => Context.Set<T>().Add(record), cancelToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Inserts many records into the data store
        /// </summary>
        /// <param name="records">The records to insert into the data store</param>
        public virtual void InsertMany(IEnumerable<T> records)
        {
            TryGenerateIds(records);

            Context.Set<T>().AddRange(records);
        }

        /// <summary>
        /// /// Inserts many records into the data store (async)
        /// </summary>
        /// <param name="records">The records to insert into the data store</param>
        /// <param name="cancelToken">A cancellation token used to cancel the task</param>
        /// <returns></returns>
        public virtual async Task InsertManyAsync(IEnumerable<T> records, CancellationToken cancelToken = default(CancellationToken))
        {
            TryGenerateIds(records);

            await Task.Run(() => Context.Set<T>().AddRange(records), cancelToken).ConfigureAwait(false);
        }

        #endregion

        #region Update

        /// <summary>
        /// /// Updates a record in the data store
        /// </summary>
        /// <param name="record">The record to update</param>
        public virtual void Update(T record)
        {

        }

        /// <summary>
        /// /// Updates a record in the data store (async)
        /// </summary>
        /// <param name="record">The record to update</param>
        /// <param name="cancelToken">A cancellation token used to cancel the task</param>
        /// <returns></returns>
        public virtual Task UpdateAsync(T record, CancellationToken cancelToken = default(CancellationToken))
        {
            return Task.FromResult<object>(null);
        }

        /// <summary>
        /// Updates many records in the data store
        /// </summary>
        /// <param name="record">The records to update</param>
        public virtual void UpdateMany(IEnumerable<T> records)
        {

        }

        /// <summary>
        /// Updates many records in the data store
        /// </summary>
        /// <param name="record">The records to update</param>
        /// <param name="cancelToken">A cancellation token used to cancel the task</param>
        /// <returns></returns>
        public virtual Task UpdateManyAsync(IEnumerable<T> records, CancellationToken cancelToken = default(CancellationToken))
        {
            return Task.FromResult<object>(null);
        }

        #endregion

        #region Delete

        /// <summary>
        /// /// Deletes a record in the data store
        /// </summary>
        /// <param name="record">The record to delete</param>
        public virtual void Delete(T record)
        {
            Context.Set<T>().Remove(record);
        }

        /// <summary>
        /// Deletes a record in the data store (async)
        /// </summary>
        /// <param name="record">The record to delete</param>
        /// <param name="cancelToken">The cancellation token used to cancel the task</param>
        /// <returns></returns>
        public virtual async Task DeleteAsync(T record, CancellationToken cancelToken = default(CancellationToken))
        {
            await Task.Run(() => Context.Set<T>().Remove(record), cancelToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Deletes many records in the data store
        /// </summary>
        /// <param name="records">The records to delete</param>
        public virtual void DeleteMany(IEnumerable<T> records)
        {
            Context.Set<T>().RemoveRange(records);
        }

        /// <summary>
        /// Deletes many records in the data store (async)
        /// </summary>
        /// <param name="records">The records to delete</param>
        /// <param name="cancelToken">The cancellation token used to cancel the task</param>
        /// <returns></returns>
        public virtual async Task DeleteManyAsync(IEnumerable<T> records, CancellationToken cancelToken = default(CancellationToken))
        {
            await Task.Run(() => Context.Set<T>().RemoveRange(records), cancelToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Deletes a record by id in the data store
        /// </summary>
        /// <param name="id">The id of the record</param>
        public virtual void Delete(K id)
        {
            var record = Get(id);
            if (record != null)
            {
                Context.Set<T>().Remove(record);
            }
        }

        /// <summary>
        /// Deletes a record by id in the data store (async)
        /// </summary>
        /// <param name="id">The id of the record</param>
        /// <param name="cancelToken">A cancellation token used to cancel the task</param>
        /// <returns></returns>
        public virtual async Task DeleteAsync(K id, CancellationToken cancelToken = default(CancellationToken))
        {
            var record = await GetAsync(id, cancelToken).ConfigureAwait(false);
            if (record != null)
            {
                await Task.Run(() => Context.Set<T>().Remove(record), cancelToken).ConfigureAwait(false);
            }
        }

        /// <summary>
        /// /// Deletes many records by id in the data store
        /// </summary>
        /// <param name="ids">The ids of the records</param>
        public virtual void DeleteMany(IEnumerable<K> ids)
        {
            var records = Context.Set<T>().Where(x => ids.Contains(x.Id));
            if (records != null && records.Any())
            {
                Context.Set<T>().RemoveRange(records);
            }
        }

        /// <summary>
        /// Deletes many records by id in the data store (async)
        /// </summary>
        /// <param name="ids">The ids of the records</param>
        /// <param name="cancelToken">A cancellation token used to cancel the task</param>
        /// <returns></returns>
        public virtual async Task DeleteManyAsync(IEnumerable<K> ids, CancellationToken cancelToken = default(CancellationToken))
        {
            var records = await Context.Set<T>().Where(x => ids.Contains(x.Id)).ToListAsync(cancelToken).ConfigureAwait(false);
            if (records != null && records.Any())
            {
                await Task.Run(() => Context.Set<T>().RemoveRange(records), cancelToken).ConfigureAwait(false);
            }
        }

        #endregion

        #region Transactions

        /// <summary>
        /// Commits pending transactions to the data store
        /// </summary>
        public virtual void Commit()
        {
            Context.SaveChanges();
        }

        /// <summary>
        /// /// Commits pending transactions to the data store (async)
        /// </summary>
        /// <param name="cancelToken">A cancellation token used to cancel the task</param>
        /// <returns></returns>
        public virtual async Task CommitAsync(CancellationToken cancelToken = default(CancellationToken))
        {
            await Context.SaveChangesAsync().ConfigureAwait(false);
        }

        #endregion

        #region Reload

        /// <summary>
        /// /// Reloads a given record from the data store
        /// </summary>
        /// <param name="record"></param>
        public virtual void Reload(T record)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Reloads a given record from the data store (async)
        /// </summary>
        /// <param name="record">The record to reload</param>
        /// <param name="cancelToken">A cancellation token used to cancel the task</param>
        /// <returns></returns>
        public virtual Task ReloadAsync(T record, CancellationToken cancelToken = default(CancellationToken))
        {
            throw new NotImplementedException();
        }

        #endregion

        protected virtual void TryGenerateIds(T record)
        {
            TryGenerateIds(new [] { record });
        }

        protected virtual void TryGenerateIds(IEnumerable<T> records)
        {
            if (typeof(K) == typeof(Guid))
            {
                foreach (var record in records)
                {
                    record.Id = (K)(object)Guid.NewGuid();
                }
            }
        }
    }
}


text:
package org.jclouds.elasticstack.domain;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Map;
import java.util.Set;

import org.jclouds.javax.annotation.Nullable;

import com.google.common.collect.ImmutableSet;

public class DriveInfo extends Drive {
   public static class Builder extends Drive.Builder {

      protected DriveStatus status;
      protected String user;
      protected Set<String> claimed = ImmutableSet.of();
      @Nullable
      protected String encryptionCipher;
      @Nullable
      protected String imaging;
      protected DriveMetrics metrics;

      public Builder status(DriveStatus status) {
         this.status = status;
         return this;
      }

      public Builder user(String user) {
         this.user = user;
         return this;
      }

      public Builder claimed(Iterable<String> claimed) {
         this.claimed = ImmutableSet.copyOf(checkNotNull(claimed, "claimed"));
         return this;
      }

      public Builder imaging(String imaging) {
         this.imaging = imaging;
         return this;
      }

      public Builder metrics(DriveMetrics metrics) {
         this.metrics = metrics;
         return this;
      }

      public Builder encryptionCipher(String encryptionCipher) {
         this.encryptionCipher = encryptionCipher;
         return this;
      }

      /**
       * {@inheritDoc}
       */
      @Override
      public Builder claimType(ClaimType claimType) {
         return Builder.class.cast(super.claimType(claimType));
      }

      /**
       * {@inheritDoc}
       */
      @Override
      public Builder readers(Iterable<String> readers) {
         return Builder.class.cast(super.readers(readers));
      }

      /**
       * {@inheritDoc}
       */
      @Override
      public Builder size(long size) {
         return Builder.class.cast(super.size(size));
      }

      /**
       * {@inheritDoc}
       */
      @Override
      public Builder uuid(String uuid) {
         return Builder.class.cast(super.uuid(uuid));
      }

      /**
       * {@inheritDoc}
       */
      @Override
      public Builder name(String name) {
         return Builder.class.cast(super.name(name));
      }

      /**
       * {@inheritDoc}
       */
      @Override
      public Builder tags(Iterable<String> tags) {
         return Builder.class.cast(super.tags(tags));
      }

      /**
       * {@inheritDoc}
       */
      @Override
      public Builder userMetadata(Map<String, String> userMetadata) {
         return Builder.class.cast(super.userMetadata(userMetadata));
      }

      public static Builder fromDriveInfo(DriveInfo driveInfo) {
         return new Builder().uuid(driveInfo.getUuid()).name(driveInfo.getName()).size(driveInfo.getSize())
               .claimType(driveInfo.getClaimType()).readers(driveInfo.getReaders()).tags(driveInfo.getTags())
               .userMetadata(driveInfo.getUserMetadata()).status(driveInfo.getStatus()).user(driveInfo.getUser())
               .claimed(driveInfo.getClaimed()).encryptionCipher(driveInfo.getEncryptionCipher())
               .imaging(driveInfo.getImaging()).metrics(driveInfo.getMetrics());
      }

      /**
       * {@inheritDoc}
       */
      @Override
      public DriveInfo build() {
         return new DriveInfo(uuid, name, size, claimType, readers, tags, userMetadata, status, user, claimed,
               encryptionCipher, imaging, metrics);
      }

   }

   protected final DriveStatus status;
   protected final String user;
   protected final Set<String> claimed;
   @Nullable
   protected final String encryptionCipher;
   @Nullable
   protected final String imaging;
   protected final DriveMetrics metrics;

   public DriveInfo(String uuid, String name, long size, ClaimType claimType, Iterable<String> readers,
         Iterable<String> tags, Map<String, String> userMetadata, DriveStatus status, String user, Set<String> claimed,
         String encryptionCipher, String imaging, DriveMetrics metrics) {
      super(uuid, name, size, claimType, readers, tags, userMetadata);
      this.status = status;
      this.user = user;
      this.claimed = ImmutableSet.copyOf(checkNotNull(claimed, "claimed"));
      this.encryptionCipher = encryptionCipher;
      this.imaging = imaging;
      this.metrics = checkNotNull(metrics, "metrics");
   }

   /**
    *
    * @return current status of the drive
    */
   public DriveStatus getStatus() {
      return status;
   }

   /**
    *
    * @return owner of the drive
    */
   public String getUser() {
      return user;
   }

   /**
    *
    * @return if drive is in use by a server, values are the server uuids
    */
   public Set<String> getClaimed() {
      return claimed;
   }

   /**
    *
    * @return either 'none' or 'aes-xts-plain' (the default)
    */
   @Nullable
   public String getEncryptionCipher() {
      return encryptionCipher;
   }

   /**
    *
    * @return percentage completed of drive imaging if this is underway, or 'queued' if waiting for
    *         another imaging operation to complete first
    */
   public String getImaging() {
      return imaging;
   }

   /**
    *
    * @return i/o and request metrics for read and write ops
    */
   public DriveMetrics getMetrics() {
      return metrics;
   }

   @Override
   public int hashCode() {
      final int prime = 31;
      int result = super.hashCode();
      result = prime * result + ((claimed == null) ? 0 : claimed.hashCode());
      result = prime * result + ((metrics == null) ? 0 : metrics.hashCode());
      result = prime * result + ((encryptionCipher == null) ? 0 : encryptionCipher.hashCode());
      result = prime * result + ((imaging == null) ? 0 : imaging.hashCode());
      result = prime * result + ((status == null) ? 0 : status.hashCode());
      result = prime * result + ((user == null) ? 0 : user.hashCode());
      return result;
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (!super.equals(obj))
         return false;
      if (getClass() != obj.getClass())
         return false;
      DriveInfo other = (DriveInfo) obj;
      if (claimed == null) {
         if (other.claimed != null)
            return false;
      } else if (!claimed.equals(other.claimed))
         return false;
      if (metrics == null) {
         if (other.metrics != null)
            return false;
      } else if (!metrics.equals(other.metrics))
         return false;
      if (encryptionCipher == null) {
         if (other.encryptionCipher != null)
            return false;
      } else if (!encryptionCipher.equals(other.encryptionCipher))
         return false;
      if (imaging == null) {
         if (other.imaging != null)
            return false;
      } else if (!imaging.equals(other.imaging))
         return false;
      if (status != other.status)
         return false;
      if (user == null) {
         if (other.user != null)
            return false;
      } else if (!user.equals(other.user))
         return false;
      return true;
   }

   @Override
   public String toString() {
      return "[size=" + size + ", claimType=" + claimType + ", readers=" + readers + ", uuid=" + uuid + ", name="
            + name + ", tags=" + tags + ", userMetadata=" + userMetadata + ", status=" + status + ", user=" + user
            + ", claimed=" + claimed + ", encryptionCipher=" + encryptionCipher + ", imaging=" + imaging
            + ", metrics=" + metrics + "]";
   }

}


text:
package minefantasy.mf2.entity;

import static net.minecraftforge.common.util.ForgeDirection.UP;
import minefantasy.mf2.config.ConfigMobs;
import minefantasy.mf2.entity.mob.EntityDragon;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.projectile.EntityFireball;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSourceIndirect;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;

public class EntityFireBlast extends EntityFireball
{
    private static final float size =0.75F;

    public EntityFireBlast(World world)
    {
        super(world);
        this.setInvisible(true);
        this.setSize(size, size);
    }

    public EntityFireBlast(World world, EntityLivingBase shooter, double xv, double yv, double zv)
    {
        super(world, shooter, xv, yv, zv);
        this.setInvisible(true);
        this.setSize(size, size);
    }

    public EntityFireBlast(World world, double x, double y, double z, double xv, double yv, double zv)
    {
        super(world, x, y, z, xv, yv, zv);
        this.setInvisible(true);
        this.setSize(size, size);
    }

    @Override
    public void onUpdate()
    {
    	super.onUpdate();
    	if(this.ticksExisted >= getLifeSpan())
    	{
    		setDead();
    	}
    	if(ticksExisted % 5 == 0)
    	{
	    	int lifeScale = (int) Math.floor((float)ticksExisted / 5F);
	    	float newSize = size + (size/4*lifeScale);
	    	this.setSize(newSize, newSize);
    	}
    	if(ticksExisted % 10 == 0)
    	{
    		for(int x = -1; x <= 1; x++)
    		{
    			for(int y = -1; y <= 1; y++)
        		{
    				for(int z = -1; z <= 1; z++)
    	    		{
    	    			int i = (int)posX + x;
    	    			int j = (int)posY + y;
    	    			int k = (int)posZ + z;

    	    			if (!worldObj.isRemote && canBlockCatchFire(i, j-1, k) && worldObj.isAirBlock(i, j, k) && rand.nextFloat() < getPyro())
    	                {
    	                    this.worldObj.setBlock(i, j, k, Blocks.fire);
    	                }
    	    		}
        		}
    		}
    	}
    	AxisAlignedBB bb = this.boundingBox.expand(1D, 1D, 1D);
        if(!worldObj.isRemote)
        this.destroyBlocksInAABB(bb);
    }

    private int getLifeSpan()
    {
    	if(isPreset("BlastFurnace"))
    	{
    		return 15;
    	}
		return 30;
	}

	/**
     * Called when this EntityFireball hits a block or entity.
     */
    protected void onImpact(MovingObjectPosition pos)
    {
        if (!this.worldObj.isRemote)
        {
            if (pos.entityHit != null)
            {
                if (!pos.entityHit.isImmuneToFire())
                {
                	pos.entityHit.setFire(isPreset("Dragon") ? 2 : 4);
                	pos.entityHit.attackEntityFrom(causeFireblastDamage(), getDamage());
                }
            }
            else
            {
                int i = pos.blockX;
                int j = pos.blockY;
                int k = pos.blockZ;

                switch (pos.sideHit)
                {
                    case 0:
                        --j;
                        break;
                    case 1:
                        ++j;
                        break;
                    case 2:
                        --k;
                        break;
                    case 3:
                        ++k;
                        break;
                    case 4:
                        --i;
                        break;
                    case 5:
                        ++i;
                }

                if (!worldObj.isRemote && this.worldObj.isAirBlock(i, j, k) && rand.nextFloat() < getPyro())
                {
                    this.worldObj.setBlock(i, j, k, Blocks.fire);
                }
                boolean tnt = worldObj.getBlock(pos.blockX, pos.blockY, pos.blockZ).getMaterial() == Material.tnt;
                if(isPreset("BlastFurnace") && (rand.nextInt(50) == 0) || tnt)
                {
                	boolean solid = worldObj.isBlockNormalCubeDefault(pos.blockX, pos.blockY, pos.blockZ, false);
                	worldObj.newExplosion(this, posX, posY, posZ, solid ? 1.5F : 0.5F, true, true);
                }
            }

            this.setDead();
        }
    }

    private float getPyro()
    {

    	if(!ConfigMobs.dragonGriefFire && shootingEntity != null && shootingEntity instanceof EntityDragon)
    	{
    		return 0F;
    	}

    	if(getEntityData().hasKey("Pyro"))
		{
			return getEntityData().getFloat("Pyro");
		}

    	return 0.75F;
    }
    private float getDamage()
    {
    	if(getEntityData().hasKey("Damage"))
		{
			return getEntityData().getFloat("Damage");
		}

    	if(isPreset("BlastFurnace"))
    	{
    		return 8F;
    	}
		return 2.0F;
	}

	/**
     * Returns true if other Entities should be prevented from moving through this Entity.
     */
    public boolean canBeCollidedWith()
    {
        return false;
    }

    /**
     * Called when the entity is attacked.
     */
    public boolean attackEntityFrom(DamageSource src, float power)
    {
        return false;
    }

    @Override
    public boolean isInvisible()
    {
        return true;
    }

    public void modifySpeed(float mod)
    {
    	this.accelerationX *= mod;
    	this.accelerationY *= mod;
    	this.accelerationZ *= mod;
    }

    public boolean isPreset(String s)
    {
    	if(getEntityData().hasKey("Preset"))
    	{
    		return getEntityData().getString("Preset").equalsIgnoreCase(s);
    	}
    	return false;
    }
    public boolean canBlockCatchFire(int x, int y, int z)
    {
        return canCatchFire(x, y, z, UP);
    }
    public boolean canCatchFire(int x, int y, int z, ForgeDirection face)
    {
        return worldObj.getBlock(x, y, z).isFlammable(worldObj, x, y, z, face);
    }

	public EntityFireBlast preset(String string)
	{
		getEntityData().setBoolean(string, true);
		return this;
	}
	public EntityFireBlast setDamage(float dam)
	{
		getEntityData().setFloat("Damage", dam);
		return this;
	}
	public EntityFireBlast setPyro(float dam)
	{
		getEntityData().setFloat("Pyro", dam);
		return this;
	}

	private boolean destroyBlocksInAABB(AxisAlignedBB box)
    {
        int var2 = MathHelper.floor_double(box.minX);
        int var3 = MathHelper.floor_double(box.minY);
        int var4 = MathHelper.floor_double(box.minZ);
        int var5 = MathHelper.floor_double(box.maxX);
        int var6 = MathHelper.floor_double(box.maxY);
        int var7 = MathHelper.floor_double(box.maxZ);
        boolean var8 = false;
        boolean var9 = false;

        for (int var10 = var2; var10 <= var5; ++var10)
        {
            for (int var11 = var3; var11 <= var6; ++var11)
            {
                for (int var12 = var4; var12 <= var7; ++var12)
                {
                    Material var13 = this.worldObj.getBlock(var10, var11, var12).getMaterial();

                    if (var13 != null)
                    {
                        if (var13 == Material.glass)
                        {
                            var9 = true;
                            this.worldObj.setBlockToAir(var10, var11, var12);
                        }
                        else if (var13 == Material.tnt)
                        {
                            var9 = true;
                            this.worldObj.setBlockToAir(var10, var11, var12);
                            this.worldObj.createExplosion(this, var10, var11, var12, 4.0F, true);
                        }
                        else
                        {
                            var8 = true;
                        }
                    }
                }
            }
        }

        if (var9)
        {
            double var16 = box.minX + (box.maxX - box.minX) * (double)this.rand.nextFloat();
            double var17 = box.minY + (box.maxY - box.minY) * (double)this.rand.nextFloat();
            double var14 = box.minZ + (box.maxZ - box.minZ) * (double)this.rand.nextFloat();
            this.worldObj.spawnParticle("largeexplode", var16, var17, var14, 0.0D, 0.0D, 0.0D);
            for(int a = 0 ; a < 1+rand.nextInt(4); a ++)
                this.worldObj.playSoundAtEntity(this, "dig.glass", 1F, 1F);
        }

        return var8;
    }

	public static DamageSource blastDamage = (new DamageSource("blastfurn")).setFireDamage();
	public static DamageSource basicDamage = (new DamageSource("fireblastBase")).setFireDamage();
	public DamageSource causeFireblastDamage()
    {
		if(isPreset("BlastFurnace"))
    	{
			return blastDamage;
    	}
        return shootingEntity == null ? basicDamage : (new EntityDamageSourceIndirect("fireblast", this, shootingEntity)).setFireDamage().setProjectile();
    }
}


text:
<!DOCTYPE HTML>

<{include file='mobile/default/lib/meta.html'}>
<meta name="keywords" content="绑定本站账号" />
<meta name="description" content="绑定本站账号" />
<title>绑定本站账号</title>
<link rel="stylesheet" type="text/css" href="<{$common.theme}>/css/general.css" />
<link rel="stylesheet" type="text/css" href="<{$common.theme}>/iconfont/iconfont.css">
<link rel="stylesheet" type="text/css" href="<{$common.theme}>/css/login.css" />

<a href="<{url c='mobile/user' a='login'}>">

完善您的账号信息

完善账号信息绑定已有账号

        <form>

<input class="field" type="text" name="username" id="username" placeholder="设置用户名" />

<input class="field" type="email" name="email" id="email" placeholder="设置邮箱" />

<input class="field" type="password" name="password" placeholder="设置登录密码" />

<input class="field" type="password" name="repassword" placeholder="确认登录密码" />

        <{if !empty($GLOBALS.cfg.captcha_user_register)}>

          <img onclick="resetCaptcha(this)" src="<{url c='api/captcha' a='image'}>" />
          <input class="field" name="captcha" type="text" placeholder="请输入图形验证码" />

        <{/if}>

确定并提交

        </form>

        <form>

<input class="field variseclear" type="text" name="username" placeholder="请输入用户名" required />

<input class="field variseclear" type="password" name="password" placeholder="请输入密码" required />

        <{if !empty($login_captcha)}>

          <img onclick="resetCaptcha(this)" src="<{url c='api/captcha' a='image'}>" />
          <input class="field" name="captcha" type="text" placeholder="请输入图形验证码" />

        <{/if}>

登录并绑定

        </form>

<{include file='mobile/default/lib/footer.html'}>


text:
require_relative 'udf_harness'

class Runner
  ARGS_HELP = """
    Usage:
      ruby #{__FILE__} <action> [udf_name]

    Actions:
      load    Loads UDFs into your database
      drop    Removes UDFs from your database
      test    Runs UDF unit tests on your database
      print   Pretty-print SQL for making the UDFs

    Examples:
      ruby #{__FILE__} load
      ruby #{__FILE__} drop harmonic_mean
      ruby #{__FILE__} test json_array_first
      ruby #{__FILE__} print
  """

  def self.run(args = [])
    if args.nil? or args.empty?
      puts ARGS_HELP
      exit
    end

    u = UdfHarness.new(args[1])
    case args.first.to_sym
      when :load then u.create_udfs
      when :drop then u.drop_udfs
      when :test then u.test_udfs
      when :print then u.print_udfs
      else
        puts "Args not understood, showing help instead."
        puts ARGS_HELP
        exit
    end
  end
end

Runner.run(ARGV) if __FILE__ == $PROGRAM_NAME


text:
;------------------------------------------------------------------------------
;
; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution.  The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php.
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
;   ZeroMem.Asm
;
; Abstract:
;
;   ZeroMem function
;
; Notes:
;
;------------------------------------------------------------------------------

    .code

;------------------------------------------------------------------------------
;  VOID *
;  InternalMemZeroMem (
;    IN VOID   *Buffer,
;    IN UINTN  Count
;    );
;------------------------------------------------------------------------------
InternalMemZeroMem  PROC    USES    rdi
    push    rcx
    xor     rax, rax
    mov     rdi, rcx
    mov     rcx, rdx
    shr     rcx, 3
    and     rdx, 7
    rep     stosq
    mov     ecx, edx
    rep     stosb
    pop     rax
    ret
InternalMemZeroMem  ENDP

    END


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Wallrothiella melanostigmoides Feltgen, 1903

### Remarks
null


text:
Interactive visual chromosome representation for [Angular.js](http://angularjs.org/)

##Brief Description
Include the angular-chromosome-vis dependency on your angular module:

```
var app = angular.module("myApp", ["angularChromosomeVis"]);
```

Include the script and stylesheet in your HTML, e.g.:

```html
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/d3/d3.min.js"></script>
<script src="bower_components/jsdas/jsdas.min.js"></script>
<script src="bower_components/underscore/underscore-min.js"></script>
<script src="bower_components/angular-chromosome-vis/angular-chromosome-vis.js"></script>
<link rel="stylesheet" href="bower_components/angular-chromosome-vis.css" />
```

Add the directive to your HTML, e.g.:

```html
<div chromosome chr="1" rel-size="true" axis="true" assembly="37" width='850' height="20" mode="multi"></div>
```

##Documentation and Demos
[pparsons.github.io/angular-chromosome-vis](http://pparsons.github.io/angular-chromosome-vis)

##References
Based on [linjoey/cyto-chromosome](https://github.com/linjoey/cyto-chromosome) and [4ndr01d3/biojs-vis-chromosome](https://github.com/4ndr01d3/biojs-vis-chromosome)


text:
# 分享文件

> 编写:[jdneo](https://github.com/jdneo) - 原文:<http://developer.android.com/training/secure-file-sharing/sharing-file.html>

在上一节课中,我们对应用程序进行了配置,使得它可以使用Content URI来共享文件了,现在你可以响应其他应用程序的文件请求。一种响应这些请求的方法是在服务端应用程序提供一个文件选择接口,它可以由其他应用激活。这种方法可以允许客户端应用程序让用户从服务端应用程序选择一个文件,然后接收这个文件的Content URI。

这节课将会向你展示如何在你的应用中创建一个用来选择文件的[Activity](http://developer.android.com/reference/android/app/Activity.html),来响应这些索取文件的请求。

## 接收文件请求

为了从客户端应用程序接收一个文件索取请求,然后以Content URI的形式进行响应,你的应用程序应该提供一个选择文件的[Activity](http://developer.android.com/reference/android/app/Activity.html)。客户端应用程序通过调用startActivityForResult()来启动这个[Activity](http://developer.android.com/reference/android/app/Activity.html)。该方法包含了一个[Intent](http://developer.android.com/reference/android/content/Intent.html)参数,它具有[ACTION_PICK](http://developer.android.com/reference/android/content/Intent.html#ACTION_PICK)这一Action。当客户端应用程序调用了startActivityForResult(),你的应用可以向客户端应用程序返回一个结果,该结果即用户所选择的文件所对应的Content URI。

学习如何在客户端应用程序实现文件索取请求,可以阅读:[请求分享一个文件](request-file.html)。

## 创建一个选择文件的Activity

为了配置一个选择文件的[Activity](http://developer.android.com/reference/android/app/Activity.html),我们首先需要在Manifest清单文件中定义你的[Activity](http://developer.android.com/reference/android/app/Activity.html),在其Intent过滤器中,匹配[ACTION_PICK](http://developer.android.com/reference/android/content/Intent.html#ACTION_PICK)这一Action,以及[CATEGORY_DEFAULT](http://developer.android.com/reference/android/content/Intent.html#CATEGORY_DEFAULT)和[CATEGORY_OPENABLE](http://developer.android.com/reference/android/content/Intent.html#CATEGORY_OPENABLE)这两种Category。另外,还需要为你的应用程序设置MIME类型过滤器,来表明你的应用程序可以向其他应用程序提供哪种类型的文件。下面的这段代码展示了如何在清单文件中定义新的[Activity](http://developer.android.com/reference/android/app/Activity.html)和Intent过滤器:

```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    ...
        <application>
        ...
            <activity
                android:name=".FileSelectActivity"
                android:label="File Selector" >
                <intent-filter>
                    <action
                        android:name="android.intent.action.PICK"/>
                    <category
                        android:name="android.intent.category.DEFAULT"/>
                    <category
                        android:name="android.intent.category.OPENABLE"/>
                    <data android:mimeType="text/plain"/>
                    <data android:mimeType="image/*"/>
                </intent-filter>
            </activity>
```

### 在代码中定义文件选择Activity

下面,定义一个[Activity](http://developer.android.com/reference/android/app/Activity.html)子类,它用来显示在你内部存储的"files/images/"目录下可以获得的文件,然后允许用户选择期望的文件。下面的代码展示了如何定义这个[Activity](http://developer.android.com/reference/android/app/Activity.html),并令其响应用户的选择:

```java
public class MainActivity extends Activity {
    // The path to the root of this app's internal storage
    private File mPrivateRootDir;
    // The path to the "images" subdirectory
    private File mImagesDir;
    // Array of files in the images subdirectory
    File[] mImageFiles;
    // Array of filenames corresponding to mImageFiles
    String[] mImageFilenames;
    // Initialize the Activity
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // Set up an Intent to send back to apps that request a file
        mResultIntent =
                new Intent("com.example.myapp.ACTION_RETURN_FILE");
        // Get the files/ subdirectory of internal storage
        mPrivateRootDir = getFilesDir();
        // Get the files/images subdirectory;
        mImagesDir = new File(mPrivateRootDir, "images");
        // Get the files in the images subdirectory
        mImageFiles = mImagesDir.listFiles();
        // Set the Activity's result to null to begin with
        setResult(Activity.RESULT_CANCELED, null);
        /*
         * Display the file names in the ListView mFileListView.
         * Back the ListView with the array mImageFilenames, which
         * you can create by iterating through mImageFiles and
         * calling File.getAbsolutePath() for each File
         */
         ...
    }
    ...
}
```

## 响应一个文件选择

一旦用户选择了一个想要共享的文件,你的应用程序必须明确哪个文件被选择了,然后为这个文件生成一个对应的Content URI。如果我们的[Activity](http://developer.android.com/reference/android/app/Activity.html)在[ListView](http://developer.android.com/reference/android/widget/ListView.html)中显示了可获得文件的清单,那么当用户点击了一个文件名时,系统会调用方法onItemClick(),在该方法中你可以获取被选择的文件。

在onItemClick()中,根据被选中文件的文件名获取一个[File](http://developer.android.com/reference/java/io/File.html)对象,然后将它作为参数传递给getUriForFile(),另外还需传入的参数是你在[`<provider>`](http://developer.android.com/guide/topics/manifest/provider-element.html)标签中为[FileProvider](http://developer.android.com/reference/android/support/v4/content/FileProvider.html)所指定的Authority,函数返回的Content URI包含了相应的Authority,一个对应于文件目录的路径标记(如在XML meta-data中定义的),以及包含扩展名的文件名。有关[FileProvider](http://developer.android.com/reference/android/support/v4/content/FileProvider.html)如何基于XML meta-data将目录路径与路径标记进行匹配的知识,可以阅读:[指定可共享目录路径](setup-sharing.html#DefineMetaData)。

下面的例子展示了如何检测选中的文件并且获得它的Content URI:

```java
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // Define a listener that responds to clicks on a file in the ListView
        mFileListView.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
            @Override
            /*
             * When a filename in the ListView is clicked, get its
             * content URI and send it to the requesting app
             */
            public void onItemClick(AdapterView<?> adapterView,
                    View view,
                    int position,
                    long rowId) {
                /*
                 * Get a File for the selected file name.
                 * Assume that the file names are in the
                 * mImageFilename array.
                 */
                File requestFile = new File(mImageFilename[position]);
                /*
                 * Most file-related method calls need to be in
                 * try-catch blocks.
                 */
                // Use the FileProvider to get a content URI
                try {
                    fileUri = FileProvider.getUriForFile(
                            MainActivity.this,
                            "com.example.myapp.fileprovider",
                            requestFile);
                } catch (IllegalArgumentException e) {
                    Log.e("File Selector",
                          "The selected file can't be shared: " +
                          clickedFilename);
                }
                ...
            }
        });
        ...
    }
```

记住,你能生成的那些Content URI所对应的文件,是那些在meta-data文件中包含`<paths>`标签的(即你定义的)目录内的文件,这方面知识在[Specify Sharable Directories](http://developer.android.com/training/secure-file-sharing/setup-sharing.html#DefineMetaData)中已经讨论过。如果你调用getUriForFile()方法所要获取的文件不在你指定的目录中,你会收到一个[IllegalArgumentException](http://developer.android.com/reference/java/lang/IllegalArgumentException.html)。

## 为文件授权

现在已经有了你想要共享给其他应用程序的文件所对应的Content URI,你需要允许客户端应用程序访问这个文件。为了达到这一目的,可以通过将Content URI添加至一个[Intent](http://developer.android.com/reference/android/content/Intent.html)中,然后为该[Intent](http://developer.android.com/reference/android/content/Intent.html)设置权限标记。你所授予的权限是临时的,并且当接收文件的应用程序的任务栈终止后,会自动过期。

下面的例子展示了如何为文件设置读权限:

```java
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // Define a listener that responds to clicks in the ListView
        mFileListView.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView,
                    View view,
                    int position,
                    long rowId) {
                ...
                if (fileUri != null) {
                    // Grant temporary read permission to the content URI
                    mResultIntent.addFlags(
                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
                ...
             }
             ...
        });
    ...
    }
```

> **Caution:**只有调用setFlags()来为你的文件授予临时被访问权限才是唯一的,安全的方法。尽量避免对文件的Content URI调用Context.grantUriPermission(),因为通过该方法授予的权限,你只能通过调用Context.revokeUriPermission()来撤销。

## 与请求应用共享文件

为了向请求文件的应用程序提供其需要的文件,我们将包含了Content URI和相应权限的[Intent](http://developer.android.com/reference/android/content/Intent.html)传递给setResult()。当你定义的[Activity](http://developer.android.com/reference/android/app/Activity.html)结束后,系统会把这个包含了Content URI的[Intent](http://developer.android.com/reference/android/content/Intent.html)传递给客户端应用程序。下面的例子展示了其中的核心步骤:

```java
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // Define a listener that responds to clicks on a file in the ListView
        mFileListView.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView,
                    View view,
                    int position,
                    long rowId) {
                ...
                if (fileUri != null) {
                    ...
                    // Put the Uri and MIME type in the result Intent
                    mResultIntent.setDataAndType(
                            fileUri,
                            getContentResolver().getType(fileUri));
                    // Set the result
                    MainActivity.this.setResult(Activity.RESULT_OK,
                            mResultIntent);
                    } else {
                        mResultIntent.setDataAndType(null, "");
                        MainActivity.this.setResult(RESULT_CANCELED,
                                mResultIntent);
                    }
                }
        });
```

当用户选择好文件后,我们应该向用户提供一个能够立即回到客户端应用程序的方法。一种实现的方法是向用户提供一个勾选框或者一个完成按钮。可以使用按钮的[android:onClick](http://developer.android.com/reference/android/view/View.html#attr_android:onClick)属性字段为它关联一个方法。在该方法中,调用finish()。例如:

```java
    public void onDoneClick(View v) {
        // Associate a method with the Done button
        finish();
    }
```


text:
<assembly>

    <formats>
        <format>zip</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>

    <dependencySets>
        <dependencySet>
            <outputDirectory>lib</outputDirectory>
        </dependencySet>
    </dependencySets>

    <fileSets>
        <fileSet>
            <directory>${project.build.directory}/classes</directory>
            <includes>
                <include>*.xml</include>
            </includes>
            <outputDirectory>/resources</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>${basedir}/src/main/resources</directory>
            <includes>
                <include>*.sh</include>
            </includes>
            <filtered>true</filtered>
            <outputDirectory>/</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>${basedir}/src/main/resources/META-INF</directory>
            <includes>
                <include>*.sh</include>
            </includes>
            <filtered>true</filtered>
            <outputDirectory>/META-INF</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>${basedir}/src/main/resources/init</directory>
            <includes>
                <include>*</include>
            </includes>
            <filtered>true</filtered>
            <outputDirectory>/init</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>${basedir}/src/main/startup/apache</directory>
            <includes>
                <include>*.properties</include>
            </includes>
            <filtered>true</filtered>
            <outputDirectory>/</outputDirectory>
        </fileSet>
    </fileSets>
</assembly>


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.eventregistry.model;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

/**
 * @author Filip Hrisafov
 */
@JsonInclude(Include.NON_NULL)
public class KafkaOutboundChannelModel extends OutboundChannelModel {

    protected String topic;
    protected String recordKey;

    public KafkaOutboundChannelModel() {
        super();
        setType("kafka");
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public String getRecordKey() {
        return recordKey;
    }

    public void setRecordKey(String recordKey) {
        this.recordKey = recordKey;
    }
}


text:
package org.libx4j.rdb.jsql;

public interface Delete {
  public interface DELETE extends ExecuteUpdate {
  }

  public interface _DELETE extends DELETE {
    public DELETE WHERE(final Condition<?> condition);
  }
}


text:
package org.apache.axis2.soap12testing.handlers;

public interface HeaderConstants {

    String REQUEST_HEADERBLOCK_NAME = "echoOk";
    String RESPONSE_HEADERBLOCK_NAME = "responseOk";
    String SAMPLE_ROLE = "http://example.org/ts-tests";
    String SOAP12_ROLE = "http://www.w3.org/2003/05/soap-envelope/role";
    String ULTIMATERECEIVER_ROLE = "ultimateReceiver";
    String NEXT_ROLE = "next";
    String NONE_ROLE = "none";
    String ROLE_BY_B = "B";
    String ROLE_BY_C = "C";
}


text:
.pgwSlideshow {
    width: 100%;
    background: #333;
    display: none;
}

.pgwSlideshow a{
    color: #black;
}

.pgwSlideshow .ps-current {
    text-align: center;
    position: relative;
    min-height: 150px;
    overflow: hidden;
}

.pgwSlideshow .ps-current > ul  > li {
    text-align: center;
    width: 100%;
    z-index: 1;
    opacity: 0;
    display: block;
}

.pgwSlideshow .ps-current > ul  > li img {
    display: block;
    max-width: 100%;
    margin: auto;
}

.pgwSlideshow .ps-caption {
    background: rgba(0, 0, 0, 0.5);
    filter:  progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#99000000', endColorstr='#99000000');
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#99000000', endColorstr='#99000000')";
    text-align: left;
    font-size: 1rem;
    color: #black;
    position: absolute;
    left: 0px;
    bottom: 0px;
    width: 100%;
    padding: 10px;
    display: none;
}

.pgwSlideshow .ps-caption span {
    padding: 7px;
    display: inline-block;
}

.pgwSlideshow .ps-list {
    border-top: 1px solid #555;
    box-shadow: 0 10px 10px -5px #333 inset;
    background: #555;
    overflow: hidden;
    position: relative;
}

.pgwSlideshow .ps-list ul {
    position: relative;
    list-style: none;
    margin: 0;
    padding: 0;
    left: 0;
}

.pgwSlideshow .ps-list li {
    float: left;
}

.pgwSlideshow .ps-list li .ps-item {
    display: block;
    margin: 15px 8px;
    opacity: 0.6;
    filter: alpha(opacity=60);
}

.pgwSlideshow .ps-list li img {
    display: block;
    border: 1px solid #777;
    width: 80px;
    height: 80px;
}

.pgwSlideshow .ps-list li .ps-item.ps-selected {
    float: left;
    opacity: 1;
    border: 4px solid #black;
    overflow: hidden;
}

.pgwSlideshow .ps-list li .ps-item.ps-selected img {
    margin: -4px;
}

.pgwSlideshow .ps-prevIcon {
    border-color:transparent #black transparent;
    border-style: solid;
    border-width: 10px 10px 10px 0;
    display: block;
}

.pgwSlideshow .ps-nextIcon {
    border-color:transparent #black transparent;
    border-style: solid;
    border-width: 10px 0 10px 10px;
    display: block;
}

.pgwSlideshow .ps-current .ps-prev {
    background: rgba(0, 0, 0, 0.5);
    filter:  progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#99000000', endColorstr='#99000000');
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#99000000', endColorstr='#99000000')";
    border: 1px solid #777;
    border-left: 0;
    border-radius: 0 4px 4px 0;
    position: absolute;
    padding: 20px 20px 20px 15px;
    left: 0;
    top: 45%;
    cursor: pointer;
}

.pgwSlideshow .ps-current .ps-next {
    background: rgba(0, 0, 0, 0.5);
    filter:  progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#99000000', endColorstr='#99000000');
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#99000000', endColorstr='#99000000')";
    border: 1px solid #777;
    border-right: 0;
    border-radius: 4px 0 0 4px;
    position: absolute;
    padding: 20px 15px 20px 20px;
    right: 0;
    top: 45%;
    cursor: pointer;
}

.pgwSlideshow .ps-list .ps-prev {
    background: rgba(0, 0, 0, 0.5);
    filter:  progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#bb000000', endColorstr='#bb000000');
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#bb000000', endColorstr='#bb000000')";
    border: 1px solid #777;
    border-left: 0;
    border-radius: 0 4px 4px 0;
    padding: 20px 15px 20px 12px;
    cursor: pointer;
    position: absolute;
    left: 0;
    top: 25px;
    z-index: 1000;
    display: none;
}

.pgwSlideshow .ps-list .ps-next {
    background: rgba(0, 0, 0, 0.5);
    filter:  progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#bb000000', endColorstr='#bb000000');
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#bb000000', endColorstr='#bb000000')";
    border: 1px solid #777;
    border-right: 0;
    border-radius: 4px 0 0 4px;
    padding: 20px 12px 20px 15px;
    cursor: pointer;
    position: absolute;
    right: 0;
    top: 25px;
    z-index: 1000;
    display: none;
}

/*
 * The media-queries are not used because IE8 doesn't support them.
 */
.pgwSlideshow.narrow .ps-list li img {
    width: 60px;
    height: 60px;
}

.pgwSlideshow.narrow .ps-current .ps-prev {
    padding: 15px 15px 15px 12px;
    top: 40%;
}

.pgwSlideshow.narrow .ps-current .ps-next {
    padding: 15px 12px 15px 15px;
    top: 40%;
}

.pgwSlideshow.narrow .ps-list .ps-prev {
    padding: 15px 12px 15px 10px;
    top: 20px;
}

.pgwSlideshow.narrow .ps-list .ps-next {
    padding: 15px 10px 15px 12px;
    top: 20px;
}

.pgwSlideshow.narrow .ps-caption {
    font-size: 0.8rem;
    padding: 8px;
}


text:
/* ---------------------------------------------------------------- */
/* (C)Copyright IBM Corp.  2007, 2008                               */
/* ---------------------------------------------------------------- */
/**
 * \file ad_gpfs_open.c
 * \brief ???
 */

/* -*- Mode: C; c-basic-offset:4 ; -*- */
/*
 *   Copyright (C) 1997 University of Chicago.
 *   See COPYRIGHT notice in top-level directory.
 */

#include "ad_gpfs.h"
#include "ad_gpfs_tuning.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#ifdef HAVE_GPFS_H
#include <gpfs.h>
#endif
#ifdef HAVE_GPFS_FCNTL_H
#include <gpfs_fcntl.h>
#endif

#ifdef HAVE_GPFS_FCNTL_H
static void gpfs_free_all_locks(int fd)
{
    int rc;
    struct {
	gpfsFcntlHeader_t header;
	gpfsFreeRange_t release;
    } release_all;

    release_all.header.totalLength = sizeof(release_all);
    release_all.header.fcntlVersion = GPFS_FCNTL_CURRENT_VERSION;
    release_all.header.fcntlReserved = 0;

    release_all.release.structLen = sizeof(release_all.release);
    release_all.release.structType = GPFS_FREE_RANGE;
    release_all.release.start = 0;
    release_all.release.length = 0;

    rc = gpfs_fcntl(fd, &release_all);
    if (rc != 0) {
	DBGV_FPRINTF(stderr,"GPFS fcntl release failed with rc=%d, errno=%d\n",
		rc,errno);
    }
}
#endif

void ADIOI_GPFS_Open(ADIO_File fd, int *error_code)
{
  int perm, old_mask, amode, rank, rc;
  static char myname[] = "ADIOI_GPFS_OPEN";

  /* set internal variables for tuning environment variables */
  ad_gpfs_get_env_vars();

  if (fd->perm == ADIO_PERM_NULL)  {
    old_mask = umask(022);
    umask(old_mask);
    perm = old_mask ^ 0666;
  }
  else perm = fd->perm;

    amode = 0;
    if (fd->access_mode & ADIO_CREATE)
	amode = amode | O_CREAT;
    if (fd->access_mode & ADIO_RDONLY)
	amode = amode | O_RDONLY;
    if (fd->access_mode & ADIO_WRONLY)
	amode = amode | O_WRONLY;
    if (fd->access_mode & ADIO_RDWR)
	amode = amode | O_RDWR;
    if (fd->access_mode & ADIO_EXCL)
	amode = amode | O_EXCL;
#ifdef ADIOI_MPE_LOGGING
    MPE_Log_event(ADIOI_MPE_open_a, 0, NULL);
#endif
    fd->fd_sys = open(fd->filename, amode, perm);
#ifdef ADIOI_MPE_LOGGING
    MPE_Log_event(ADIOI_MPE_open_b, 0, NULL);
#endif
  DBG_FPRINTF(stderr,"open('%s',%#X,%#X) rc=%d, errno=%d\n",fd->filename,amode,perm,fd->fd_sys,errno);
  fd->fd_direct = -1;

  if (gpfsmpio_devnullio == 1) {
      fd->null_fd = open("/dev/null", O_RDWR);
  } else {
      fd->null_fd = -1;
  }

  if ((fd->fd_sys != -1) && (fd->access_mode & ADIO_APPEND))
    fd->fp_ind = fd->fp_sys_posn = lseek(fd->fd_sys, 0, SEEK_END);

    if(fd->fd_sys != -1)
    {

        fd->blksize = 1048576; /* default to 1M */

#ifdef ADIOI_MPE_LOGGING
        MPE_Log_event(ADIOI_MPE_stat_a, 0, NULL);
#endif
	/* in this fs-specific routine, we might not be called over entire
	 * communicator (deferred open).  Collect statistics on one process.
	 * ADIOI_GEN_Opencoll (common-code caller) will take care of the
	 * broadcast */

	MPI_Comm_rank(fd->comm, &rank);
	if ((rank == fd->hints->ranklist[0]) || (fd->comm == MPI_COMM_SELF)) {
	    struct stat64 gpfs_statbuf;
	    /* Get the (real) underlying file system block size */
	    rc = stat64(fd->filename, &gpfs_statbuf);
	    if (rc >= 0)
	    {
		fd->blksize = gpfs_statbuf.st_blksize;
		DBGV_FPRINTF(stderr,"Successful stat '%s'.  Blocksize=%ld\n",
			fd->filename,gpfs_statbuf.st_blksize);
	    }
	    else
	    {
		DBGV_FPRINTF(stderr,"Stat '%s' failed with rc=%d, errno=%d\n",
			fd->filename,rc,errno);
	    }
	}
	/* all other ranks have incorrect fd->blocksize, but ADIOI_GEN_Opencoll
	 * will take care of that in both standard and deferred-open case */

#ifdef ADIOI_MPE_LOGGING
        MPE_Log_event(ADIOI_MPE_stat_b, 0, NULL);
#endif

#ifdef HAVE_GPFS_FCNTL_H
	/* in parallel workload, might be helpful to immediately release block
	 * tokens.  Or, system call overhead will outweigh any benefits... */
	if (getenv("ROMIO_GPFS_FREE_LOCKS")!=NULL)
	    gpfs_free_all_locks(fd->fd_sys);

#endif
    }

  if (fd->fd_sys == -1)  {
      *error_code = ADIOI_Err_create_code(myname, fd->filename, errno);
  }
  else *error_code = MPI_SUCCESS;
}
/*
 *vim: ts=8 sts=4 sw=4 noexpandtab
 */


text:
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using log4net.Config;
using LightInject;
using Yak.DTO;
using Yak.Services.Interfaces;
using Yak.Web;
using Yak.Web.Interfaces;
using Yak.Web.Models;

namespace Yak
{
    public class MvcApplication : HttpApplication
    {
        private static ServiceContainer _serviceContainer;

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            _serviceContainer = new ServiceContainer();
            _serviceContainer.RegisterControllers(typeof(MvcApplication).Assembly);
            _serviceContainer.EnableMvc();

            XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
        }

        public void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs e)
        {
            var customPrincipal = User as ICustomPrincipal;
            if (customPrincipal == null && e.Identity != null)
            {
                customPrincipal = new CustomPrincipal(_serviceContainer.GetInstance<IService<User>>(), e.Identity);
                HttpContext.Current.User = customPrincipal;
            }

            if (customPrincipal != null && customPrincipal.DatabaseUser == null)
            {
                var userSrvice = _serviceContainer.GetInstance<IService<User>>();
                var newUser = new User
                {
                    Username = customPrincipal.Identity.Name.Split('\\')[1],
                    // TODO: somehow get user email address from AD
                    Email = "test@test.test"
                };

                userSrvice.Add(newUser);
            }
        }
    }
}