text:
from oslo_config import cfg
from oslo_log import log
from oslo_utils import excutils
from oslo_utils import units
import six.moves.urllib_parse as urlparse

from ironic.common import dhcp_factory
from ironic.common import exception
from ironic.common.glance_service import service_utils
from ironic.common.i18n import _
from ironic.common.i18n import _LE
from ironic.common.i18n import _LI
from ironic.common.i18n import _LW
from ironic.common import image_service
from ironic.common import images
from ironic.common import paths
from ironic.common import raid
from ironic.common import states
from ironic.common import utils
from ironic.conductor import task_manager
from ironic.conductor import utils as manager_utils
from ironic.drivers import base
from ironic.drivers.modules import agent_base_vendor
from ironic.drivers.modules import deploy_utils

agent_opts = [
    cfg.StrOpt('agent_pxe_append_params',
               default='nofb nomodeset vga=normal',
               help=_('DEPRECATED. Additional append parameters for '
                      'baremetal PXE boot. This option is deprecated and '
                      'will be removed in Mitaka release. Please use '
                      '[pxe]pxe_append_params instead.')),
    cfg.StrOpt('agent_pxe_config_template',
               default=paths.basedir_def(
                   'drivers/modules/agent_config.template'),
               help=_('DEPRECATED. Template file for PXE configuration. '
                      'This option is deprecated and will be removed '
                      'in Mitaka release. Please use [pxe]pxe_config_template '
                      'instead.')),
    cfg.BoolOpt('manage_agent_boot',
                default=True,
                deprecated_name='manage_tftp',
                help=_('Whether Ironic will manage booting of the agent '
                       'ramdisk. If set to False, you will need to configure '
                       'your mechanism to allow booting the agent '
                       'ramdisk.')),
    cfg.IntOpt('memory_consumed_by_agent',
               default=0,
               help=_('The memory size in MiB consumed by agent when it is '
                      'booted on a bare metal node. This is used for '
                      'checking if the image can be downloaded and deployed '
                      'on the bare metal node after booting agent ramdisk. '
                      'This may be set according to the memory consumed by '
                      'the agent ramdisk image.')),
    cfg.BoolOpt('stream_raw_images',
                default=True,
                help=_('Whether the agent ramdisk should stream raw images '
                       'directly onto the disk or not. By streaming raw '
                       'images directly onto the disk the agent ramdisk will '
                       'not spend time copying the image to a tmpfs partition '
                       '(therefore consuming less memory) prior to writing it '
                       'to the disk. Unless the disk where the image will be '
                       'copied to is really slow, this option should be set '
                       'to True. Defaults to True.')),
]

CONF = cfg.CONF
CONF.import_opt('my_ip', 'ironic.netconf')
CONF.import_opt('erase_devices_priority',
                'ironic.drivers.modules.deploy_utils', group='deploy')
CONF.register_opts(agent_opts, group='agent')

LOG = log.getLogger(__name__)

REQUIRED_PROPERTIES = {
    'deploy_kernel': _('UUID (from Glance) of the deployment kernel. '
                       'Required.'),
    'deploy_ramdisk': _('UUID (from Glance) of the ramdisk with agent that is '
                        'used at deploy time. Required.'),
}

OPTIONAL_PROPERTIES = {
    'image_http_proxy': _('URL of a proxy server for HTTP connections. '
                          'Optional.'),
    'image_https_proxy': _('URL of a proxy server for HTTPS connections. '
                           'Optional.'),
    'image_no_proxy': _('A comma-separated list of host names, IP addresses '
                        'and domain names (with optional :port) that will be '
                        'excluded from proxying. To denote a doman name, use '
                        'a dot to prefix the domain name. This value will be '
                        'ignored if ``image_http_proxy`` and '
                        '``image_https_proxy`` are not specified. Optional.'),
}

COMMON_PROPERTIES = REQUIRED_PROPERTIES.copy()
COMMON_PROPERTIES.update(OPTIONAL_PROPERTIES)

def build_instance_info_for_deploy(task):
    """Build instance_info necessary for deploying to a node.

    :param task: a TaskManager object containing the node
    :returns: a dictionary containing the properties to be updated
        in instance_info
    :raises: exception.ImageRefValidationFailed if image_source is not
        Glance href and is not HTTP(S) URL.
    """
    node = task.node
    instance_info = node.instance_info

    image_source = instance_info['image_source']
    if service_utils.is_glance_image(image_source):
        glance = image_service.GlanceImageService(version=2,
                                                  context=task.context)
        image_info = glance.show(image_source)
        swift_temp_url = glance.swift_temp_url(image_info)
        LOG.debug('Got image info: %(info)s for node %(node)s.',
                  {'info': image_info, 'node': node.uuid})
        instance_info['image_url'] = swift_temp_url
        instance_info['image_checksum'] = image_info['checksum']
        instance_info['image_disk_format'] = image_info['disk_format']
        instance_info['image_container_format'] = (
            image_info['container_format'])
    else:
        try:
            image_service.HttpImageService().validate_href(image_source)
        except exception.ImageRefValidationFailed:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE("Agent deploy supports only HTTP(S) URLs as "
                              "instance_info['image_source']. Either %s "
                              "is not a valid HTTP(S) URL or "
                              "is not reachable."), image_source)
        instance_info['image_url'] = image_source

    return instance_info

def check_image_size(task, image_source):
    """Check if the requested image is larger than the ram size.

    :param task: a TaskManager instance containing the node to act on.
    :param image_source: href of the image.
    :raises: InvalidParameterValue if size of the image is greater than
        the available ram size.
    """
    node = task.node
    properties = node.properties
    # skip check if 'memory_mb' is not defined
    if 'memory_mb' not in properties:
        LOG.warning(_LW('Skip the image size check as memory_mb is not '
                        'defined in properties on node %s.'), node.uuid)
        return

    image_show = images.image_show(task.context, image_source)
    if CONF.agent.stream_raw_images and image_show.get('disk_format') == 'raw':
        LOG.debug('Skip the image size check since the image is going to be '
                  'streamed directly onto the disk for node %s', node.uuid)
        return

    memory_size = int(properties.get('memory_mb'))
    image_size = int(image_show['size'])
    reserved_size = CONF.agent.memory_consumed_by_agent
    if (image_size + (reserved_size * units.Mi)) > (memory_size * units.Mi):
        msg = (_('Memory size is too small for requested image, if it is '
                 'less than (image size + reserved RAM size), will break '
                 'the IPA deployments. Image size: %(image_size)d MiB, '
                 'Memory size: %(memory_size)d MiB, Reserved size: '
                 '%(reserved_size)d MiB.')
               % {'image_size': image_size / units.Mi,
                  'memory_size': memory_size,
                  'reserved_size': reserved_size})
        raise exception.InvalidParameterValue(msg)

def validate_image_proxies(node):
    """Check that the provided proxy parameters are valid.

    :param node: an Ironic node.
    :raises: InvalidParameterValue if any of the provided proxy parameters are
        incorrect.
    """
    invalid_proxies = {}
    for scheme in ('http', 'https'):
        proxy_param = 'image_%s_proxy' % scheme
        proxy = node.driver_info.get(proxy_param)
        if proxy:
            chunks = urlparse.urlparse(proxy)
            # NOTE(vdrok) If no scheme specified, this is still a valid
            # proxy address. It is also possible for a proxy to have a
            # scheme different from the one specified in the image URL,
            # e.g. it is possible to use https:// proxy for downloading
            # http:// image.
            if chunks.scheme not in ('', 'http', 'https'):
                invalid_proxies[proxy_param] = proxy
    msg = ''
    if invalid_proxies:
        msg += _("Proxy URL should either have HTTP(S) scheme "
                 "or no scheme at all, the following URLs are "
                 "invalid: %s.") % invalid_proxies
    no_proxy = node.driver_info.get('image_no_proxy')
    if no_proxy is not None and not utils.is_valid_no_proxy(no_proxy):
        msg += _(
            "image_no_proxy should be a list of host names, IP addresses "
            "or domain names to exclude from proxying, the specified list "
            "%s is incorrect. To denote a domain name, prefix it with a dot "
            "(instead of e.g. '.*').") % no_proxy
    if msg:
        raise exception.InvalidParameterValue(msg)

class AgentDeploy(base.DeployInterface):
    """Interface for deploy-related actions."""

    def get_properties(self):
        """Return the properties of the interface.

        :returns: dictionary of <property name>:<property description> entries.
        """
        return COMMON_PROPERTIES

    def validate(self, task):
        """Validate the driver-specific Node deployment info.

        This method validates whether the properties of the supplied node
        contain the required information for this driver to deploy images to
        the node.

        :param task: a TaskManager instance
        :raises: MissingParameterValue, if any of the required parameters are
            missing.
        :raises: InvalidParameterValue, if any of the parameters have invalid
            value.
        """
        if CONF.agent.manage_agent_boot:
            task.driver.boot.validate(task)

        node = task.node
        params = {}
        image_source = node.instance_info.get('image_source')
        params['instance_info.image_source'] = image_source
        error_msg = _('Node %s failed to validate deploy image info. Some '
                      'parameters were missing') % node.uuid
        deploy_utils.check_for_missing_params(params, error_msg)

        if not service_utils.is_glance_image(image_source):
            if not node.instance_info.get('image_checksum'):
                raise exception.MissingParameterValue(_(
                    "image_source's image_checksum must be provided in "
                    "instance_info for node %s") % node.uuid)

        check_image_size(task, image_source)
        is_whole_disk_image = node.driver_internal_info.get(
            'is_whole_disk_image')
        # TODO(sirushtim): Remove once IPA has support for partition images.
        if is_whole_disk_image is False:
            raise exception.InvalidParameterValue(_(
                "Node %(node)s is configured to use the %(driver)s driver "
                "which currently does not support deploying partition "
                "images.") % {'node': node.uuid, 'driver': node.driver})

        # Validate the root device hints
        deploy_utils.parse_root_device_hints(node)

        # Validate node capabilities
        deploy_utils.validate_capabilities(node)

        validate_image_proxies(node)

    @task_manager.require_exclusive_lock
    def deploy(self, task):
        """Perform a deployment to a node.

        Perform the necessary work to deploy an image onto the specified node.
        This method will be called after prepare(), which may have already
        performed any preparatory steps, such as pre-caching some data for the
        node.

        :param task: a TaskManager instance.
        :returns: status of the deploy. One of ironic.common.states.
        """
        manager_utils.node_power_action(task, states.REBOOT)
        return states.DEPLOYWAIT

    @task_manager.require_exclusive_lock
    def tear_down(self, task):
        """Tear down a previous deployment on the task's node.

        :param task: a TaskManager instance.
        :returns: status of the deploy. One of ironic.common.states.
        """
        manager_utils.node_power_action(task, states.POWER_OFF)
        return states.DELETED

    def prepare(self, task):
        """Prepare the deployment environment for this node.

        :param task: a TaskManager instance.
        """
        # Nodes deployed by AgentDeploy always boot from disk now. So there
        # is nothing to be done in prepare() when it's called during
        # take over.
        node = task.node
        if node.provision_state != states.ACTIVE:
            node.instance_info = build_instance_info_for_deploy(task)
            node.save()
            if CONF.agent.manage_agent_boot:
                deploy_opts = deploy_utils.build_agent_options(node)
                task.driver.boot.prepare_ramdisk(task, deploy_opts)

    def clean_up(self, task):
        """Clean up the deployment environment for this node.

        If preparation of the deployment environment ahead of time is possible,
        this method should be implemented by the driver. It should erase
        anything cached by the `prepare` method.

        If implemented, this method must be idempotent. It may be called
        multiple times for the same node on the same conductor, and it may be
        called by multiple conductors in parallel. Therefore, it must not
        require an exclusive lock.

        This method is called before `tear_down`.

        :param task: a TaskManager instance.
        """
        if CONF.agent.manage_agent_boot:
            task.driver.boot.clean_up_ramdisk(task)
        provider = dhcp_factory.DHCPFactory()
        provider.clean_dhcp(task)

    def take_over(self, task):
        """Take over management of this node from a dead conductor.

        Since this deploy interface only does local boot, there's no need
        for this conductor to do anything when it takes over management
        of this node.

        :param task: a TaskManager instance.
        """
        pass

    def get_clean_steps(self, task):
        """Get the list of clean steps from the agent.

        :param task: a TaskManager object containing the node

        :returns: A list of clean step dictionaries
        """
        new_priorities = {
            'erase_devices': CONF.deploy.erase_devices_priority,
        }
        return deploy_utils.agent_get_clean_steps(
            task, interface='deploy',
            override_priorities=new_priorities)

    def execute_clean_step(self, task, step):
        """Execute a clean step asynchronously on the agent.

        :param task: a TaskManager object containing the node
        :param step: a clean step dictionary to execute
        :raises: NodeCleaningFailure if the agent does not return a command
            status
        :returns: states.CLEANWAIT to signify the step will be completed async
        """
        return deploy_utils.agent_execute_clean_step(task, step)

    def prepare_cleaning(self, task):
        """Boot into the agent to prepare for cleaning.

        :param task: a TaskManager object containing the node
        :raises NodeCleaningFailure: if the previous cleaning ports cannot
            be removed or if new cleaning ports cannot be created
        :returns: states.CLEANWAIT to signify an asynchronous prepare
        """
        return deploy_utils.prepare_inband_cleaning(
            task, manage_boot=CONF.agent.manage_agent_boot)

    def tear_down_cleaning(self, task):
        """Clean up the PXE and DHCP files after cleaning.

        :param task: a TaskManager object containing the node
        :raises NodeCleaningFailure: if the cleaning ports cannot be
            removed
        """
        deploy_utils.tear_down_inband_cleaning(
            task, manage_boot=CONF.agent.manage_agent_boot)

class AgentVendorInterface(agent_base_vendor.BaseAgentVendor):

    def deploy_has_started(self, task):
        commands = self._client.get_commands_status(task.node)

        for command in commands:
            if command['command_name'] == 'prepare_image':
                # deploy did start at some point
                return True
        return False

    def deploy_is_done(self, task):
        commands = self._client.get_commands_status(task.node)
        if not commands:
            return False

        last_command = commands[-1]

        if last_command['command_name'] != 'prepare_image':
            # catches race condition where prepare_image is still processing
            # so deploy hasn't started yet
            return False

        if last_command['command_status'] != 'RUNNING':
            return True

        return False

    @task_manager.require_exclusive_lock
    def continue_deploy(self, task, **kwargs):
        task.process_event('resume')
        node = task.node
        image_source = node.instance_info.get('image_source')
        LOG.debug('Continuing deploy for node %(node)s with image %(img)s',
                  {'node': node.uuid, 'img': image_source})

        image_info = {
            'id': image_source.split('/')[-1],
            'urls': [node.instance_info['image_url']],
            'checksum': node.instance_info['image_checksum'],
            # NOTE(comstud): Older versions of ironic do not set
            # 'disk_format' nor 'container_format', so we use .get()
            # to maintain backwards compatibility in case code was
            # upgraded in the middle of a build request.
            'disk_format': node.instance_info.get('image_disk_format'),
            'container_format': node.instance_info.get(
                'image_container_format'),
            'stream_raw_images': CONF.agent.stream_raw_images,
        }

        proxies = {}
        for scheme in ('http', 'https'):
            proxy_param = 'image_%s_proxy' % scheme
            proxy = node.driver_info.get(proxy_param)
            if proxy:
                proxies[scheme] = proxy
        if proxies:
            image_info['proxies'] = proxies
            no_proxy = node.driver_info.get('image_no_proxy')
            if no_proxy is not None:
                image_info['no_proxy'] = no_proxy

        # Tell the client to download and write the image with the given args
        self._client.prepare_image(node, image_info)

        task.process_event('wait')

    def check_deploy_success(self, node):
        # should only ever be called after we've validated that
        # the prepare_image command is complete
        command = self._client.get_commands_status(node)[-1]
        if command['command_status'] == 'FAILED':
            return command['command_error']

    def reboot_to_instance(self, task, **kwargs):
        task.process_event('resume')
        node = task.node
        error = self.check_deploy_success(node)
        if error is not None:
            # TODO(jimrollenhagen) power off if using neutron dhcp to
            #                      align with pxe driver?
            msg = (_('node %(node)s command status errored: %(error)s') %
                   {'node': node.uuid, 'error': error})
            LOG.error(msg)
            deploy_utils.set_failed_state(task, msg)
            return

        LOG.info(_LI('Image successfully written to node %s'), node.uuid)
        LOG.debug('Rebooting node %s to instance', node.uuid)

        manager_utils.node_set_boot_device(task, 'disk', persistent=True)
        self.reboot_and_finish_deploy(task)

        # NOTE(TheJulia): If we deployed a whole disk image, we
        # should expect a whole disk image and clean-up the tftp files
        # on-disk incase the node is disregarding the boot preference.
        # TODO(rameshg87): Not all in-tree drivers using reboot_to_instance
        # have a boot interface. So include a check for now. Remove this
        # check once all in-tree drivers have a boot interface.
        if task.driver.boot:
            task.driver.boot.clean_up_ramdisk(task)

class AgentRAID(base.RAIDInterface):
    """Implementation of RAIDInterface which uses agent ramdisk."""

    def get_properties(self):
        """Return the properties of the interface."""
        return {}

    @base.clean_step(priority=0)
    def create_configuration(self, task,
                             create_root_volume=True,
                             create_nonroot_volumes=True):
        """Create a RAID configuration on a bare metal using agent ramdisk.

        This method creates a RAID configuration on the given node.

        :param task: a TaskManager instance.
        :param create_root_volume: If True, a root volume is created
            during RAID configuration. Otherwise, no root volume is
            created. Default is True.
        :param create_nonroot_volumes: If True, non-root volumes are
            created. If False, no non-root volumes are created. Default
            is True.
        :returns: states.CLEANWAIT if operation was successfully invoked.
        :raises: MissingParameterValue, if node.target_raid_config is missing
            or was found to be empty after skipping root volume and/or non-root
            volumes.
        """
        node = task.node
        LOG.debug("Agent RAID create_configuration invoked for node %(node)s "
                  "with create_root_volume=%(create_root_volume)s and "
                  "create_nonroot_volumes=%(create_nonroot_volumes)s with the "
                  "following target_raid_config: %(target_raid_config)s.",
                  {'node': node.uuid,
                   'create_root_volume': create_root_volume,
                   'create_nonroot_volumes': create_nonroot_volumes,
                   'target_raid_config': node.target_raid_config})

        if not node.target_raid_config:
            raise exception.MissingParameterValue(
                _("Node %s has no target RAID configuration.") % node.uuid)

        target_raid_config = node.target_raid_config.copy()

        error_msg_list = []
        if not create_root_volume:
            target_raid_config['logical_disks'] = [
                x for x in target_raid_config['logical_disks']
                if not x.get('is_root_volume')]
            error_msg_list.append(_("skipping root volume"))

        if not create_nonroot_volumes:
            error_msg_list.append(_("skipping non-root volumes"))

            target_raid_config['logical_disks'] = [
                x for x in target_raid_config['logical_disks']
                if x.get('is_root_volume')]

        if not target_raid_config['logical_disks']:
            error_msg = _(' and ').join(error_msg_list)
            raise exception.MissingParameterValue(
                _("Node %(node)s has empty target RAID configuration "
                  "after %(msg)s.") % {'node': node.uuid, 'msg': error_msg})

        # Rewrite it back to the node object, but no need to save it as
        # we need to just send this to the agent ramdisk.
        node.driver_internal_info['target_raid_config'] = target_raid_config

        LOG.debug("Calling agent RAID create_configuration for node %(node)s "
                  "with the following target RAID configuration: %(target)s",
                  {'node': node.uuid, 'target': target_raid_config})
        step = node.clean_step
        return deploy_utils.agent_execute_clean_step(task, step)

    @staticmethod
    @agent_base_vendor.post_clean_step_hook(
        interface='raid', step='create_configuration')
    def _create_configuration_final(task, command):
        """Clean step hook after a RAID configuration was created.

        This method is invoked as a post clean step hook by the Ironic
        conductor once a create raid configuration is completed successfully.
        The node (properties, capabilities, RAID information) will be updated
        to reflect the actual RAID configuration that was created.

        :param task: a TaskManager instance.
        :param command: A command result structure of the RAID operation
            returned from agent ramdisk on query of the status of command(s).
        :raises: InvalidParameterValue, if 'current_raid_config' has more than
            one root volume or if node.properties['capabilities'] is malformed.
        :raises: IronicException, if clean_result couldn't be found within
            the 'command' argument passed.
        """
        try:
            clean_result = command['command_result']['clean_result']
        except KeyError:
            raise exception.IronicException(
                _("Agent ramdisk didn't return a proper command result while "
                  "cleaning %(node)s. It returned '%(result)s' after command "
                  "execution.") % {'node': task.node.uuid,
                                   'result': command})

        raid.update_raid_info(task.node, clean_result)

    @base.clean_step(priority=0)
    def delete_configuration(self, task):
        """Deletes RAID configuration on the given node.

        :param task: a TaskManager instance.
        :returns: states.CLEANWAIT if operation was successfully invoked
        """
        LOG.debug("Agent RAID delete_configuration invoked for node %s.",
                  task.node.uuid)
        step = task.node.clean_step
        return deploy_utils.agent_execute_clean_step(task, step)

    @staticmethod
    @agent_base_vendor.post_clean_step_hook(
        interface='raid', step='delete_configuration')
    def _delete_configuration_final(task, command):
        """Clean step hook after RAID configuration was deleted.

        This method is invoked as a post clean step hook by the Ironic
        conductor once a delete raid configuration is completed successfully.
        It sets node.raid_config to empty dictionary.

        :param task: a TaskManager instance.
        :param command: A command result structure of the RAID operation
            returned from agent ramdisk on query of the status of command(s).
        :returns: None
        """
        task.node.raid_config = {}
        task.node.save()


text:
(function(factory) {
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else {
    factory(jQuery);
  }
}(function($) {

  var laziestLoader = function(options, callback) {

    var $w = $(window),
      $elements = this,
      $loaded = $(), // elements with the correct source set
      retina = window.devicePixelRatio > 1,
      didScroll = false;

    options = $.extend(true, {
      threshold: 0,
      sizePattern: /{{SIZE}}/ig,
      getSource: getSource,
      scrollThrottle: 250, // time in ms to throttle scroll. Increase for better performance.
      sizeOffsetPercent: 0, // prefer smaller images
      setSourceMode: true // plugin sets source attribute of the element. Set to false if you would like to, instead, use the callback to completely manage the element on trigger.
    }, options);

    /**
     * Generate source path of image to load. Take into account
     * type of data supplied and whether or not a retina
     * image is available.
     *
     * Basic option: data attributes specifing a single image to load,
     * regardless of viewport.
     * Eg:
     *
     *
     *
     *
     * Range of sizes: specify a string path with a {{size}} that
     * will be replaced by an integer from a list of available sizes.
     * Eg:
     *
     *
     *
     *
     *
     * Range of sizes, with slugs: specify a string path with a {{size}} that
     * will be replaced by a slug representing an image size.
     * Eg:
     *
     *
     *
     * @param  {jQuery object} $el
     * @return {String}
     */

    function getSource($el) {
      var source, slug;
      var data = $el.data();
      if (data.pattern && data.widths && $.isArray(data.widths)) {
        source = retina ? data.patternRetina : data.pattern;
        source = source || data.pattern;

        // width or slug version?
        if (typeof data.widths[0] === 'object') {
          slug = (function() {
            var widths = $.map(data.widths, function(val) {
              return val.size;
            });

            var bestFitWidth = bestFit($el.width(), widths);

            // match best width back to its corresponding slug
            for (var i = data.widths.length - 1; i >= 0; i--) {
              if (data.widths[i].size === bestFitWidth) {
                return data.widths[i].slug;
              }
            }
          })();

          source = source.replace(options.sizePattern, slug);
        } else {
          source = source.replace(options.sizePattern, bestFit($el.width(), data.widths));
        }
      } else {
        source = retina ? data.srcRetina : data.src;
        source = source || data.src;
      }

      return source;
    }

    /**
     * Reflect loaded state in class names
     * and fire event.
     *
     * @param  {jQuery Object} $el
     */
    function onLoad($el) {
      $el.addClass('ll-loaded').removeClass('ll-notloaded');
      $el.trigger('loaded');

      if (typeof callback === 'function') {
        callback.call($el);
      }
    }

    /**
     * Attach event handler that sets correct
     * media source for the elements' width, or
     * allows callback to manipulate element
     * exclusively.
     */

    function bindLoader() {
      $elements.one('laziestloader', function() {
        var $el = $(this);
        var source;

        // set height?
        if ($el.data().ratio) {
          setHeight.call(this);
        }

        // set content. default: set element source
        if (options.setSourceMode) {
          source = options.getSource($el);
          if (source && this.getAttribute('src') !== source) {
            this.setAttribute('src', source);
          }
        }

        // Determine when to fire `loaded` event. Wait until
        // media is truly loaded if possible, otherwise immediately
        if (options.setSourceMode && (this.nodeName === 'IMG' || this.nodeName === 'VIDEO' || this.nodeName === 'AUDIO') ) {
          if (this.nodeName === 'IMG') {
            this.onload = function() {
              onLoad($el);
            };
          } else {
            this.onloadstart = function() {
              onLoad($el);
            };
          }
        } else {
          onLoad($el);
        }
      });
    }

    /**
     * Remove even handler from elements
     */

    function unbindLoader() {
      $elements.off('laziestloader');
    }

    /**
     * Find the best sized image, opting for larger over smaller
     *
     * @param  {Number} targetWidth   element width
     * @param  {Array} widths         array of numbers
     * @return {Number}
     */

    var bestFit = laziestLoader.bestFit = function(targetWidth, widths) {
      var selectedWidth = widths[widths.length - 1],
        i = widths.length,
        offset = targetWidth * (options.sizeOffsetPercent / 100);

      // sort smallest to largest
      widths.sort(function(a, b) {
        return a - b;
      });

      while (i--) {
        if ((targetWidth - offset) <= widths[i]) {
          selectedWidth = widths[i];
        }
      }

      return selectedWidth;
    };

    /**
     * Cycle through elements that haven't had their
     * source set and, if they're in the viewport within
     * the threshold, load their media
     */

    function laziestloader() {
      var $inview = $elements.not($loaded).filter(function() {
        var $el = $(this),
          threshold = options.threshold;

        if ($el.is(':hidden')) return;

        var wt = $w.scrollTop(),
          wb = wt + $w.height(),
          et = $el.offset().top,
          eb = et + $el.height();

        return eb >= wt - threshold && et <= wb + threshold;
      });

      $inview.trigger('laziestloader');
      $loaded.add($inview);
    }

    function setHeight() {
      var $el = $(this),
        data = $el.data();

      data.ratio = data.ratio || data.heightMultiplier; // backwards compatible for old data-height-multiplier code.

      if (data.ratio) {
        $el.css({
          height: Math.round($el.width() * data.ratio)
        });
      }
    }

    // add inital state classes, and check if
    // element dimensions need to be set.
    $elements.addClass('ll-init ll-notloaded').each(setHeight);

    bindLoader();

    // throttled scroll events
    $w.scroll(function() {
      didScroll = true;
    });

    setInterval(function() {
      if (didScroll) {
        didScroll = false;
        laziestloader();
      }
    }, options.scrollThrottle);

    // reset state on resize
    $w.resize(function() {
      $loaded = $();
      unbindLoader();
      bindLoader();
      laziestloader();
    });

    laziestloader();

    return this;
  };

  $.fn.laziestloader = laziestLoader;

}));

redpajama_set_name: RedPajamaGithub


text:
require 'lhm/intersection'

module Lhm
  class Migration
    attr_reader :origin, :destination, :conditions, :renames

    def initialize(origin, destination, conditions = nil, renames = {}, time = Time.now)
      @origin = origin
      @destination = destination
      @conditions = conditions
      @start = time
      @renames = renames
    end

    def archive_name
      "lhma_#{ startstamp }_#{ @origin.name }"[0...64]
    end

    def intersection
      Intersection.new(@origin, @destination, @renames)
    end

    def startstamp
      @start.strftime "%Y_%m_%d_%H_%M_%S_#{ '%03d' % (@start.usec / 1000) }"
    end
  end
end


text:
<?php

class Denkmal_FormField_Venue extends CM_FormField_SuggestOne {

    protected function _initialize() {
        /** @var Denkmal_Params $params */
        $params = $this->getParams();
        $this->_options['region'] = $params->has('region') ? $params->getRegion('region') : null;
        parent::_initialize();
    }

    /**
     * @param CM_Frontend_Environment $environment
     * @param array                   $userInput
     * @return Denkmal_Model_Venue|string
     * @throws CM_Exception_FormFieldValidation
     */
    public function validate(CM_Frontend_Environment $environment, $userInput) {
        $value = parent::validate($environment, $userInput);
        if (null === $value) {
            throw new CM_Exception_FormFieldValidation(new CM_I18n_Phrase('Invalid venue data.'));
        }
        if (is_numeric($value)) {
            $value = new Denkmal_Model_Venue($value);
        } else {
            $value = (string) $value;
        }
        return $value;
    }

    /**
     * @param Denkmal_Model_Venue $item
     * @param CM_Frontend_Render  $render
     * @return array
     */
    public function getSuggestion($item, CM_Frontend_Render $render) {
        return array('id' => $item->getId(), 'name' => $item->getName());
    }

    protected function _getSuggestions($term, array $options, CM_Frontend_Render $render) {
        $term = (string) $term;
        $suggestions = array();
        $venueList = new Denkmal_Paging_Venue_All($this->_options['region'], true);
        /** @var $item Denkmal_Model_Venue */
        foreach ($venueList as $item) {
            if (0 === strlen($term) || false !== stripos($item->getName(), $term)) {
                $suggestions[] = $this->getSuggestion($item, $render);
            }
            if (count($suggestions) > 30) {
                break;
            }
        }
        return $suggestions;
    }
}


text:
using UnityEngine;
using UnityEngine.UI;

public class QuestView : MonoBehaviour
{
  public Text title;
  public Text description;
}


text:
/**
 * Created by chenjianjun on 16/2/26.
 */
import _ from 'lodash'
import env from '../cache/db/config'
let r = env.Thinky.r

import weddingClass from '../cache/db/module/weddingClass.js'

// 婚礼课堂API
const weddingClassApi = {

    // 获取婚礼课堂列表
    'get+/weddingroom/all': function*(next) {
        this.model = weddingClass
        this.APIKey = 'WeddingClass'
        yield next
    },
    'get+/weddingroom/:position': function*(next) {
        if (this.params.position === 'all') {
            this.model = weddingClass.filter({})
        } else {
            this.model = weddingClass.filter({
                position: this.params.position
            })
        }
        this.model = this.model.orderBy(r.desc('weight'))

        _.each(this.request.query, (v, k) => {
            if (k.indexOf('pageSize') !== -1) {
                let limit = 0
                limit = Number(this.request.query['pageIndex'] || '1') - 1
                if (limit < 0) {
                    limit = 0
                }
                this.model = this.model.skip(limit * Number(this.request.query["pageSize"] || '10'));
                this.model = this.model.limit(Number(this.request.query["pageSize"] || '10'));
            } else if(k.indexOf('moduleTypeId') !== -1) {
                // 模块类型
                this.model = this.model.filter({
                    moduleType: parseInt(this.request.query["moduleTypeId"])
                });
            }
        })

        this.APIKey = 'WeddingClass'
        yield next
    },
    // 获取婚礼课堂详情
    'get+/weddingroom/detail/:id': function*(next) {
        this.model = weddingClass.filter({
            id: parseInt(this.params.id)
        })

        this.APIKey = 'WeddingClass'
        yield next
    }

}

export default weddingClassApi


text:
template: post.html
title: Can the Rest of the System's Signals Modernized Without Years of Delays?
title: Computerized Signals on the 7 are Finally Actived. Will Upgrading the Whole System Also take Years of Delay.
title: 7 Train Signal Upgrades Fininished After Years of Delays
title: 7 Train Signal Upgrades Complete After Years of Delays. Up Next: The Rest of the Subway.
date: 2018-11-26
permalink: /flushing-cbtc-finished
shareimg: https://i.imgur.com/i5njD1m.png
---

After years of weekend closures, the MTA announced the completion of the 7 train's new, [computerized signal system](https://www.nytimes.com/2017/05/01/nyregion/new-york-subway-signals.html) yesterday.

Replacing finicky pneumatic electromechanical devices installed in the 50s, the modernized signals increase the number of trains the MTA can run on the 7 line, reduce "signal problems ahead," and lower maintenance costs. Over the next 10 years, the MTA plans to spend $20 billion upgrading every line's signals.

Past experience suggests this be will difficult.

##  The L and 7 Signal Upgrades Were Late and Over Budget

In their efforts to fix the subway, the MTA has addressed some of the issues that caused problems in the past. They're [buying](https://twitter.com/ModernSignaling/status/1053394646892720128) train cars that work with computer signals without retrofitting, a previous source of delays. The new head of New York City Transit, Andy Byford, has proposed shutting down all weekend and night travel for years while a line's signals are upgraded; the intermittent shutdowns on the 7 meant that additional days of necessary [trackwork](https://www.wsj.com/articles/nyc-subway-chief-faces-reality-check-in-push-for-upgrades-1540044000?redirect=amp#click=https://t.co/VSchTsaExm) could add a month to the project timeline.

But there are still problems.

## How the 7 Signal Completion Date Slipped Over Time

Plagued by software issues, the last two years of work on the 7 line took four years to finish. This isn't a new problem for the MTA. On a [previous signal project](https://www.theatlantic.com/technology/archive/2015/11/why-dont-we-know-where-all-the-trains-are/415152/), ad hoc deployment errors caused interruptions to train service. A vaguely specified voice communications system failed in the field. UIs that had only been prototyped in PowerPoint were hard to use and had to be redone.

Byford says he wants to buy "[off-the-shelf](https://www.nytimes.com/2018/06/11/nyregion/subway-signal-upgrade-plan.html)" to cut costs and reduce delays. His previous job as CEO of the Toronto Transit Commission provides a clue about what that'll entail.

## Combining Old and New Signaling Systems Isn't Easy

When Toronto decided to update its [50 year old signals](https://stevemunro.ca/2015/03/30/the-evolution-of-ttc-signaling-contracts/), they kept the old electromechanical signals in place and overlaid the computerized signals. This is hard to do: the computerized signals need heavily customized software that simulates how the old signals and interlocks work. And the amount of track work increases; instead of just putting down beacons that let the train car know its exact position, the old signals also require extensive modifications.

Faced with mounting delays, Byford [simplified](https://ttc.ca/About_the_TTC/Commission_reports_and_information/Commission_meetings/2015/March_26/Reports/5_2_Staff_Report_%26_Attachment.pdf). Instead of keeping the old signals, almost everything was computerized.

In its signal modernization efforts, the MTA is still overlaying rebuilt parts of the old signal system as a failsafe. Overlaying old signals accounts for a significant chunk of the project timeline on the signal modernization project currently underway on the Queens Boulevard Line:

    ![](cbtc-queens.png)

    QBL CBTC Installation RFQ via Philippe Vibien

A Federal Transit Administration [report](https://www.transit.dot.gov/sites/fta.dot.gov/files/docs/FTA_REPORT_No._0045.pdf) found that keeping the old signals isn't necessary and increased capital costs by at least 30%. The safety benefit is limited. In use, two sets of signals can actually decrease reliability because service is interpreted if one of them fails. Keeping the old signals working also requires regularly sending workers onto the tracks. Many of the upsides of computerized signals are negated.

## Things Will Get Worse Before They Get Better

Under the [current plan](https://fastforward.mta.info/transform-the-subway), each line will require years of weekend and overnight closures to overlay the computerized signals on the old signals. Even if the project stays within its scoped budget, this signal modernization will cost a huge amount of money. Already overloaded with [debt](https://www.nytimes.com/2017/11/18/nyregion/new-york-subway-system-failure-delays.html) and weighing [service cuts and fare hikes](https://www.nytimes.com/2018/11/15/nyregion/mta-fare-hike-nyc.html), the MTA has limited fiscal room to maneuver if there are steep cost overruns.

Will Byford continue to overlay two sets of signals or will he decide to simplify? The activation of the new signals on the 7 yesterday could impact the decision. There were extensive delays during the evening commute after a component of the old signal system [failed](https://www.nydailynews.com/new-york/ny-metro-7-train-signals-20181126-story.html).

*Nov. 27, 2018*

<link rel="stylesheet" type="text/css" href="/flushing-cbtc-finished/style.css">


text:
#ifndef StylePendingImage_h
#define StylePendingImage_h

#include "CSSImageGeneratorValue.h"
#if ENABLE(CSS_IMAGE_SET)
#include "CSSImageSetValue.h"
#endif
#include "CSSImageValue.h"
#include "Image.h"
#include "StyleImage.h"

namespace WebCore {

// StylePendingImage is a placeholder StyleImage that is entered into the RenderStyle during
// style resolution, in order to avoid loading images that are not referenced by the final style.
// They should never exist in a RenderStyle after it has been returned from the style selector.

class StylePendingImage : public StyleImage {
public:
    static PassRefPtr<StylePendingImage> create(CSSValue* value) { return adoptRef(new StylePendingImage(value)); }

    virtual WrappedImagePtr data() const { return static_cast<CSSImageValue*>(m_value); }

    virtual PassRefPtr<CSSValue> cssValue() const { return m_value; }
    CSSImageValue* cssImageValue() const { return m_value->isImageValue() ? static_cast<CSSImageValue*>(m_value) : 0; }
    CSSImageGeneratorValue* cssImageGeneratorValue() const { return m_value->isImageGeneratorValue() ? static_cast<CSSImageGeneratorValue*>(m_value) : 0; }
#if ENABLE(CSS_IMAGE_SET)
    CSSImageSetValue* cssImageSetValue() const { return m_value->isImageSetValue() ? static_cast<CSSImageSetValue*>(m_value) : 0; }
#endif

    virtual LayoutSize imageSize(const RenderObject*, float /*multiplier*/) const OVERRIDE { return LayoutSize(); }
    virtual bool imageHasRelativeWidth() const { return false; }
    virtual bool imageHasRelativeHeight() const { return false; }
    virtual void computeIntrinsicDimensions(const RenderObject*, Length& /* intrinsicWidth */ , Length& /* intrinsicHeight */, FloatSize& /* intrinsicRatio */) { }
    virtual bool usesImageContainerSize() const { return false; }
    virtual void setContainerSizeForRenderer(const RenderObject*, const IntSize&, float) { }
    virtual void addClient(RenderObject*) { }
    virtual void removeClient(RenderObject*) { }
    virtual PassRefPtr<Image> image(RenderObject*, const IntSize&) const
    {
        ASSERT_NOT_REACHED();
        return 0;
    }
    virtual bool hasAlpha(const RenderObject*) const { return true; }

private:
    StylePendingImage(CSSValue* value)
        : m_value(value)
    {
        m_isPendingImage = true;
    }

    CSSValue* m_value; // Not retained; it owns us.
};

}
#endif


text:
var React = require('react')
  , makeStubbedDescriptor = require('../../__tests__/makeStubbedDescriptor')
  , Launch = require('../Launch');

describe('Launch', function() {
  it('renders', function(done) {
    done();
  });
});


text:
module TestServer
  class FileUpload
    include ActiveModel::Validations
    include ActiveModel::Conversion
    extend ActiveModel::Naming

    attr_reader :virus_scan, :checksum_calculation, :filetype_detection

    def initialize(attributes = {})
      Hash(attributes).each do |name, value|
        send("#{name}=", value)
      end
    end

    [:virus_scan, :checksum_calculation, :filetype_detection ].each do |m|
      define_method :"#{m}=" do |value|
        instance_variable_set :"@#{m}", case value
        when /1|y|on/
          true
        when /0|n|off/
          false
        else
          false
        end
      end
    end

    def uploaded_file=(file)
      @uploaded_file = UploadedFile.new(file)
    end

    def uploaded_file
      @uploaded_file || UploadedFile.new(nil)
    end

    def persisted?
      false
    end
  end
end


text:
FROM golang:1.16
WORKDIR /app/gohttpserver
ADD . /app/gohttpserver
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags '-X main.VERSION=docker' -o gohttpserver

FROM debian:stretch
WORKDIR /app
RUN mkdir -p /app/public
RUN apt-get update && apt-get install -y ca-certificates
VOLUME /app/public
ADD assets ./assets
COPY --from=0 /app/gohttpserver/gohttpserver .
EXPOSE 8000
ENTRYPOINT [ "/app/gohttpserver", "--root=/app/public" ]
CMD []


text:
/**
 * [ description]
 * @param  {[type]} config [description]
 * @return {[type]}        [description]
 */
var ConnectionType = module.exports = function (config) {
	this.config = config;
};

ConnectionType.prototype._connection = null;
ConnectionType.prototype.config = null;

ConnectionType.prototype._connect = function (data) {
	this.connect = function (fn) {
		fn(data);
	};
};

ConnectionType.prototype.connect = function (fn) {
	throw new Error('You must define this method in your own code');
	this._connect = fn;
	return this;
};

ConnectionType.prototype._error = function (data) {
	this.error = function (fn) {
		fn(data);
	};
};

ConnectionType.prototype.error = function (fn) {
	this._error = fn;
	return this;
};

ConnectionType.prototype.getConnection = function () {
	return this._connection;
}


text:
"""Script to compare to resource instances. Prints mismatches to stderr.
Exits with 0 if successful, 1 if there were one or more mismatches, or 2 if there
was another problem
"""

import json
import sys
import os.path

def get_resource_map_and_id_set(inst_list):
    m = {}
    s = set()
    for inst in inst_list:
        iid = inst['id']
        s.add(iid)
        m[iid] = inst
    return (m, s)

def compare_objs(prop, exp, act):
    if type(exp)!=type(act):
        sys.stderr.write("%s: types mismatch (%s and %s)\n" %
                         (prop, type(exp), type(act)))
        return 1
    if isinstance(exp, list):
        if len(exp) != len(act):
            sys.stderr.write("%s: list length mismatch (%d and %d)\n" %
                             (prop, len(exp), len(act)))
            return 1
        else:
            errcnt = 0
            for i in range(0, len(exp)):
                errcnt += compare_objs("%s[%d]" % (prop, i), exp[i], act[i])
            return errcnt
    elif isinstance(exp, dict):
        k_exp = set(exp.keys())
        k_act = set(act.keys())
        if k_exp != k_act:
            sys.stderr.write("%s: Properties differ between expected and actual: %s" %
                             (prop, k_exp.symmetric_difference(k_act).__repr__()))
            return 1
        else:
            errcnt = 0
            for k in exp.keys():
                errcnt += compare_objs("%s.%s" % (prop, k), exp[k], act[k])
            return errcnt
    else:
        if exp != act:
            sys.stderr.write("%s: Values differ (%s and %s)\n" %
                             (prop, exp, act))
            return 1
        else:
            return 0

def compare(exp, act):
    errcnt = 0
    (exp_m, exp_s) = get_resource_map_and_id_set(exp)
    (act_m, act_s) = get_resource_map_and_id_set(act)
    if act_s != exp_s:
        sys.stderr.write("Set of resources does not match. Differences are: %s\n" %
                         exp_s.symmetric_difference(act_s))
        errcnt += 1
    for r in exp:
        assert r.has_key('id'), "Bad exp resource %s" % r.__repr__()
        if act_m.has_key(r['id']):
            errcnt += compare_objs(r['id'], r, act_m[r['id']])

    sys.stdout.write("%d errors found\n" % errcnt)
    return 0 if errcnt==0 else 1

def main(argv=sys.argv[1:]):
    if len(argv)!=2:
        sys.stderr.write("Incorrect number of filenames. Should be:\n%s expected_file actual_file\n" %
                         sys.argv[0])
        return 2
    exp_filename = argv[0]
    act_filename = argv[1]
    if not os.path.exists(exp_filename):
        sys.stderr.write("File %s does not exist\n" % exp_filename)
        return 2
    if not os.path.exists(act_filename):
        sys.stderr.write("File %s does not exist\n" % act_filename)
        return 2
    try:
        with open(exp_filename, "rb") as f:
            exp_data = json.load(f)
        with open(act_filename, "rb") as f:
            act_data = json.load(f)
    except Exception, e:
        sys.stderr.write("%s\n" % str(e))
        return 2

    return compare(exp_data, act_data)

if __name__ == "__main__":
    sys.exit(main())


text:
<?php
/**
 * 4/5 layout category implementation, it extends DDElementTemplate like all other elements
 */
	class TF_GridFourFifth extends DDElementTemplate {

		public function __construct(){

			parent::__construct();
		}

		// Implementation for the element structure.
		public function create_element_structure() {

			// Add name of the class to deserialize it again when the element is sent back to the server from the web page
			$this->config['php_class'] 		= get_class($this);
			// element id
			$this->config['id']	   		= 'grid_four_fifth';
			// element name
			$this->config['name']	 		= '4/5';
			// element icon
			$this->config['icon_url']  		= "icons/four-fifth.png";
			// element icon class
			$this->config['icon_class']		= 'fusion-icon fusion-icon-grid-4-5';
			// css class related to this element
			$this->config['css_class'] 		= "fusion_layout_column grid_four_fifth item-container sort-container ";
			// tooltip that will be displyed upon mouse over the element
			//$this->config['tool_tip']  		= 'Creates a single full (1/1) width column';
			// any special html data attribute (i.e. data-width) needs to be passed
			// width determine the ratio of them element related to its parent element in the editor,
			// it's only important for layout elements.
			// drop_level: elements with higher drop level can be dropped in elements with lower drop_level,
			// i.e. element with drop_level = 2 can be dropped in element with drop_level = 0 or 1 only.
			$this->config['data'] 			= array("floated_width" => "0.8", "width" => "4/5", "drop_level" => "3");
		}

		// override default implemenation for this function as this element doesn't have any content.
		public function create_visual_editor( $params ) {

			$this->config['innerHtml'] = "";
		}

		//this function defines 4/5 sub elements or structure
		function popup_elements() {
			$this->config['layout_opt']  = true;
			$this->config['subElements'] = array(

				array("name" 			=> __('Last Column', 'fusion-core'),
					  "desc" 			=> __('Choose if the column is last in a set. This has to be set to "Yes" for the last column in a set', 'fusion-core'),
					  "id" 				=> "fusion_last",
					  "type" 			=> ElementTypeEnum::SELECT,
					  "value" 			=> "no",
					  "allowedValues" 	=> array('yes' 			=> __('Yes', 'fusion-core'),
												 'no' 			=> __('No', 'fusion-core'),
												 )
					  ),

				array("name" 			=> __('CSS Class', 'fusion-core'),
					  "desc"			=> __('Add a class to the wrapping HTML element.', 'fusion-core'),
					  "id" 				=> "fusion_class",
					  "type" 			=> ElementTypeEnum::INPUT,
					  "value" 			=> ""
					  ),

				array("name" 			=> __('CSS ID', 'fusion-core'),
					  "desc"			=> __('Add an ID to the wrapping HTML element.', 'fusion-core'),
					  "id" 				=> "fusion_id",
					  "type" 			=> ElementTypeEnum::INPUT,
					  "value" 			=> ""
					  ),
				);
		}
	}


text:
package labex.feevale.br.oinc;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.text.DecimalFormat;

import labex.feevale.br.oinc.dao.GoalDao;
import labex.feevale.br.oinc.dao.UserDao;
import labex.feevale.br.oinc.model.Balance;
import labex.feevale.br.oinc.model.Goal;
import labex.feevale.br.oinc.views.actions.ExtraAction;
import labex.feevale.br.oinc.views.actions.LayoutChanges;
import labex.feevale.br.oinc.views.activities.BaseActivity;
import labex.feevale.br.oinc.views.activities.EntryActivity;
import labex.feevale.br.oinc.views.activities.GalleryGoalsActivity;
import labex.feevale.br.oinc.views.custom.CustomToast;
import labex.feevale.br.oinc.views.dialogs.DialogActions;
import labex.feevale.br.oinc.views.dialogs.DialogMaker;
import labex.feevale.br.oinc.views.fragments.MainFragment;
import labex.feevale.br.oinc.views.fragments.NewGoalFragment;
import labex.feevale.br.oinc.views.fragments.RegisterFragment;

public class MainActivity extends BaseActivity implements LayoutChanges {

    private ImageButton galleryButton, homeButton, newEntryButton, buyButton;
    private TextView objectiveTextView, objectiveValueTextView, additionalValueTextView;
    private ImageView objectivesAdd;
    private RelativeLayout footer;
    private LinearLayout header;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        footer = (RelativeLayout) findViewById(R.id.footer);
        header = (LinearLayout) findViewById(R.id.top);
        objectivesAdd = (ImageView)findViewById(R.id.btn_reset);

        homeButton = (ImageButton)findViewById(R.id.goToMain);
        homeButton.setOnClickListener(openMainClickListener());

        galleryButton = (ImageButton)findViewById(R.id.btn_list);
        galleryButton.setOnClickListener(openListGoalClickListener());

        additionalValueTextView = (TextView)findViewById(R.id.additionalValueTextView);
        Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/porkys.regular.ttf");
        additionalValueTextView.setTypeface(typeface);
        additionalValueTextView.setTextColor(getResources().getColor(R.color.orange));
        additionalValueTextView.setRotationY(45);
        additionalValueTextView.setVisibility(View.INVISIBLE);

        newEntryButton = (ImageButton) findViewById(R.id.newEntryButton);
        newEntryButton.setOnClickListener(openNewEntryClickListener());

        objectivesAdd.setOnClickListener(createNewGolClickListener());

        objectiveTextView = (TextView) header.findViewById(R.id.tv_title_objetivo);
        objectiveValueTextView = (TextView) header.findViewById(R.id.tv_value_objetivo);

        buyButton =  (ImageButton) header.findViewById(R.id.buyButton);
        buyButton.setOnClickListener(buyEventClick());

        if(UserDao.getUser() == null){
            changeFragment(new RegisterFragment());
        }else {
            changeFragment(new MainFragment(this));
        }
    }

    private View.OnClickListener buyEventClick() {
        final Activity activity = this;
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DialogMaker("Efetuar compra?",
                        "Legal, você ja tem o valor suficiente para adquirir o que deseja. Vai fazer isso agora?",new DialogActions() {
                    @Override
                    public void cancelAction() { }

                    @Override
                    public void confirmAction() {
                        closeGoal();
                    }
                }).createDialog(activity).show();
            }
        };
    }

    private View.OnClickListener createNewGolClickListener() {
        final Activity activity = this;
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (GoalDao.getUserActiveGoal() != null) {
                    new DialogMaker("Novo Objetivo", "Começar um novo objetivo fará com que o anterior" +
                            "seja desativo. Prosseguir? ", new DialogActions() {
                        @Override
                        public void cancelAction() {}

                        @Override
                        public void confirmAction() {
                            closeGoal();
                        }
                    }).createDialog(activity).show();
                } else {
                    changeFragment(new NewGoalFragment());
                }
            }
        };
    }

    private View.OnClickListener openNewEntryClickListener() {
        final Activity activity = this;
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(GoalDao.getUserActiveGoal() != null) {
                    Intent intent = new Intent(getApplicationContext(), EntryActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }else{
                    CustomToast.show("Você deve ter um objetivo para efetuar um lançamento.", activity, new ExtraAction() {
                        @Override
                        public void execute() {
                            changeFragment(new NewGoalFragment());
                        }
                    });
                }
            }
        };
    }

    private View.OnClickListener openMainClickListener(){
        return new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        };
    }

    private View.OnClickListener openListGoalClickListener(){
        final Activity activity = this;
        return new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(GoalDao.getAllGoals() != null && !GoalDao.getAllGoals().isEmpty()) {
                    Intent intent = new Intent(activity, GalleryGoalsActivity.class);
                    startActivity(intent);
                }else{
                   new DialogMaker("Sem objetivos =/", "Ops! Você não tem nenhum objetivo. Que tal fazer isso agora?",
                           new DialogActions() {
                               @Override
                               public void cancelAction() {}

                               @Override
                               public void confirmAction() {
                                   changeFragment(new NewGoalFragment());
                               }
                           }).createDialog(activity).show();
                }
            }
        };
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {return true;}
        return super.onOptionsItemSelected(item);
    }

    private void showHideBars(){
        if(getFragment() instanceof MainFragment) {
            footer.setVisibility(View.VISIBLE);
            header.setVisibility(View.VISIBLE);
            additionalValueTextView.setVisibility(View.VISIBLE);
            homeButton.setImageResource(R.drawable.btn_door);
        }else{
            footer.setVisibility(View.GONE);
            header.setVisibility(View.GONE);
            additionalValueTextView.setVisibility(View.INVISIBLE);
            homeButton.setImageResource(R.drawable.btn_oinc);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        if(getFragment() instanceof MainFragment || getFragment() instanceof RegisterFragment)
            super.finish();
        else
            changeFragment(new MainFragment(this));
    }

    @Override
    public void changeLayout() {
        Goal goal = GoalDao.getUserActiveGoal();
        this.objectiveTextView.setText(goal != null ? goal.getMeta() : "");

        DecimalFormat df = new DecimalFormat(".00");
        df.setMinimumIntegerDigits(1);
        this.objectiveValueTextView.setText("R$"+ (goal != null ? df.format(goal.getValue()) : "00,00"));
        this.additionalValueTextView.setText("Bônus! +R$"+ (goal != null ? df.format(goal.getTotalValue() - goal.getValue()) : "00,00"));
        if(goal != null && goal.getTotalValue() >= goal.getValue()) {
            this.buyButton.setVisibility(View.VISIBLE);
            this.additionalValueTextView.setVisibility(View.VISIBLE);
        }else {
            this.buyButton.setVisibility(View.INVISIBLE);
            this.additionalValueTextView.setVisibility(View.INVISIBLE);
        }
    }

    private void closeGoal(){
        Goal goal = GoalDao.getUserActiveGoal();
        if (goal != null) {
            goal.setStatus(false);
            goal.save();
            if(goal.getTotalValue() > goal.getValue()){
                Balance balance = Balance.getBalance();
                balance.setBallanceOnAccount(goal.getTotalValue() - goal.getValue());
                balance.save();
            }
        }
        changeFragment(new NewGoalFragment());
    }

    @Override
    public void executeActionChangeFragment() {
        showHideBars();
    }
}


text:
'use strict'

var request = require('superagent')
var GeoJSON = require('geojson')
var fs = require('fs')

var OV_MANIFEST = 'http://s3.amazonaws.com/openvenues-static-public/cities/manifest.json'
var dest = 'data/cities.geojson'

request
  .get(OV_MANIFEST)
  .end(function (err, res) {
    if (err) {
      console.error('Error @ GET request!', err)
      process.exit(1)
    }

    var data = JSON.parse(res.text)
    GeoJSON.parse(data.files, { Point: ['latitude', 'longitude'] }, function (geojson) {
      fs.writeFileSync(dest, JSON.stringify(geojson))
      console.log('OpenVenues city manifest data processed to ' + dest)
    })
  })


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace Steam.Query
{
    public partial class MasterServer
    {
        private const string FIRST_AND_LAST_SERVER = "0.0.0.0:0";
        private const int HEADER_BYTES_LENGTH = 6;
        private readonly IPAddress _steamSteamIpAddress;
        private readonly int _steamSteamPort;

        public MasterServer()
            : this("hl2master.steampowered.com", 27011)
        {
        }

        public MasterServer(string hostname, int steamPort)
        {
            _steamSteamIpAddress = Dns.GetHostEntry(hostname).AddressList[0];
            _steamSteamPort = steamPort;
        }

#if NET45
        public async Task<IEnumerable<Server>> GetServers(
            MasterServerRegion region = MasterServerRegion.All,
            params MasterServerFilter[] masterServerFilters)
        {
            var servers = new List<Server>();

            using (var client = new UdpClient(new IPEndPoint(IPAddress.Any, 0)))
            {
                client.Connect(_steamSteamIpAddress, _steamSteamPort);

                string thisServer = null;
                while (thisServer != FIRST_AND_LAST_SERVER)
                {
                    var requestPacket = CreateRequestPacket(thisServer ?? FIRST_AND_LAST_SERVER, region, masterServerFilters);
                    await client.SendAsync(requestPacket, requestPacket.Length);
                    var response = await client.ReceiveAsync();
                    var responseData = response.Buffer.ToList();
                    for (int i = HEADER_BYTES_LENGTH; i < responseData.Count; i++)
                    {
                        var ip = string.Join(".", responseData.GetRange(i, 4).ToArray());
                        int port = responseData[i + 4] << 8 | responseData[i + 5];
                        thisServer = string.Format("{0}:{1}", ip, port);
                        if (thisServer != FIRST_AND_LAST_SERVER)
                        {
                            servers.Add(new Server(new IPEndPoint(IPAddress.Parse(ip), port)));
                        }
                        i += 5;
                    }
                }
            }

            return servers;
        }

        private static byte[] CreateRequestPacket(string ipAddress, MasterServerRegion region, IEnumerable<MasterServerFilter> filters)
        {
            var buffer = new List<byte> { 0x31, (byte)region };
            buffer.AddRange(System.Text.Encoding.ASCII.GetBytes(ipAddress));
            buffer.Add(0x00);
            var filtersString = string.Join("", filters.Select(x => x.Key + "\\" + x.Value));
            buffer.AddRange(System.Text.Encoding.ASCII.GetBytes(filtersString));
            return buffer.ToArray();
        }
#endif
    }
}


text:
package com.github.dockerjava.cmd.swarm;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.SwarmNode;
import org.junit.Test;

import java.util.Collections;
import java.util.List;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public class ListSwarmNodesCmdExecIT extends SwarmCmdIT {
    @Test
    public void testListSwarmNodes() throws Exception {
        DockerClient dockerClient = startSwarm();

        List<SwarmNode> nodes = dockerClient.listSwarmNodesCmd().exec();
        assertThat(nodes.size(), is(1));
    }

    @Test
    public void testListSwarmNodesWithIdFilter() throws Exception {
        DockerClient dockerClient = startSwarm();

        List<SwarmNode> nodes = dockerClient.listSwarmNodesCmd().exec();
        assertThat(nodes.size(), is(1));

        String nodeId = nodes.get(0).getId();
        List<SwarmNode> nodesWithId = dockerClient.listSwarmNodesCmd()
            .withIdFilter(Collections.singletonList(nodeId))
            .exec();
        assertThat(nodesWithId.size(), is(1));

        List<SwarmNode> nodesWithNonexistentId = dockerClient.listSwarmNodesCmd()
            .withIdFilter(Collections.singletonList("__nonexistent__"))
            .exec();
        assertThat(nodesWithNonexistentId.size(), is(0));
    }

    @Test
    public void testListSwarmNodesWithNameFilter() throws Exception {
        DockerClient dockerClient = startSwarm();

        List<SwarmNode> nodes = dockerClient.listSwarmNodesCmd().exec();
        assertThat(nodes.size(), is(1));

        String nodeName = nodes.get(0).getSpec().getName();
        List<SwarmNode> nodesWithFirstNodesName = dockerClient.listSwarmNodesCmd()
            .withNameFilter(Collections.singletonList(nodeName))
            .exec();
        assertThat(nodesWithFirstNodesName.size(), is(1));

        List<SwarmNode> nodesWithNonexistentName = dockerClient.listSwarmNodesCmd()
            .withNameFilter(Collections.singletonList("__nonexistent__"))
            .exec();
        assertThat(nodesWithNonexistentName.size(), is(0));
    }

    @Test
    public void testListSwarmNodesWithMembershipFilter() throws Exception {
        DockerClient dockerClient = startSwarm();

        List<SwarmNode> nodesWithAcceptedMembership = dockerClient.listSwarmNodesCmd()
            .withMembershipFilter(Collections.singletonList("accepted"))
            .exec();
        assertThat(nodesWithAcceptedMembership.size(), is(1));

        List<SwarmNode> nodesWithPendingMembership = dockerClient.listSwarmNodesCmd()
            .withMembershipFilter(Collections.singletonList("pending"))
            .exec();
        assertThat(nodesWithPendingMembership.size(), is(0));
    }

    @Test
    public void testListSwarmNodesWithRoleFilter() throws Exception {
        DockerClient dockerClient = startSwarm();

        List<SwarmNode> nodesWithManagerRole = dockerClient.listSwarmNodesCmd()
            .withRoleFilter(Collections.singletonList("manager"))
            .exec();
        assertThat(nodesWithManagerRole.size(), is(1));

        List<SwarmNode> nodesWithWorkerRole = dockerClient.listSwarmNodesCmd()
            .withRoleFilter(Collections.singletonList("worker"))
            .exec();
        assertThat(nodesWithWorkerRole.size(), is(0));
    }
}


text:
using Newtonsoft.Json;

namespace Microsoft.VisualStudio.Services.Agent.Worker.Release
{
    public sealed class ReleaseDefinitionToFolderMap
    {
        [JsonProperty("releaseDirectory")]
        public string ReleaseDirectory { get; set; }
    }
}


text:
<?php

namespace Symfony\Bundle\SecurityBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder;

/**
 * Encode a user's password.
 *
 * @author Sarah Khalil <mkhalil.sarah@gmail.com>
 */
class UserPasswordEncoderCommand extends ContainerAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('security:encode-password')
            ->setDescription('Encodes a password.')
            ->addArgument('password', InputArgument::OPTIONAL, 'The plain password to encode.')
            ->addArgument('user-class', InputArgument::OPTIONAL, 'The User entity class path associated with the encoder used to encode the password.', 'Symfony\Component\Security\Core\User\User')
            ->addOption('empty-salt', null, InputOption::VALUE_NONE, 'Do not generate a salt or let the encoder generate one.')
            ->setHelp(<<<EOF

The <info>%command.name%</info> command encodes passwords according to your
security configuration. This command is mainly used to generate passwords for
the <comment>in_memory</comment> user provider type and for changing passwords
in the database while developing the application.

Suppose that you have the following security configuration in your application:

<comment>
# app/config/security.yml
security:
    encoders:
        Symfony\Component\Security\Core\User\User: plaintext
        AppBundle\Entity\User: bcrypt
</comment>

If you execute the command non-interactively, the default Symfony User class
is used and a random salt is generated to encode the password:

  <info>php %command.full_name% --no-interaction [password]</info>

Pass the full user class path as the second argument to encode passwords for
your own entities:

  <info>php %command.full_name% --no-interaction [password] AppBundle\Entity\User</info>

Executing the command interactively allows you to generate a random salt for
encoding the password:

  <info>php %command.full_name% [password] AppBundle\Entity\User</info>

In case your encoder doesn't require a salt, add the <comment>empty-salt</comment> option:

  <info>php %command.full_name% --empty-salt [password] AppBundle\Entity\User</info>

EOF
            )
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output = new SymfonyStyle($input, $output);

        $input->isInteractive() ? $output->title('Symfony Password Encoder Utility') : $output->newLine();

        $password = $input->getArgument('password');
        $userClass = $input->getArgument('user-class');
        $emptySalt = $input->getOption('empty-salt');

        $encoder = $this->getContainer()->get('security.encoder_factory')->getEncoder($userClass);
        $bcryptWithoutEmptySalt = !$emptySalt && $encoder instanceof BCryptPasswordEncoder;

        if ($bcryptWithoutEmptySalt) {
            $emptySalt = true;
        }

        if (!$password) {
            if (!$input->isInteractive()) {
                $output->error('The password must not be empty.');

                return 1;
            }
            $passwordQuestion = $this->createPasswordQuestion($input, $output);
            $password = $output->askQuestion($passwordQuestion);
        }

        $salt = null;

        if ($input->isInteractive() && !$emptySalt) {
            $emptySalt = true;

            $output->note('The command will take care of generating a salt for you. Be aware that some encoders advise to let them generate their own salt. If you\'re using one of those encoders, please answer \'no\' to the question below. '.PHP_EOL.'Provide the \'empty-salt\' option in order to let the encoder handle the generation itself.');

            if ($output->confirm('Confirm salt generation ?')) {
                $salt = $this->generateSalt();
                $emptySalt = false;
            }
        } elseif (!$emptySalt) {
            $salt = $this->generateSalt();
        }

        $encodedPassword = $encoder->encodePassword($password, $salt);

        $rows = array(
            array('Encoder used', get_class($encoder)),
            array('Encoded password', $encodedPassword),
        );
        if (!$emptySalt) {
            $rows[] = array('Generated salt', $salt);
        }
        $output->table(array('Key', 'Value'), $rows);

        if (!$emptySalt) {
            $output->note(sprintf('Make sure that your salt storage field fits the salt length: %s chars', strlen($salt)));
        } elseif ($bcryptWithoutEmptySalt) {
            $output->note('Bcrypt encoder used: the encoder generated its own built-in salt.');
        }

        $output->success('Password encoding succeeded');
    }

    /**
     * Create the password question to ask the user for the password to be encoded.
     *
     * @return Question
     */
    private function createPasswordQuestion()
    {
        $passwordQuestion = new Question('Type in your password to be encoded');

        return $passwordQuestion->setValidator(function ($value) {
            if ('' === trim($value)) {
                throw new \Exception('The password must not be empty.');
            }

            return $value;
        })->setHidden(true)->setMaxAttempts(20);
    }

    private function generateSalt()
    {
        return base64_encode(random_bytes(30));
    }
}


text:
<?php

/**
 * For more information, please contact <graham@goat1000.com>
 */

require_once 'SVGGraphAxis.php';

/**
 * Axis with fixed measurements
 */
class AxisFixed extends Axis {

  protected $step;
  protected $orig_max_value;
  protected $orig_min_value;

  public function __construct($length, $max_val, $min_val, $step,
    $units_before, $units_after, $decimal_digits, $label_callback, $values)
  {
    // min_unit = 1, min_space = 1, fit = false
    parent::__construct($length, $max_val, $min_val, 1, 1, false, $units_before,
      $units_after, $decimal_digits, $label_callback, $values);
    $this->orig_max_value = $max_val;
    $this->orig_min_value = $min_val;
    $this->step = $step;
  }

  /**
   * Calculates a grid based on min, max and step
   * min and max will be adjusted to fit step
   */
  protected function Grid()
  {
    // use the original min/max to prevent compounding of floating-point
    // rounding problems
    $min = $this->orig_min_value;
    $max = $this->orig_max_value;

    // if min and max are the same side of 0, only adjust one of them
    if($max * $min >= 0) {
      $count = $max - $min;
      if(abs($max) >= abs($min)) {
        $this->max_value = $min + $this->step * ceil($count / $this->step);
      } else {
        $this->min_value = $max - $this->step * ceil($count / $this->step);
      }
    } else {
      $this->max_value = $this->step * ceil($max / $this->step);
      $this->min_value = $this->step * floor($min / $this->step);
    }

    $count = ($this->max_value - $this->min_value) / $this->step;
    $ulen = $this->max_value - $this->min_value;
    if($ulen == 0)
      throw new Exception("Zero length axis (min >= max)");
    $this->unit_size = $this->length / $ulen;
    $grid = $this->length / $count;
    $this->zero = (-$this->min_value / $this->step) * $grid;
    return $grid;
  }

  /**
   * Sets the bar style, adding an extra unit
   */
  public function Bar()
  {
    if(!$this->rounded_up) {
      $this->orig_max_value += $this->min_unit;
      parent::Bar();
    }
  }
}


text:
package me.hugmanrique.pokedata.connections;

import lombok.Getter;
import me.hugmanrique.pokedata.Data;
import me.hugmanrique.pokedata.roms.ROM;

/**
 * Missing bulbapedia article
 * @author Hugmanrique
 * @since 01/05/2017
 */
@Getter
public class Connection extends Data {
    private long type;
    private long offset;
    private byte bank;
    private byte map;

    public Connection(ROM rom) {
        type = rom.getPointer(true);
        offset = rom.getSignedLong(true);
        bank = rom.readByte();
        map = rom.readByte();
        rom.addInternalOffset(2);
    }
}


text:
var _ = require('ramda');
const print = console.log;

// 创建容器
var Container = function(x){
    this.__value = x;
}

Container.of = function(x){
    return new Container(x);
}

Container.of(3);
print(Container.of(3));
print(Container.of('hotdogs'));
print(Container.of({ name: 'mozart' }));  //=> Container { __value: { name: 'mozart' } }

// 第一个functor 函子

Container.prototype.map = function(f){
    return Container.of(f(this.__value));
}

Container.of(2).map(function (x) { return x + 2 }); // => Container {__value: 4}

var concat = _.curry(function(a,b){
    return a.concat(b);
})

var l = Container.of('good').map(concat(' morning !')).map(_.prop('length')); // => Container { __value: 14 }
//print(l);

// functor 是实现了 map 函数并遵守一些特定规则的容器类型。

module.exports = {
    Container:Container
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
|	example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
|	https://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
|	$route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
|	$route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
|	$route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples:	my-controller/index	-> my_controller/index
|		my-controller/my-method	-> my_controller/my_method
*/
switch ($_SERVER['HTTP_HOST']) {
    case 'farm.farmeazy.com':
        $route['default_controller'] = "farm";
        $route['404_override'] = '';
        //$route['latest'] = "blog/latest";
        break;
    case 'market.farmeazy.com':
    	$route['default_controller'] = "market/Home";
      $route['login'] = "auth/login";
      $route['join'] = "auth/register";
      $route['dashboard'] = "market/Dashboard";
      $route['dashboard/manage_orders'] = "market/Dashboard/manage_orders";
      $route['dashboard/orders'] = "market/Dashboard/orders";
      $route['dashboard/orders/type/:any'] = "market/Dashboard/orders";
      $route['dashboard/payments/shopping'] = "market/Dashboard/payments";
      $route['dashboard/payments/sales'] = "market/Dashboard/payments";
      $route['dashboard/analytics/shopping'] = "market/Dashboard/analytics";
      $route['dashboard/analytics/sales'] = "market/Dashboard/analytics";
      $route['dashboard/request'] = "market/Dashboard/request";
      $route['dashboard/manage_gigs'] = "market/Dashboard/manage_gigs";
      $route['dashboard/manage_gigs/:any'] = "market/Dashboard/manage_gigs";
      $route['dashboard/manage_gigs/:any/edit'] = "market/Dashboard/manage_gigs";
      $route['dashboard/manage_gigs/:any/publish'] = "market/Dashboard/manage_gigs";
      $route['dashboard/manage_sales/promotion'] = "market/Dashboard/manage_sales";
      $route['dashboard/manage_requests'] = "market/Dashboard/manage_requests";
      $route['dashboard/manage_requests/new'] = "market/Dashboard/manage_requests";
      $route['dashboard/manage_contacts'] = "market/Dashboard/manage_contacts";
      $route['manage_gigs/category_suggestion'] = "market/Manage_gigs/category_suggestion";
      $route['manage_gigs/gig_attributes'] = "market/Manage_gigs/gig_attributes";
      $route['manage_gigs/gig_pricing']= "market/Manage_gigs/gig_pricing";
      $route['conversations'] = "market/Conversations";
      $route['conversations/preview'] = "market/Conversations/preview";
      $route['conversations/preview/:any'] = "market/Conversations/preview";
      $route['conversations/:any'] = "market/Conversations";
      $route['notification_items/preview'] = "market/Notification_items/preview";
      $route['notification_items/preview/:any'] = "market/Notification_items/preview";
      $route['notification_items/:any'] = "market/Notification_items";
      $route['header_data'] = "market/Header_data";
      $route['categories'] = "market/Categories";
      $route['categories/:num/sub_categories'] = "market/Categories/get_sub_categories";
      $route['recommendations'] = "market/Recommendations";
      $route['recommendations/orders_index'] = "market/Recommendations/orders_index";

      /* Automated Routing for User profiles and gigs */
      $route[':any'] = "market/Users_controller";
      //$route['([a-z]+)/(\d+)'] = 'market/Users/$1/id_$2';
      $route[':any/:any'] = "market/Users_controller";
      //$route['404_override'] = 'market/Notfound';
      //$route['([a-zA-z_]+)'] = "market/Users/$1";
    	break;

    case 'library.farmeazy.com':
    	$route['default_controller'] = "library";
      $route['404_override'] = '';
    	break;
    default:
        $route['default_controller'] = "welcome";
        $route['404_override'] = '';
        break;
}
//$route['default_controller'] = 'welcome';
$route['login'] = "auth/login";
$route['join'] = "auth/register";
//$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

//$route['admin'] = "admin/dashboard";


text:
#include "..\defines.h"

namespace star
{
	/// <summary>
	/// A class that is mostly used internally in the engine.
	/// It allows you to get the full static path, of several locations.
	/// It allows you to get the extension and filename of the filepath.
	/// </summary>
	class FilePath final
	{
	public:
		/// <summary>
		/// Default constructor for the filepath,
		/// assigning an EMPTY_STRING value to all datamembers.
		/// </summary>
		FilePath();
		/// <summary>
		/// Constructor overload requiring a string of the full filepath,
		/// starting from the root directory.
		/// </summary>
		/// <param name="full_path">a reference of a FilePath object</param>
		/// <param name="mode">the mode to be used, defining the root directory</param>
		explicit FilePath(const tstring & full_path,
			DirectoryMode mode = DirectoryMode::assets);
		/// <summary>
		/// An overload of the constructor requiring the reference
		/// of an FilePath object where the datamembers will be copped from.
		/// </summary>
		/// <param name="yRef">a reference of a FilePath object</param>
		FilePath(const FilePath & yRef);
		/// <summary>
		/// An overload of the constructor requiring
		/// a FilePath object where the datamembers will be moved from.
		/// </summary>
		/// <param name="yRef">the FilePath object to be moved</param>
		FilePath(FilePath && yRef);
		/// <summary>
		/// Cleans up the path and file tstring datamembers.
		/// </summary>
		~FilePath();

		/// <summary>
		/// Copy the path and file tstring datamembers.
		/// </summary>
		/// <param name="yRef">a reference of a FilePath object</param>
		/// <returns>a reference to the object where
		/// assignment operator get invoked off.</returns>
		FilePath & operator=(const FilePath & yRef);
		/// <summary>
		/// Move the path and file tstring datamembers.
		/// </summary>
		/// <param name="yRef"> a FilePath object to be moved</param>
		/// <returns>a reference to the object where
		/// assignment operator get invoked off.</returns>
		FilePath & operator=(FilePath && yRef);
		/// <summary>
		/// Comparing the path and file tstrings combining it into a boolean result.
		/// </summary>
		/// <param name="yRef">a reference of a FilePath object</param>
		/// <returns>true if the yRef object and the current invoked object are equal</returns>
		bool operator==(const FilePath & yRef);

		/// <summary>
		/// Get the path variable of the filepath.
		/// </summary>
		/// <returns>a const reference to the path datamember.</returns>
		const tstring & GetPath() const;
		/// <summary>
		/// Get the file variable of the filepath.
		/// </summary>
		/// <returns>a const reference to the file datamember.</returns>
		const tstring & GetFile() const;
		/// <summary>
		/// Get the name of the file without the extension part.
		/// </summary>
		/// <returns>the name of the file hidden in the filepath</returns>
		tstring GetName() const;
		/// <summary>
		/// Get the extension of the file hidden in the filepath
		/// </summary>
		/// <returns>the extension of the file</returns>
		tstring GetExtension() const;
		/// <summary>
		/// Get the root of the path, using the correct DirectoryMode.
		/// </summary>
		/// <returns>the root of the path</returns>
		/// <seealso cref="DirectoryMode"></seealso>
		const tstring & GetRoot() const;
		/// <summary>
		/// Get the complete local path which is equal
		/// to a combination of the path and file datamembers.
		/// </summary>
		/// <returns>the complete local path</returns>
		tstring GetLocalPath() const;
		/// <summary>
		/// Get the correct complete dynamic path with the root being used,
		/// defined based on the mode value.
		/// <param name="correct_path">the complete dynamic path, combining the
		/// directory defined by the mode value and the full local path.</param>
		/// </summary>
		/// <seealso cref="DirectoryMode"></seealso>
		void GetFullPath(tstring & correct_path) const;
		/// <summary>
		/// Get the correct complete dynamic path with the root being used,
		/// defined based on the mode value.
		/// </summary>
		/// <returns>the complete dynamic path, combining the
		/// directory defined by the mode value and the full local path.</returns>
		/// <seealso cref="DirectoryMode"></seealso>
		tstring GetFullPath() const;
		/// <summary>
		/// Gets the directory mode.
		/// </summary>
		/// <returns>The directory mode defined in the constructor</returns>
		DirectoryMode GetDirectoryMode() const;

#ifdef DESKTOP
		/// <summary>
		/// Sets the static datamember that represents the assets root directory.
		/// </summary>
		/// <param name="root">the path of the assets directory</param>
		static void SetAssetsRoot(const tstring & root);
		/// <summary>
		/// Sets the static datamember that represents the internal root directory.
		/// </summary>
		/// <param name="root">the path of the internal directory</param>
		static void SetInternalRoot(const tstring & root);
		/// <summary>
		/// Sets the static datamember that represents the external root directory.
		/// </summary>
		/// <param name="root">the path of the external directory</param>
		static void SetExternalRoot(const tstring & root);
#endif

	private:

		tstring m_Path,
				m_File;
#ifdef DESKTOP
		static tstring m_AssetsRoot, m_InternalRoot, m_ExternalRoot;
#else
static const tstring ANDR_INTERNAL_PATH;
static const tstring ANDR_EXTERNAL_PATH;
#endif
		static const tchar PATH_SEPERATOR;
		DirectoryMode m_DirectoryMode;

		/// <summary>
		/// Checks if the path is capital correct.
		/// This check is important for unix based operating system,
		/// as their file system is capital sensitive.
		/// </summary>
		/// <param name="path">The path.</param>
		void CheckIfPathIsCapitalCorrect(const tstring & path);
		/// <summary>
		/// A function to get the static capital-sensitive path
		/// of the current file.
		/// </summary>
		/// <param name="pathIn">the path to be checked</param>
		/// <param name="pathOut">the correct capital-sensitive static path</param>
		/// <returns>True if the file existed, false if the file didnt exist.</returns>
		static bool GetActualPathName(const tstring & pathIn, tstring & pathOut);
		/// <summary>
		/// For windows: Converts all / seperators to \\ seperators.
		/// For android and linux: Converts all \\ seperators to / seperators.
		/// </summary>
		/// <param name="path">The path to convert.</param>
		/// <seealso cref="WIN_PATH_SEPERATOR"/>
		/// <seealso cref="ANDR_PATH_SEPERATOR"/>
		static void ConvertPathToCorrectPlatformStyle(tstring & path);
	};
}


text:
<?php

namespace Anuncios\AnuncioBundle\Controller\Backend;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

/**
 * Backend dashboard controller.
 *
 */
class DashboardController extends Controller
{
    /**
     * Backend dashboard display action.
     */
    public function mainAction()
    {
    	$campaign = $this->getDoctrine()
    		->getRepository('AnunciosAnuncioBundle:Campaign')
    		->getCampaignActive();

    	$closed = false;

    	if(!$campaign)
    	{
    		$campaign = $this->getDoctrine()
    			->getRepository('AnunciosAnuncioBundle:Campaign')
    			->getLastActiveCampaignClosed();

    		$closed = true;
    	}

    	$categories = array();
    	$rankingUsuario = array();
    	$rankingJurado = array();
    	$currentYear = (date('n')=='1')?date('Y')-1:date('Y');
    	$months = array('Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');

    	if($campaign)
    	{
	    	if($campaign->isAnual())
	    	{
	    		$categories = $this->getDoctrine()
	    		->getRepository('AnunciosAnuncioBundle:Category')
	    		->findAll();
	    	}else
	    	{
	    		$categories = $this->getDoctrine()
	    			->getRepository('AnunciosAnuncioBundle:Category')
	    			->getCategoriesWithoutAnual();
	    	}

	    	foreach($categories as $category)
	    	{
	    		$rankingJurado[] = $this->getDoctrine()
	    			->getRepository('AnunciosAnuncioBundle:Anuncio')
	    			->getAnunciosVoteByJurado($campaign, $category);

	    		$rankingUsuario[] = $this->getDoctrine()
	    			->getRepository('AnunciosAnuncioBundle:Anuncio')
	    			->getAnunciosVoteByUsuario($campaign, $category);
	    	}
    	}

    	$votesOnYear = $this->getDoctrine()
    		->getRepository('AnunciosAnuncioBundle:Voting')
    		->votesOnYear($currentYear);

    	/*$finalCampaign = $this->getDoctrine()
    		->getRepository('AnunciosAnuncioBundle:Campaign')
    		->getFinalCampaignOfYear($currentYear);*/

    	$votesPerCampaign = array();
    	$voters = array();
    	foreach ($votesOnYear as $vote)
    	{
    		$campaignId = $vote->getAnuncio()->getCampaign()->getId();
    		$campaignName = $vote->getAnuncio()->getCampaign()->getPeriodName();

    		if(!isset($votesPerCampaign[$campaignId]))
    		{
    			$votesPerCampaign[$campaignId] = array('name' => $campaignName, 'totalVotes' => 0, 'totalVoters' => 0);
    			$voters[$campaignId] = array();
    		}

    		$votesPerCampaign[$campaignId]['totalVotes'] = $votesPerCampaign[$campaignId]['totalVotes']+1;

    		if(!in_array($vote->getUser()->getId(), $voters[$campaignId]))
    		{
    			$voters[$campaignId][] = $vote->getUser()->getId();
	    		$votesPerCampaign[$campaignId]['totalVoters'] = $votesPerCampaign[$campaignId]['totalVoters']+1;
    		}
    	}

    	/*$votesOnFinal = null;
    	if($finalCampaign)
    	{
    		$votesOnFinal = 0;
    		$monthNumber = $finalCampaign->getDateBegin()->format('n');
    		if($monthNumber != 1)
    		{
    			$month = $months[$monthNumber-1];
    			if(isset($votesPerMonth[$month]))
    			{
    				$votesOnFinal = $votesPerMonth[$month];
    				unset($votesPerMonth[$month]);
    			}
    		}

    	}*/

        return $this->render('AnunciosAnuncioBundle:Backend/Dashboard:main.html.twig', array(
        	'campaign'   => $campaign,
			'rankingUsuario' => $rankingUsuario,
			'rankingJurado'  => $rankingJurado,
        	'closed'         => $closed,
        	'currentYear'    => $currentYear,
        	'votesPerCampaign'  => $votesPerCampaign
        ));
    }
}


text:
require 'rails'
module Tbone
  module Devise
    class Engine < Rails::Engine
      initializer "tbone-devise" do |app|
        Tbone.configure do |c|
          c.add_params devise_modules: User.devise_modules
          app.middleware.use Middleware
        end
      end
    end
    class Middleware
      def initialize(app)
        @app = app
      end
      def call(env)
        warden = env['warden']
        return @app.call(env) if env['REQUEST_PATH'] =~ /^\/assets/
        user = warden.authenticate
        m = self
        Tbone.configure do |c|
          c.add_params currentUser: m.render_user(user || User.new)
          c.add_params guestUser: m.render_user(User.new)
        end
        @app.call(env)
      end
      def render_user(user)
        Rabl.render(user, 'users/show', view_path: 'app/views', format: :hash)
      end
    end
  end
end