text:
"""The tests for the USGS Earthquake Hazards Program Feed platform."""
import datetime
from unittest.mock import MagicMock, call, patch

from homeassistant.components import geo_location
from homeassistant.components.geo_location import ATTR_SOURCE
from homeassistant.components.usgs_earthquakes_feed.geo_location import (
    ATTR_ALERT,
    ATTR_EXTERNAL_ID,
    ATTR_MAGNITUDE,
    ATTR_PLACE,
    ATTR_STATUS,
    ATTR_TIME,
    ATTR_TYPE,
    ATTR_UPDATED,
    CONF_FEED_TYPE,
    SCAN_INTERVAL,
)
from homeassistant.const import (
    ATTR_ATTRIBUTION,
    ATTR_FRIENDLY_NAME,
    ATTR_ICON,
    ATTR_LATITUDE,
    ATTR_LONGITUDE,
    ATTR_UNIT_OF_MEASUREMENT,
    CONF_LATITUDE,
    CONF_LONGITUDE,
    CONF_RADIUS,
    EVENT_HOMEASSISTANT_START,
)
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util

from tests.common import assert_setup_component, async_fire_time_changed

CONFIG = {
    geo_location.DOMAIN: [
        {
            "platform": "usgs_earthquakes_feed",
            CONF_FEED_TYPE: "past_hour_m25_earthquakes",
            CONF_RADIUS: 200,
        }
    ]
}

CONFIG_WITH_CUSTOM_LOCATION = {
    geo_location.DOMAIN: [
        {
            "platform": "usgs_earthquakes_feed",
            CONF_FEED_TYPE: "past_hour_m25_earthquakes",
            CONF_RADIUS: 200,
            CONF_LATITUDE: 15.1,
            CONF_LONGITUDE: 25.2,
        }
    ]
}

def _generate_mock_feed_entry(
    external_id,
    title,
    distance_to_home,
    coordinates,
    place=None,
    attribution=None,
    time=None,
    updated=None,
    magnitude=None,
    status=None,
    entry_type=None,
    alert=None,
):
    """Construct a mock feed entry for testing purposes."""
    feed_entry = MagicMock()
    feed_entry.external_id = external_id
    feed_entry.title = title
    feed_entry.distance_to_home = distance_to_home
    feed_entry.coordinates = coordinates
    feed_entry.place = place
    feed_entry.attribution = attribution
    feed_entry.time = time
    feed_entry.updated = updated
    feed_entry.magnitude = magnitude
    feed_entry.status = status
    feed_entry.type = entry_type
    feed_entry.alert = alert
    return feed_entry

async def test_setup(hass):
    """Test the general setup of the platform."""
    # Set up some mock feed entries for this test.
    mock_entry_1 = _generate_mock_feed_entry(
        "1234",
        "Title 1",
        15.5,
        (-31.0, 150.0),
        place="Location 1",
        attribution="Attribution 1",
        time=datetime.datetime(2018, 9, 22, 8, 0, tzinfo=datetime.timezone.utc),
        updated=datetime.datetime(2018, 9, 22, 9, 0, tzinfo=datetime.timezone.utc),
        magnitude=5.7,
        status="Status 1",
        entry_type="Type 1",
        alert="Alert 1",
    )
    mock_entry_2 = _generate_mock_feed_entry("2345", "Title 2", 20.5, (-31.1, 150.1))
    mock_entry_3 = _generate_mock_feed_entry("3456", "Title 3", 25.5, (-31.2, 150.2))
    mock_entry_4 = _generate_mock_feed_entry("4567", "Title 4", 12.5, (-31.3, 150.3))

    # Patching 'utcnow' to gain more control over the timed update.
    utcnow = dt_util.utcnow()
    with patch("homeassistant.util.dt.utcnow", return_value=utcnow), patch(
        "geojson_client.usgs_earthquake_hazards_program_feed."
        "UsgsEarthquakeHazardsProgramFeed"
    ) as mock_feed:
        mock_feed.return_value.update.return_value = (
            "OK",
            [mock_entry_1, mock_entry_2, mock_entry_3],
        )
        with assert_setup_component(1, geo_location.DOMAIN):
            assert await async_setup_component(hass, geo_location.DOMAIN, CONFIG)
            # Artificially trigger update.
            hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
            # Collect events.
            await hass.async_block_till_done()

            all_states = hass.states.async_all()
            assert len(all_states) == 3

            state = hass.states.get("geo_location.title_1")
            assert state is not None
            assert state.name == "Title 1"
            assert state.attributes == {
                ATTR_EXTERNAL_ID: "1234",
                ATTR_LATITUDE: -31.0,
                ATTR_LONGITUDE: 150.0,
                ATTR_FRIENDLY_NAME: "Title 1",
                ATTR_PLACE: "Location 1",
                ATTR_ATTRIBUTION: "Attribution 1",
                ATTR_TIME: datetime.datetime(
                    2018, 9, 22, 8, 0, tzinfo=datetime.timezone.utc
                ),
                ATTR_UPDATED: datetime.datetime(
                    2018, 9, 22, 9, 0, tzinfo=datetime.timezone.utc
                ),
                ATTR_STATUS: "Status 1",
                ATTR_TYPE: "Type 1",
                ATTR_ALERT: "Alert 1",
                ATTR_MAGNITUDE: 5.7,
                ATTR_UNIT_OF_MEASUREMENT: "km",
                ATTR_SOURCE: "usgs_earthquakes_feed",
                ATTR_ICON: "mdi:pulse",
            }
            assert round(abs(float(state.state) - 15.5), 7) == 0

            state = hass.states.get("geo_location.title_2")
            assert state is not None
            assert state.name == "Title 2"
            assert state.attributes == {
                ATTR_EXTERNAL_ID: "2345",
                ATTR_LATITUDE: -31.1,
                ATTR_LONGITUDE: 150.1,
                ATTR_FRIENDLY_NAME: "Title 2",
                ATTR_UNIT_OF_MEASUREMENT: "km",
                ATTR_SOURCE: "usgs_earthquakes_feed",
                ATTR_ICON: "mdi:pulse",
            }
            assert round(abs(float(state.state) - 20.5), 7) == 0

            state = hass.states.get("geo_location.title_3")
            assert state is not None
            assert state.name == "Title 3"
            assert state.attributes == {
                ATTR_EXTERNAL_ID: "3456",
                ATTR_LATITUDE: -31.2,
                ATTR_LONGITUDE: 150.2,
                ATTR_FRIENDLY_NAME: "Title 3",
                ATTR_UNIT_OF_MEASUREMENT: "km",
                ATTR_SOURCE: "usgs_earthquakes_feed",
                ATTR_ICON: "mdi:pulse",
            }
            assert round(abs(float(state.state) - 25.5), 7) == 0

            # Simulate an update - one existing, one new entry,
            # one outdated entry
            mock_feed.return_value.update.return_value = (
                "OK",
                [mock_entry_1, mock_entry_4, mock_entry_3],
            )
            async_fire_time_changed(hass, utcnow + SCAN_INTERVAL)
            await hass.async_block_till_done()

            all_states = hass.states.async_all()
            assert len(all_states) == 3

            # Simulate an update - empty data, but successful update,
            # so no changes to entities.
            mock_feed.return_value.update.return_value = "OK_NO_DATA", None
            async_fire_time_changed(hass, utcnow + 2 * SCAN_INTERVAL)
            await hass.async_block_till_done()

            all_states = hass.states.async_all()
            assert len(all_states) == 3

            # Simulate an update - empty data, removes all entities
            mock_feed.return_value.update.return_value = "ERROR", None
            async_fire_time_changed(hass, utcnow + 3 * SCAN_INTERVAL)
            await hass.async_block_till_done()

            all_states = hass.states.async_all()
            assert len(all_states) == 0

async def test_setup_with_custom_location(hass):
    """Test the setup with a custom location."""
    # Set up some mock feed entries for this test.
    mock_entry_1 = _generate_mock_feed_entry("1234", "Title 1", 20.5, (-31.1, 150.1))

    with patch(
        "geojson_client.usgs_earthquake_hazards_program_feed."
        "UsgsEarthquakeHazardsProgramFeed"
    ) as mock_feed:
        mock_feed.return_value.update.return_value = "OK", [mock_entry_1]

        with assert_setup_component(1, geo_location.DOMAIN):
            assert await async_setup_component(
                hass, geo_location.DOMAIN, CONFIG_WITH_CUSTOM_LOCATION
            )

            # Artificially trigger update.
            hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
            # Collect events.
            await hass.async_block_till_done()

            all_states = hass.states.async_all()
            assert len(all_states) == 1

            assert mock_feed.call_args == call(
                (15.1, 25.2),
                "past_hour_m25_earthquakes",
                filter_minimum_magnitude=0.0,
                filter_radius=200.0,
            )


text:
/* jshint indent:4 */
var REQUEST_EVENTS = ["onBeforeRequest",
                   "onBeforeSendHeaders",
                   "onSendHeaders",
                   "onHeadersReceived",
                   "onAuthRequired",
                   "onBeforeRedirect",
                   "onResponseStarted",
                   "onCompleted",
                   "onErrorOccurred"
                   ];

var OPTS_FILTER_IDENTIFIER = "filter";
var OPTS_EXTRA_INFO_IDENTIFIER = "extraInfo";

var DEFAULT_EXTRA_INFO_OPTS = {};

//init data
(function(){
    "use strict";

    _.each(["onBeforeRequest", "onBeforeSendHeaders", "onHeadersReceived"], function(ev) {
        DEFAULT_EXTRA_INFO_OPTS[ev] = ["blocking"];
    });

    DEFAULT_EXTRA_INFO_OPTS.onAuthRequired = ["asyncBlocking"];

    DEFAULT_EXTRA_INFO_OPTS.onBeforeSendHeaders.push("requestHeaders");
    DEFAULT_EXTRA_INFO_OPTS.onHeadersReceived.push("responseHeaders");

})();

/* exported engine */
var engine = function() {
    "use strict";

    //records callback list
    var gRules;

    //generate rules from localStorage
    var generateRules = function() {

        var cfg = {onBeforeRequest: {}};

        var cancelCfg = new Store("snail-cancel");

        var cancelUrls = _(cancelCfg.records)
                            .chain()
                            .filter(function(id){
                                    return cancelCfg.jsonData(cancelCfg.localStorage()
                                                        .getItem(cancelCfg.name+"-"+id)).enable === true;
                                })
                            .map(function(id){
                                    return cancelCfg.jsonData(cancelCfg.localStorage()
                                                        .getItem(cancelCfg.name+"-"+id)).url;
                                }, this)
                            .compact()
                            .value();

        if (cancelUrls.length>0) {
            cfg.onBeforeRequest.cancel = {_snail_cancel: {urls: cancelUrls}};
        }

        //////////////
        var redirectCfg = new Store("snail-replace");

        var rUrls = _(redirectCfg.records)
                        .chain()
                        .filter(function(id){
                                return redirectCfg.jsonData(redirectCfg.localStorage()
                                                    .getItem(redirectCfg.name+"-"+id)).enable === true;
                            })
                        .map(function(id){
                                var one = redirectCfg.jsonData(redirectCfg.localStorage().getItem(redirectCfg.name+"-"+id));
                                return {src: new RegExp(one.old_url), dest: one.new_url};
                            }, this)
                        .compact()
                        .value();

        if (rUrls.length>0) {
            cfg.onBeforeRequest.redirectUrl = {_snail_replace: {}};

            console.log("rUrls:"+JSON.stringify(rUrls));

            cfg.onBeforeRequest.redirectUrl._snail_replace.replace = rUrls;
        }

        //////////////
        //TODO:
        /*
        var someCfg = new Store("snail-cfg");
        _(redirectCfg.records).chain().each(function(id){
            var one = redirectCfg.jsonData(redirectCfg.localStorage().getItem(redirectCfg.name+"-"+id));
            //console.log("one:"+JSON
        }, this);
        */

        //////////////
        console.log("generateRules:"+JSON.stringify(cfg));

        convertRules(cfg);

    };

    //TODO: RegExp/Date/Function stringify
    //save cfg to localStorage
    var recordCfg = function(config, desc, order) {
        var some = new Store("snail-cfg");
        order = order || (some.records.length + 1);
        some.create({order:order, desc:desc, cfg:JSON.stringify(config)});
    };

    //convert config to options
    var parse = function(config) {

        var cfg = {};

        for(var action in config) {
            if (_.include(["cancel", "redirectUrl"], action)) {
                cfg.onBeforeRequest = cfg.onBeforeRequest || {};
                cfg.onBeforeRequest[action] = config[action];
            }

            if (_.include(REQUEST_EVENTS, action)) {
                cfg[action] = cfg[action] || {};
                _.extend(cfg[action], config[action]);
            }
        }

        convertRules(cfg);
    };

    //get filter option or extraInfo option by eventName
    var getOpt = function(option, eventName, type) {

        //get default extraInfo options
        if (option === void 0 && type === OPTS_EXTRA_INFO_IDENTIFIER) {
            option = DEFAULT_EXTRA_INFO_OPTS[eventName];
        }

        if (option === void 0 && type === OPTS_FILTER_IDENTIFIER) {
            option = {urls:["<all_urls>"]};
        }

        return _.isFunction(option) ? option() : option;
    };

    var handles = {
        cancelHandle: function(details){
            console.log("cancel url:"+details.url);
            return {cancel:true};
        },

        redirectHandle: function(info) {
            var redirects = info;
            if (!_.isArray(info)) {
                redirects = [];
                for(var dest in info) {
                    var obj = {src: info[dest], dest: dest};
                    redirects.push(obj);
                }
            }
            //console.log("redirects:"+JSON.stringify(redirects));

            return function(details) {
                var newUrl = details.url;
                for(var i = 0, j = redirects.length; i<j; ++i) {
                    //console.log("replace rule.  src:"+redirects[i].src + ", dest:"+redirects[i].dest);
                    newUrl = newUrl.replace(redirects[i].src,redirects[i].dest);
                }
                if (newUrl !== details.url) {
                    //console.log("old_url:"+details.url);
                    //console.log("new_url:"+newUrl);
                    return {redirectUrl: newUrl};
                }
            };
        }

    };

    //
    var convertRules = function(options) {

        gRules = gRules || {};
        var handle;

        for(var ev in options) {

            if (!_.include(REQUEST_EVENTS, ev)) {
                continue;
            }

            var option = options[ev];
            gRules[ev] = gRules[ev] || {};

            for(var action in option) {
                var targets = option[action];

                for(var target in targets) {
                    var cmd = targets[target];

                    if (action === "cancel") {
                        handle = cmd.expr || handles.cancelHandle;
                        gRules[ev][action+"."+target] = {   handle:handle,
                                                            filter: (cmd.expr ? cmd.filter : cmd),
                                                            extraInfo: cmd.extraInfo    };
                        continue;
                    }

                    if (action === "redirectUrl") {
                        handle = handles.redirectHandle(cmd.replace);
                        gRules[ev][action+"."+target] = {   handle:handle,
                                                            filter: cmd.filter,
                                                            extraInfo: cmd.extraInfo };
                        continue;
                    }

                    ///default
                    gRules[ev][action+"."+target] = {   handle:cmd.handle,
                                                            filter: cmd.filter,
                                                            extraInfo: cmd.extraInfo };

                }

            }
        }

    };

    var on = function() {

        if (!gRules) {
            return;
        }

        console.log("on:"+JSON.stringify(gRules));

        for(var ev in gRules) {
            var targets = gRules[ev];

            for(var target in targets) {
                var cmd = targets[target];

                console.log("on["+ev+"]-"+target+":"+JSON.stringify(cmd));
                chrome.webRequest[ev].addListener(  cmd.handle,
                                                    getOpt(cmd.filter, ev, OPTS_FILTER_IDENTIFIER),
                                                    getOpt(cmd.extraInfo, ev, OPTS_EXTRA_INFO_IDENTIFIER) );
            }
        }

    };

    var off = function() {

        console.log("off:"+JSON.stringify(gRules));

        if (!gRules) {
            return;
        }

        for(var ev in gRules) {
            var targets = gRules[ev];

            for(var target in targets) {
                var cmd = targets[target];

                console.log("off["+ev+"]-"+target+":"+JSON.stringify(cmd));
                chrome.webRequest[ev].removeListener( cmd.handle );
            }
        }

        //remove old rules
        gRules=null;
    };

    return {
        generateRules: generateRules,
        parse: parse,
        on : on,
        off: off
    };
};

redpajama_set_name: RedPajamaGithub


text:
package coursier.cli.install

import caseapp.{ExtraName => Short, HelpMessage => Help, _}

// format: off
final case class UninstallOptions(

  @Short("dir")
    installDir: Option[String] = None,

  all: Boolean = false,

  @Help("Quiet output")
  @Short("q")
    quiet: Int @@ Counter = Tag.of(0),

  @Help("Increase verbosity (specify several times to increase more)")
  @Short("v")
    verbose: Int @@ Counter = Tag.of(0)

)
// format: on


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from ggplot import *
gg = ggplot(mtcars, aes("wt", "mpg")) + geom_point()
g2 = gg + geom_text(aes(label="name"), data=mtcars[mtcars.cyl == 6])
g2.draw()
#print(g2)


text:
<?php

namespace Gedmo\Timestampable\Mapping\Event\Adapter;

use Gedmo\Mapping\Event\Adapter\ORM as BaseAdapterORM;
use Gedmo\Timestampable\Mapping\Event\TimestampableAdapter;

/**
 * Doctrine event adapter for ORM adapted
 * for Timestampable behavior
 *
 * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
 * @package Gedmo\Timestampable\Mapping\Event\Adapter
 * @subpackage ORM
 * @link http://www.gediminasm.org
 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
final class ORM extends BaseAdapterORM implements TimestampableAdapter
{
    /**
     * {@inheritDoc}
     */
    public function getDateValue($meta, $field)
    {
        if (isset($mapping['type']) && $mapping['type'] == 'zenddate') {
            return new \Zend_Date();
        }
        return new \DateTime();
    }
}


text:
#include <elf.h>
#include <fcntl.h>
#include <limits.h>
#include <link.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/mman.h>

/*
 * Get inline functions for system calls.
 */
static int my_errno;
#define SYS_ERRNO my_errno
#include "third_party/lss/linux_syscall_support.h"

#define MAX_PHNUM               12

typedef uintptr_t __attribute__((may_alias)) stack_val_t;

/*
 * These exact magic argument strings are recognized in check_r_debug_arg
 * and check_reserved_at_zero_arg, below. Requiring the arguments to have
 * those Xs as a template both simplifies our argument matching code and saves
 * us from having to reformat the whole stack to find space for a string longer
 * than the original argument.
 */
#define TEMPLATE_DIGITS "XXXXXXXXXXXXXXXX"
#define R_DEBUG_TEMPLATE_PREFIX "--r_debug=0x"
static const char kRDebugTemplate[] = R_DEBUG_TEMPLATE_PREFIX TEMPLATE_DIGITS;
static const size_t kRDebugPrefixLen = sizeof(R_DEBUG_TEMPLATE_PREFIX) - 1;

#define RESERVED_AT_ZERO_TEMPLATE_PREFIX "--reserved_at_zero=0x"
static const char kReservedAtZeroTemplate[] =
    RESERVED_AT_ZERO_TEMPLATE_PREFIX TEMPLATE_DIGITS;
static const size_t kReservedAtZeroPrefixLen =
    sizeof(RESERVED_AT_ZERO_TEMPLATE_PREFIX) - 1;
extern char RESERVE_TOP[];

extern char TEXT_START[];

/*
 * We're not using <string.h> functions here, to avoid dependencies.
 * In the x86 libc, even "simple" functions like memset and strlen can
 * depend on complex startup code, because in newer libc
 * implementations they are defined using STT_GNU_IFUNC.
 */

/*
 * Some GCC versions are so clever that they recognize these simple loops
 * as having the semantics of standard library functions and replace them
 * with calls.  That defeats the whole purpose, which is to avoid requiring
 * any C library at all.  Fortunately, this optimization can be disabled
 * for all (following) functions in the file via #pragma.
 */
#if (defined(__GNUC__) && !defined(__clang__) && \
     (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
# pragma GCC optimize("-fno-tree-loop-distribute-patterns")
#endif

static void my_bzero(void *buf, size_t n) {
  char *p = buf;
  while (n-- > 0)
    *p++ = 0;
}

static size_t my_strlen(const char *s) {
  size_t n = 0;
  while (*s++ != '\0')
    ++n;
  return n;
}

static int my_strcmp(const char *a, const char *b) {
  while (*a == *b) {
    if (*a == '\0')
      return 0;
    ++a;
    ++b;
  }
  return (int) (unsigned char) *a - (int) (unsigned char) *b;
}

/*
 * We're avoiding libc, so no printf.  The only nontrivial thing we need
 * is rendering numbers, which is, in fact, pretty trivial.
 * bufsz of course must be enough to hold INT_MIN in decimal.
 */
static void iov_int_string(int value, struct kernel_iovec *iov,
                           char *buf, size_t bufsz) {
  char *p = &buf[bufsz];
  int negative = value < 0;
  if (negative)
    value = -value;
  do {
    --p;
    *p = "0123456789"[value % 10];
    value /= 10;
  } while (value != 0);
  if (negative)
    *--p = '-';
  iov->iov_base = p;
  iov->iov_len = &buf[bufsz] - p;
}

#define STRING_IOV(string_constant, cond) \
  { (void *) string_constant, cond ? (sizeof(string_constant) - 1) : 0 }

__attribute__((noreturn)) static void fail(const char *filename,
                                           const char *message,
                                           const char *item1, int value1,
                                           const char *item2, int value2) {
  char valbuf1[32];
  char valbuf2[32];
  struct kernel_iovec iov[] = {
    STRING_IOV("bootstrap_helper: ", 1),
    { (void *) filename, my_strlen(filename) },
    STRING_IOV(": ", 1),
    { (void *) message, my_strlen(message) },
    { (void *) item1, item1 == NULL ? 0 : my_strlen(item1) },
    STRING_IOV("=", item1 != NULL),
    { NULL, 0 },                        /* iov[6] */
    STRING_IOV(", ", item1 != NULL && item2 != NULL),
    { (void *) item2, item2 == NULL ? 0 : my_strlen(item2) },
    STRING_IOV("=", item2 != NULL),
    { NULL, 0 },                        /* iov[10] */
    { "\n", 1 },
  };
  const int niov = sizeof(iov) / sizeof(iov[0]);

  if (item1 != NULL)
    iov_int_string(value1, &iov[6], valbuf1, sizeof(valbuf1));
  if (item2 != NULL)
    iov_int_string(value2, &iov[10], valbuf2, sizeof(valbuf2));

  sys_writev(2, iov, niov);
  sys_exit_group(2);
  while (1) *(volatile int *) 0 = 0;  /* Crash.  */
}

static int my_open(const char *file, int oflag) {
  int result = sys_open(file, oflag, 0);
  if (result < 0)
    fail(file, "Cannot open ELF file!  ", "errno", my_errno, NULL, 0);
  return result;
}

static void my_pread(const char *file, const char *fail_message,
                     int fd, void *buf, size_t bufsz, uintptr_t pos) {
  ssize_t result = sys_pread64(fd, buf, bufsz, pos);
  if (result < 0)
    fail(file, fail_message, "errno", my_errno, NULL, 0);
  if ((size_t) result != bufsz)
    fail(file, fail_message, "read count", result, NULL, 0);
}

static uintptr_t my_mmap_simple(uintptr_t address, size_t size,
                                int prot, int flags, int fd, uintptr_t pos) {
#if defined(__NR_mmap2)
  void *result = sys_mmap2((void *) address, size, prot, flags, fd, pos >> 12);
#else
  void *result = sys_mmap((void *) address, size, prot, flags, fd, pos);
#endif
  return (uintptr_t) result;
}

static uintptr_t my_mmap(const char *file,
                         const char *segment_type, unsigned int segnum,
                         uintptr_t address, size_t size,
                         int prot, int flags, int fd, uintptr_t pos) {
  uintptr_t result = my_mmap_simple(address, size, prot, flags, fd, pos);
  if ((void *) result == MAP_FAILED)
    fail(file, "Failed to map segment!  ",
         segment_type, segnum, "errno", my_errno);
  return result;
}

static void my_mprotect(const char *file, unsigned int segnum,
                        uintptr_t address, size_t size, int prot) {
  if (sys_mprotect((void *) address, size, prot) < 0)
    fail(file, "Failed to mprotect segment hole!  ",
         "segment", segnum, "errno", my_errno);
}

static int prot_from_phdr(const ElfW(Phdr) *phdr) {
  int prot = 0;
  if (phdr->p_flags & PF_R)
    prot |= PROT_READ;
  if (phdr->p_flags & PF_W)
    prot |= PROT_WRITE;
  if (phdr->p_flags & PF_X)
    prot |= PROT_EXEC;
  return prot;
}

static uintptr_t round_up(uintptr_t value, uintptr_t size) {
  return (value + size - 1) & -size;
}

static uintptr_t round_down(uintptr_t value, uintptr_t size) {
  return value & -size;
}

/*
 * Handle the "bss" portion of a segment, where the memory size
 * exceeds the file size and we zero-fill the difference.  For any
 * whole pages in this region, we over-map anonymous pages.  For the
 * sub-page remainder, we zero-fill bytes directly.
 */
static void handle_bss(const char *file,
                       unsigned int segnum, const ElfW(Phdr) *ph,
                       ElfW(Addr) load_bias, size_t pagesize) {
  if (ph->p_memsz > ph->p_filesz) {
    ElfW(Addr) file_end = ph->p_vaddr + load_bias + ph->p_filesz;
    ElfW(Addr) file_page_end = round_up(file_end, pagesize);
    ElfW(Addr) page_end = round_up(ph->p_vaddr + load_bias +
                                   ph->p_memsz, pagesize);
    if (page_end > file_page_end)
      my_mmap(file, "bss segment", segnum,
              file_page_end, page_end - file_page_end,
              prot_from_phdr(ph), MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0);
    if (file_page_end > file_end && (ph->p_flags & PF_W))
      my_bzero((void *) file_end, file_page_end - file_end);
  }
}

/*
 * Open an ELF file and load it into memory.
 */
static ElfW(Addr) load_elf_file(const char *filename,
                                size_t pagesize,
                                ElfW(Addr) *out_phdr,
                                ElfW(Addr) *out_phnum,
                                const char **out_interp) {
  int fd = my_open(filename, O_RDONLY);

  ElfW(Ehdr) ehdr;
  my_pread(filename, "Failed to read ELF header from file!  ",
           fd, &ehdr, sizeof(ehdr), 0);

  if (ehdr.e_ident[EI_MAG0] != ELFMAG0 ||
      ehdr.e_ident[EI_MAG1] != ELFMAG1 ||
      ehdr.e_ident[EI_MAG2] != ELFMAG2 ||
      ehdr.e_ident[EI_MAG3] != ELFMAG3 ||
      ehdr.e_version != EV_CURRENT ||
      ehdr.e_ehsize != sizeof(ehdr) ||
      ehdr.e_phentsize != sizeof(ElfW(Phdr)))
    fail(filename, "File has no valid ELF header!", NULL, 0, NULL, 0);

  switch (ehdr.e_machine) {
#if defined(__i386__)
    case EM_386:
#elif defined(__x86_64__)
    case EM_X86_64:
#elif defined(__arm__)
    case EM_ARM:
#elif defined(__mips__)
    case EM_MIPS:
#else
# error "Don't know the e_machine value for this architecture!"
#endif
      break;
    default:
      fail(filename, "ELF file has wrong architecture!  ",
           "e_machine", ehdr.e_machine, NULL, 0);
      break;
  }

  ElfW(Phdr) phdr[MAX_PHNUM];
  if (ehdr.e_phnum > sizeof(phdr) / sizeof(phdr[0]) || ehdr.e_phnum < 1)
    fail(filename, "ELF file has unreasonable ",
         "e_phnum", ehdr.e_phnum, NULL, 0);

  if (ehdr.e_type != ET_DYN)
    fail(filename, "ELF file not ET_DYN!  ",
         "e_type", ehdr.e_type, NULL, 0);

  my_pread(filename, "Failed to read program headers from ELF file!  ",
           fd, phdr, sizeof(phdr[0]) * ehdr.e_phnum, ehdr.e_phoff);

  size_t i = 0;
  while (i < ehdr.e_phnum && phdr[i].p_type != PT_LOAD)
    ++i;
  if (i == ehdr.e_phnum)
    fail(filename, "ELF file has no PT_LOAD header!",
         NULL, 0, NULL, 0);

  /*
   * ELF requires that PT_LOAD segments be in ascending order of p_vaddr.
   * Find the last one to calculate the whole address span of the image.
   */
  const ElfW(Phdr) *first_load = &phdr[i];
  const ElfW(Phdr) *last_load = &phdr[ehdr.e_phnum - 1];
  while (last_load > first_load && last_load->p_type != PT_LOAD)
    --last_load;

  size_t span = last_load->p_vaddr + last_load->p_memsz - first_load->p_vaddr;

  /*
   * Map the first segment and reserve the space used for the rest and
   * for holes between segments.
   */
  const uintptr_t mapping = my_mmap(filename, "segment", first_load - phdr,
                                    round_down(first_load->p_vaddr, pagesize),
                                    span, prot_from_phdr(first_load),
                                    MAP_PRIVATE, fd,
                                    round_down(first_load->p_offset, pagesize));

  const ElfW(Addr) load_bias = mapping - round_down(first_load->p_vaddr,
                                                    pagesize);

  if (first_load->p_offset > ehdr.e_phoff ||
      first_load->p_filesz < ehdr.e_phoff + (ehdr.e_phnum * sizeof(ElfW(Phdr))))
    fail(filename, "First load segment of ELF file does not contain phdrs!",
         NULL, 0, NULL, 0);

  handle_bss(filename, first_load - phdr, first_load, load_bias, pagesize);

  ElfW(Addr) last_end = first_load->p_vaddr + load_bias + first_load->p_memsz;

  /*
   * Map the remaining segments, and protect any holes between them.
   */
  const ElfW(Phdr) *ph;
  for (ph = first_load + 1; ph <= last_load; ++ph) {
    if (ph->p_type == PT_LOAD) {
      ElfW(Addr) last_page_end = round_up(last_end, pagesize);

      last_end = ph->p_vaddr + load_bias + ph->p_memsz;
      ElfW(Addr) start = round_down(ph->p_vaddr + load_bias, pagesize);
      ElfW(Addr) end = round_up(last_end, pagesize);

      if (start > last_page_end)
        my_mprotect(filename,
                    ph - phdr, last_page_end, start - last_page_end, PROT_NONE);

      my_mmap(filename, "segment", ph - phdr,
              start, end - start,
              prot_from_phdr(ph), MAP_PRIVATE | MAP_FIXED, fd,
              round_down(ph->p_offset, pagesize));

      handle_bss(filename, ph - phdr, ph, load_bias, pagesize);
    }
  }

  if (out_interp != NULL) {
    /*
     * Find the PT_INTERP header, if there is one.
     */
    for (i = 0; i < ehdr.e_phnum; ++i) {
      if (phdr[i].p_type == PT_INTERP) {
        /*
         * The PT_INTERP isn't really required to sit inside the first
         * (or any) load segment, though it normally does.  So we can
         * easily avoid an extra read in that case.
         */
        if (phdr[i].p_offset >= first_load->p_offset &&
            phdr[i].p_filesz <= first_load->p_filesz) {
          *out_interp = (const char *) (phdr[i].p_vaddr + load_bias);
        } else {
          static char interp_buffer[PATH_MAX + 1];
          if (phdr[i].p_filesz >= sizeof(interp_buffer)) {
            fail(filename, "ELF file has unreasonable PT_INTERP size!  ",
                 "segment", i, "p_filesz", phdr[i].p_filesz);
          }
          my_pread(filename, "Cannot read PT_INTERP segment contents!",
                   fd, interp_buffer, phdr[i].p_filesz, phdr[i].p_offset);
          *out_interp = interp_buffer;
        }
        break;
      }
    }
  }

  sys_close(fd);

  if (out_phdr != NULL)
    *out_phdr = (ehdr.e_phoff - first_load->p_offset +
                 first_load->p_vaddr + load_bias);
  if (out_phnum != NULL)
    *out_phnum = ehdr.e_phnum;

  return ehdr.e_entry + load_bias;
}

/*
 * Replace template digits with a fill value.  This function places the
 * bottom num_digits of the hex representation of fill into the string
 * pointed to by start.
 */
static void fill_in_template_digits(char *start, size_t num_digits,
                                    uintptr_t fill) {
  while (num_digits-- > 0) {
    start[num_digits] = "0123456789abcdef"[fill & 0xf];
    fill >>= 4;
  }
  if (fill != 0)
    fail("fill_in_template_digits",
         "fill has significant digits beyond num_digits", NULL, 0, NULL, 0);
}

/*
 * GDB looks for this symbol name when it cannot find PT_DYNAMIC->DT_DEBUG.
 * We don't have a PT_DYNAMIC, so it will find this.  Now all we have to do
 * is arrange for this space to be filled in with the dynamic linker's
 * _r_debug contents after they're initialized.  That way, attaching GDB to
 * this process or examining its core file will find the PIE we loaded, the
 * dynamic linker, and all the shared libraries, making debugging pleasant.
 */
struct r_debug _r_debug __attribute__((nocommon, section(".r_debug")));

/*
 * If the argument matches the kRDebugTemplate string, then replace
 * the 16 Xs with the hexadecimal address of our _r_debug variable.
 */
static int check_r_debug_arg(char *arg) {
  if (my_strcmp(arg, kRDebugTemplate) == 0) {
    fill_in_template_digits(arg + kRDebugPrefixLen,
                            sizeof(TEMPLATE_DIGITS) - 1,
                            (uintptr_t) &_r_debug);
    return 1;
  }
  return 0;
}

/*
 * If the argument matches the kReservedAtZeroTemplate string, then replace
 * the 8 Xs with the hexadecimal representation of the amount of
 * prereserved memory.
 */
static int check_reserved_at_zero_arg(char *arg) {
  if (my_strcmp(arg, kReservedAtZeroTemplate) == 0) {
    fill_in_template_digits(arg + kReservedAtZeroPrefixLen,
                            sizeof(TEMPLATE_DIGITS) - 1,
                            (uintptr_t) RESERVE_TOP);
    return 1;
  }
  return 0;
}

static void ReserveBottomPages(size_t pagesize) {
  uintptr_t page_addr;
  uintptr_t mmap_rval;

  /*
   * Attempt to protect low memory from zero to the code start address.
   *
   * It is normal for mmap() calls to fail with EPERM if the indicated
   * page is less than vm.mmap_min_addr (see /proc/sys/vm/mmap_min_addr),
   * or with EACCES under SELinux if less than CONFIG_LSM_MMAP_MIN_ADDR
   * (64k).  Sometimes, mmap() calls may fail with EINVAL if the
   * starting address is 0.  Hence, we adaptively move the bottom of the
   * region up a page at a time until we succeed in getting a reservation.
   */
  for (page_addr = 0;
       page_addr < (uintptr_t) TEXT_START;
       page_addr += pagesize) {
    mmap_rval = my_mmap_simple(page_addr,
                               (uintptr_t) TEXT_START - page_addr,
                               PROT_NONE,
                               MAP_PRIVATE | MAP_FIXED |
                               MAP_ANONYMOUS | MAP_NORESERVE,
                               -1, 0);
    if (page_addr == mmap_rval) {
      /* Success; the pages are now protected. */
      break;
    } else if (MAP_FAILED == (void *) mmap_rval &&
               (EPERM == my_errno || EACCES == my_errno ||
                (EINVAL == my_errno && 0 == page_addr))) {
      /*
       * Normal; this is an invalid page for this process and
       * doesn't need to be protected. Continue with next page.
       */
    } else {
      fail("ReserveBottomPages", "NULL pointer guard page ",
           "errno", my_errno, NULL, 0);
    }
  }
}

/*
 * This is the main loading code.  It's called with the starting stack pointer.
 * This points to a sequence of pointer-size words:
 *      [0]             argc
 *      [1..argc]       argv[0..argc-1]
 *      [1+argc]        NULL
 *      [2+argc..]      envp[0..]
 *                      NULL
 *                      auxv[0].a_type
 *                      auxv[1].a_un.a_val
 *                      ...
 * It returns the dynamic linker's runtime entry point address, where
 * we should jump to.  This is called by the machine-dependent _start
 * code (below).  On return, it restores the original stack pointer
 * and jumps to this entry point.
 *
 * argv[0] is the uninteresting name of this bootstrap program.  argv[1] is
 * the real program file name we'll open, and also the argv[0] for that
 * program.  We need to modify argc, move argv[1..] back to the argv[0..]
 * position, and also examine and modify the auxiliary vector on the stack.
 */
ElfW(Addr) do_load(stack_val_t *stack) {
  size_t i;
  int argn;

  /*
   * First find the end of the auxiliary vector.
   */
  int argc = stack[0];
  char **argv = (char **) &stack[1];
  const char *program = argv[1];
  char **envp = &argv[argc + 1];
  char **ep = envp;
  while (*ep != NULL)
    ++ep;
  ElfW(auxv_t) *auxv = (ElfW(auxv_t) *) (ep + 1);
  ElfW(auxv_t) *av = auxv;
  while (av->a_type != AT_NULL)
    ++av;
  size_t stack_words = (stack_val_t *) (av + 1) - &stack[1];

  if (argc < 2)
    fail("Usage", "PROGRAM ARGS...", NULL, 0, NULL, 0);

  /*
   * Now move everything back to eat our original argv[0].  When we've done
   * that, envp and auxv will start one word back from where they were.
   */
  --argc;
  --envp;
  auxv = (ElfW(auxv_t) *) ep;
  stack[0] = argc;
  for (i = 1; i < stack_words; ++i)
    stack[i] = stack[i + 1];

  /*
   * If an argument is the kRDebugTemplate or kReservedAtZeroTemplate
   * string, then we'll modify that argument string in place to specify
   * the address of our _r_debug structure (for kRDebugTemplate) or the
   * amount of prereserved address space (for kReservedAtZeroTemplate).
   * We expect that the arguments matching the templates are the first
   * arguments provided.
   */
  for (argn = 1; argn < argc; ++argn) {
    if (!check_r_debug_arg(argv[argn]) &&
        !check_reserved_at_zero_arg(argv[argn]))
     break;
  }

  /*
   * Record the auxv entries that are specific to the file loaded.
   * The incoming entries point to our own static executable.
   */
  ElfW(auxv_t) *av_entry = NULL;
  ElfW(auxv_t) *av_phdr = NULL;
  ElfW(auxv_t) *av_phnum = NULL;
  size_t pagesize = 0;

  for (av = auxv;
       av_entry == NULL || av_phdr == NULL || av_phnum == NULL || pagesize == 0;
       ++av) {
    switch (av->a_type) {
      case AT_NULL:
        fail("startup",
             "Failed to find AT_ENTRY, AT_PHDR, AT_PHNUM, or AT_PAGESZ!",
             NULL, 0, NULL, 0);
        /*NOTREACHED*/
        break;
      case AT_ENTRY:
        av_entry = av;
        break;
      case AT_PAGESZ:
        pagesize = av->a_un.a_val;
        break;
      case AT_PHDR:
        av_phdr = av;
        break;
      case AT_PHNUM:
        av_phnum = av;
        break;
    }
  }

  ReserveBottomPages(pagesize);

  /* Load the program and point the auxv elements at its phdrs and entry.  */
  const char *interp = NULL;
  av_entry->a_un.a_val = load_elf_file(program,
                                       pagesize,
                                       &av_phdr->a_un.a_val,
                                       &av_phnum->a_un.a_val,
                                       &interp);

  ElfW(Addr) entry = av_entry->a_un.a_val;

  if (interp != NULL) {
    /*
     * There was a PT_INTERP, so we have a dynamic linker to load.
     */
    entry = load_elf_file(interp, pagesize, NULL, NULL, NULL);
  }

  return entry;
}

/*
 * We have to define the actual entry point code (_start) in assembly for
 * each machine.  The kernel startup protocol is not compatible with the
 * normal C function calling convention.  Here, we call do_load (above)
 * using the normal C convention as per the ABI, with the starting stack
 * pointer as its argument; restore the original starting stack; and
 * finally, jump to the dynamic linker's entry point address.
 */
#if defined(__i386__)
asm(".pushsection \".text\",\"ax\",@progbits\n"
    ".globl _start\n"
    ".type _start,@function\n"
    "_start:\n"
    "xorl %ebp, %ebp\n"
    "movl %esp, %ebx\n"         /* Save starting SP in %ebx.  */
    "andl $-16, %esp\n"         /* Align the stack as per ABI.  */
    "pushl %ebx\n"              /* Argument: stack block.  */
    "call do_load\n"
    "movl %ebx, %esp\n"         /* Restore the saved SP.  */
    "jmp *%eax\n"               /* Jump to the entry point.  */
    ".popsection"
    );
#elif defined(__x86_64__)
asm(".pushsection \".text\",\"ax\",@progbits\n"
    ".globl _start\n"
    ".type _start,@function\n"
    "_start:\n"
    "xorq %rbp, %rbp\n"
    "movq %rsp, %rbx\n"         /* Save starting SP in %rbx.  */
    "andq $-16, %rsp\n"         /* Align the stack as per ABI.  */
    "movq %rbx, %rdi\n"         /* Argument: stack block.  */
    "call do_load\n"
    "movq %rbx, %rsp\n"         /* Restore the saved SP.  */
    "jmp *%rax\n"               /* Jump to the entry point.  */
    ".popsection"
    );
#elif defined(__arm__)
asm(".pushsection \".text\",\"ax\",%progbits\n"
    ".globl _start\n"
    ".type _start,#function\n"
    "_start:\n"
#if defined(__thumb2__)
    ".thumb\n"
    ".syntax unified\n"
#endif
    "mov fp, #0\n"
    "mov lr, #0\n"
    "mov r4, sp\n"              /* Save starting SP in r4.  */
    "mov r0, sp\n"              /* Argument: stack block.  */
    "bl do_load\n"
    "mov sp, r4\n"              /* Restore the saved SP.  */
    "blx r0\n"                  /* Jump to the entry point.  */
    ".popsection"
    );
#elif defined(__mips__)
asm(".pushsection \".text\",\"ax\",@progbits\n"
    ".globl _start\n"
    ".type _start,@function\n"
    "_start:\n"
    ".set noreorder\n"
    "addiu $fp, $zero, 0\n"
    "addiu $ra, $zero, 0\n"
    "addiu $s8, $sp,   0\n"     /* Save starting SP in s8.  */
    "addiu $a0, $sp,   0\n"
    "addiu $sp, $sp, -16\n"
    "jal   do_load\n"
    "nop\n"
    "addiu $sp, $s8,  0\n"      /* Restore the saved SP.  */
    "jr    $v0\n"               /* Jump to the entry point.  */
    "nop\n"
    ".popsection"
    );
#else
# error "Need stack-preserving _start code for this architecture!"
#endif

#if defined(__arm__)
/*
 * We may bring in __aeabi_* functions from libgcc that in turn
 * want to call raise.
 */
int raise(int sig) {
  return sys_kill(sys_getpid(), sig);
}
#endif


text:
<?php
/* @var $this UserController */
/* @var $model User */
/* @var $form CActiveForm */
?>

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'user-form',
	// Please note: When you enable ajax validation, make sure the corresponding
	// controller action is handling ajax validation correctly.
	// There is a call to performAjaxValidation() commented in generated controller code.
	// See class documentation of CActiveForm for details on this.
	'enableAjaxValidation'=>false,
)); ?>

Fields with * are required.

	<?php echo $form->errorSummary($model); ?>

		<?php echo $form->labelEx($model,'login'); ?>
		<?php echo $form->textField($model,'login',array('size'=>50,'maxlength'=>50)); ?>
		<?php echo $form->error($model,'login'); ?>

		<?php echo $form->labelEx($model,'email'); ?>
		<?php echo $form->textField($model,'email',array('size'=>50,'maxlength'=>50)); ?>
		<?php echo $form->error($model,'email'); ?>

		<?php echo $form->labelEx($model,'pass'); ?>
		<?php echo $form->passwordField($model,'pass',array('size'=>25,'maxlength'=>25)); ?>
		<?php echo $form->error($model,'pass'); ?>

		<?php echo $form->labelEx($model,'status'); ?>
		<?php echo $form->textField($model,'status',array('size'=>15,'maxlength'=>15)); ?>
		<?php echo $form->error($model,'status'); ?>

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

<?php $this->endWidget(); ?>


text:
package com.epishie.tabs.feature.shared.model;

public class ImageData {
    int width;
    int height;
    String url;

    public String getUrl() {
        return url;
    }
}


text:
import { OnDestroy, ApplicationRef } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { Subject } from 'rxjs/Subject';
import { ToastConfig, ToastData } from './toastrConfig';
import { ToastrService } from './toastrService';
import { ToastRef } from './toastInjector';
export declare class Toast implements OnDestroy {
    protected toastrService: ToastrService;
    data: ToastData;
    protected toastRef: ToastRef<any>;
    protected appRef: ApplicationRef;
    protected sanitizer: DomSanitizer;
    toastId: number;
    message: string | SafeHtml;
    title: string;
    options: ToastConfig;
    width: number;
    toastClasses: string;
    state: string;
    private timeout;
    private intervalId;
    private hideTime;
    private sub;
    private sub1;
    onTap: Subject<any>;
    onAction: Subject<any>;
    constructor(toastrService: ToastrService, data: ToastData, toastRef: ToastRef<any>, appRef: ApplicationRef, sanitizer: DomSanitizer);
    ngOnDestroy(): void;
    activateToast(): void;
    updateProgress(): void;
    remove(): void;
    tapToast(): void;
    stickAround(): void;
    delayedHideToast(): void;
}


text:
class CreateCompanies < ActiveRecord::Migration
  def change
    create_table :companies do |t|
      t.string :industry
      t.string :name
      t.text :description
      t.string :location
      t.string :size
      t.string :ctype

      t.timestamps
    end
  end
end


text:
#include <iostream>
#include <sstream>

#include "rpc/RpcAuth.h"
#include "common/XmlConfig.h"
#include "common/SessionConfig.h"
#include "Exception.h"
#include "ExceptionInternal.h"
#include "ApplicationClient.h"
#include "StringUtil.h"

namespace libyarn {

RMInfo::RMInfo() {
}

const char * YARN_RESOURCEMANAGER_HA = "yarn.resourcemanager.ha";

std::vector<RMInfo> RMInfo::getHARMInfo(const Yarn::Config & conf, const char* name) {
    std::vector<RMInfo> retval;
    /*
    * Read config and create a vector of RM address.
    */
    try{
        std::string strHA = StringTrim(conf.getString(std::string(name)));
        std::vector<std::string> strRMs = StringSplit(strHA, ",");
        retval.resize(strRMs.size());
        for (size_t i = 0; i < strRMs.size(); ++i) {
            std::vector<std::string> rm = StringSplit(strRMs[i], ":");
            retval[i].setHost(rm[0]);
            retval[i].setPort(rm[1]);
        }
    } catch (const Yarn::YarnConfigNotFound &e) {
        LOG(DEBUG1, "Yarn RM HA is not configured.");
    }

    return retval;
}

ApplicationClient::ApplicationClient(string &user, string &host, string &port) {
    std::vector<RMInfo> rmConfInfos, rmInfos;
    RMInfo activeRM;
    std::string tokenService = "";

    Yarn::Internal::shared_ptr<Yarn::Config> conf = DefaultConfig().getConfig();
    Yarn::Internal::SessionConfig sessionConfig(*conf);
    RootLogger.setLogSeverity(sessionConfig.getLogSeverity());
    LOG(INFO, "ApplicationClient session auth method : %s",
            sessionConfig.getRpcAuthMethod().c_str());

    activeRM.setHost(host);
    activeRM.setPort(port);
    rmInfos.push_back(activeRM);
    rmConfInfos = RMInfo::getHARMInfo(*conf, YARN_RESOURCEMANAGER_HA);

    /* build a list of candidate RMs without duplicate */
    for (std::vector<RMInfo>::iterator it = rmConfInfos.begin();
            it != rmConfInfos.end(); it++) {
        bool found = false;
        for (std::vector<RMInfo>::iterator it2 = rmInfos.begin();
                it2 != rmInfos.end(); it2++) {
            if (it2->getHost() == it->getHost()
                    && it2->getPort() == it->getPort()) {
                found = true;
                break;
            }
        }
        if (!found)
            rmInfos.push_back(*it);
    }

    if (rmInfos.size() <= 1) {
        LOG(INFO, "ApplicationClient Resource Manager HA is disable.");
        enableRMHA = false;
        maxRMHARetry = 0;
    } else {
        LOG(INFO,
                "ApplicationClient Resource Manager HA is enable. Number of RM: %d",
                rmInfos.size());
        enableRMHA = true;
        maxRMHARetry = sessionConfig.getRpcMaxHaRetry();
    }

    if (!enableRMHA)
    {
        appClientProtos.push_back(
            std::shared_ptr<ApplicationClientProtocol>(
                new ApplicationClientProtocol(user, host, port, tokenService, sessionConfig)));
    } else {
        /*
        * iterate RMInfo vector and create 1-1 applicationClientProtocol for each standby RM
        */
        for (size_t i = 0; i < rmInfos.size(); ++i) {
            appClientProtos.push_back(
                std::shared_ptr<ApplicationClientProtocol>(
                    new ApplicationClientProtocol(
                        user, rmInfos[i].getHost(),rmInfos[i].getPort(), tokenService, sessionConfig)));
            LOG(INFO, "ApplicationClient finds a candidate RM, host:%s, port:%s",
                      rmInfos[i].getHost().c_str(), rmInfos[i].getPort().c_str());
        }
    }
    currentAppClientProto = 0;
}

/*
 * Used for unittest
 */
ApplicationClient::ApplicationClient(ApplicationClientProtocol *appclient){
    appClientProtos.push_back(std::shared_ptr<ApplicationClientProtocol>(appclient));
    currentAppClientProto = 0;
}

ApplicationClient::~ApplicationClient() {
}

std::shared_ptr<ApplicationClientProtocol>
    ApplicationClient::getActiveAppClientProto(uint32_t & oldValue) {
    lock_guard<mutex> lock(this->mut);

    LOG(DEBUG2, "ApplicationClient::getActiveAppClientProto is called.");

    if (appClientProtos.empty()) {
        LOG(WARNING, "The vector of ApplicationClientProtocol is empty.");
        THROW(Yarn::YarnResourceManagerClosed, "ApplicationClientProtocol is closed.");
    }

    oldValue = currentAppClientProto;
    LOG(DEBUG1, "ApplicationClient::getActiveAppClientProto, current is %d.",
            currentAppClientProto);
    return appClientProtos[currentAppClientProto % appClientProtos.size()];
}

void ApplicationClient::failoverToNextAppClientProto(uint32_t oldValue){
    lock_guard<mutex> lock(mut);

    if (oldValue != currentAppClientProto || appClientProtos.size() == 1) {
        return;
    }

    ++currentAppClientProto;
    currentAppClientProto = currentAppClientProto % appClientProtos.size();
    LOG(INFO, "ApplicationClient::failoverToNextAppClientProto, current is %d.",
            currentAppClientProto);
}

static void HandleYarnFailoverException(const Yarn::YarnFailoverException & e) {
    try {
        Yarn::rethrow_if_nested(e);
    } catch (...) {
        NESTED_THROW(Yarn::YarnRpcException, "%s", e.what());
    }

    //should not reach here
    abort();
}

#define RESOURCEMANAGER_HA_RETRY_BEGIN() \
    do { \
        int __count = 0; \
        do { \
            uint32_t __oldValue = 0; \
            std::shared_ptr<ApplicationClientProtocol> appClientProto = getActiveAppClientProto(__oldValue); \
            try { \
                (void)0

#define RESOURCEMANAGER_HA_RETRY_END() \
    break; \
    } catch (const Yarn::ResourceManagerStandbyException & e) { \
        if (!enableRMHA || __count++ > maxRMHARetry) { \
            throw; \
        } \
    } catch (const Yarn::YarnFailoverException & e) { \
        if (!enableRMHA || __count++ > maxRMHARetry) { \
            HandleYarnFailoverException(e); \
        } \
    } \
    failoverToNextAppClientProto(__oldValue); \
    } while (true); \
    } while (0)

/*
 rpc getNewApplication (GetNewApplicationRequestProto) returns (GetNewApplicationResponseProto);

 message GetNewApplicationRequestProto {
 }

 message GetNewApplicationResponseProto {
 optional ApplicationIdProto application_id = 1;
 optional ResourceProto maximumCapability = 2;
 }
 */
ApplicationId ApplicationClient::getNewApplication() {
    GetNewApplicationRequest request;
    GetNewApplicationResponse response;

    RESOURCEMANAGER_HA_RETRY_BEGIN();
    response = appClientProto->getNewApplication(request);
    RESOURCEMANAGER_HA_RETRY_END();
    return response.getApplicationId();
}

/*
 rpc submitApplication (SubmitApplicationRequestProto) returns (SubmitApplicationResponseProto);

 message SubmitApplicationRequestProto {
 optional ApplicationSubmissionContextProto application_submission_context= 1;
 }

 message SubmitApplicationResponseProto {
 }
 */

void ApplicationClient::submitApplication(
        ApplicationSubmissionContext &appContext) {
    SubmitApplicationRequest request;
    request.setApplicationSubmissionContext(appContext);

    RESOURCEMANAGER_HA_RETRY_BEGIN();
    appClientProto->submitApplication(request);
    RESOURCEMANAGER_HA_RETRY_END();
}

/*
 rpc getApplicationReport (GetApplicationReportRequestProto) returns (GetApplicationReportResponseProto);

 message GetApplicationReportRequestProto {
 optional ApplicationIdProto application_id = 1;
 }

 message GetApplicationReportResponseProto {
 optional ApplicationReportProto application_report = 1;
 }
 */

ApplicationReport ApplicationClient::getApplicationReport(
        ApplicationId &appId) {
    GetApplicationReportRequest request;
    GetApplicationReportResponse response;

    request.setApplicationId(appId);
    RESOURCEMANAGER_HA_RETRY_BEGIN();
    response = appClientProto->getApplicationReport(request);
    RESOURCEMANAGER_HA_RETRY_END();

    return response.getApplicationReport();
}

list<ContainerReport> ApplicationClient::getContainers(ApplicationAttemptId &appAttempId){
    GetContainersRequest request;
    GetContainersResponse response;

    request.setApplicationAttemptId(appAttempId);
    RESOURCEMANAGER_HA_RETRY_BEGIN();
    response = appClientProto->getContainers(request);
    RESOURCEMANAGER_HA_RETRY_END();

    return response.getContainersReportList();
}

list<NodeReport> ApplicationClient::getClusterNodes(list<NodeState> &states) {
    GetClusterNodesRequest request;
    GetClusterNodesResponse response;
    request.setNodeStates(states);

    RESOURCEMANAGER_HA_RETRY_BEGIN();
    response = appClientProto->getClusterNodes(request);
    RESOURCEMANAGER_HA_RETRY_END();

    return response.getNodeReports();
}

QueueInfo ApplicationClient::getQueueInfo(string &queue, bool includeApps,
        bool includeChildQueues, bool recursive) {
    GetQueueInfoRequest request;
    GetQueueInfoResponse response;
    request.setQueueName(queue);
    request.setIncludeApplications(includeApps);
    request.setIncludeChildQueues(includeChildQueues);
    request.setRecursive(recursive);

    RESOURCEMANAGER_HA_RETRY_BEGIN();
    response = appClientProto->getQueueInfo(request);
    RESOURCEMANAGER_HA_RETRY_END();

    return response.getQueueInfo();
}

void ApplicationClient::forceKillApplication(ApplicationId &appId) {
    KillApplicationRequest request;
    request.setApplicationId(appId);

    RESOURCEMANAGER_HA_RETRY_BEGIN();
    appClientProto->forceKillApplication(request);
    RESOURCEMANAGER_HA_RETRY_END();
}

YarnClusterMetrics ApplicationClient::getClusterMetrics() {
    GetClusterMetricsRequest request;
    GetClusterMetricsResponse response;

    RESOURCEMANAGER_HA_RETRY_BEGIN();
    response = appClientProto->getClusterMetrics(request);
    RESOURCEMANAGER_HA_RETRY_END();

    return response.getClusterMetrics();
}

list<ApplicationReport> ApplicationClient::getApplications(
        list<string> &applicationTypes,
        list<YarnApplicationState> &applicationStates) {
    GetApplicationsRequest request;
    GetApplicationsResponse response;
    request.setApplicationStates(applicationStates);
    request.setApplicationTypes(applicationTypes);

    RESOURCEMANAGER_HA_RETRY_BEGIN();
    response = appClientProto->getApplications(request);
    RESOURCEMANAGER_HA_RETRY_END();

    return response.getApplicationList();
}

list<QueueUserACLInfo> ApplicationClient::getQueueAclsInfo() {
    GetQueueUserAclsInfoRequest request;
    GetQueueUserAclsInfoResponse response;

    RESOURCEMANAGER_HA_RETRY_BEGIN();
    response = appClientProto->getQueueAclsInfo(request);
    RESOURCEMANAGER_HA_RETRY_END();

    return response.getUserAclsInfoList();
}

} /* namespace libyarn */


text: Repositorio de ruby para todo lo relacionado a la contabilidad de Mexico


text:
#include <stdio.h>

#include "internal.h"

#define FREQUENCY 100 /* set this to zero to use the default timer */

static int timer_installed;
#if FREQUENCY
static volatile int ticks;

static void
ticks_timer (void *p)
{
   (void)p;
   ticks++;
} ENDOFUNC(ticks_timer)
#else
#include <time.h>

static struct timeval then;
#endif

int APIENTRY
glutGet (GLenum type)
{
   switch (type) {
      case GLUT_WINDOW_X:
         return _glut_current->xpos;
      case GLUT_WINDOW_Y:
         return _glut_current->ypos;
      case GLUT_WINDOW_WIDTH:
         return _glut_current->width;
      case GLUT_WINDOW_HEIGHT:
         return _glut_current->height;
      case GLUT_WINDOW_STENCIL_SIZE:
         return _glut_visual.stencil;
      case GLUT_WINDOW_DEPTH_SIZE:
         return _glut_visual.depth;
      case GLUT_WINDOW_RGBA:
         return !(_glut_default.mode & GLUT_INDEX);
      case GLUT_WINDOW_COLORMAP_SIZE:
         return (_glut_default.mode & GLUT_INDEX) ? (256 - RESERVED_COLORS) : 0;
      case GLUT_SCREEN_WIDTH:
         return _glut_visual.geometry[0];
      case GLUT_SCREEN_HEIGHT:
         return _glut_visual.geometry[1];
      case GLUT_INIT_WINDOW_X:
         return _glut_default.x;
      case GLUT_INIT_WINDOW_Y:
         return _glut_default.y;
      case GLUT_INIT_WINDOW_WIDTH:
         return _glut_default.width;
      case GLUT_INIT_WINDOW_HEIGHT:
         return _glut_default.height;
      case GLUT_INIT_DISPLAY_MODE:
         return _glut_default.mode;
      case GLUT_ELAPSED_TIME:
#if FREQUENCY
         if (!timer_installed) {
            timer_installed = GL_TRUE;
            LOCKDATA(ticks);
            LOCKFUNC(ticks_timer);
            pc_install_int(ticks_timer, NULL, FREQUENCY);
         }
         return ticks * 1000 / FREQUENCY;
#else
         if (!timer_installed) {
            timer_installed = GL_TRUE;
            gettimeofday(&then, NULL);
            return 0;
         } else {
            struct timeval now;
            gettimeofday(&now, NULL);
            return (now.tv_usec - then.tv_usec) / 1000 +
                   (now.tv_sec  - then.tv_sec)  * 1000;
         }
#endif
      default:
         return -1;
   }
}

int APIENTRY
glutDeviceGet (GLenum type)
{
   switch (type) {
      case GLUT_HAS_KEYBOARD:
         return GL_TRUE;
      case GLUT_HAS_MOUSE:
         return (_glut_mouse != 0);
      case GLUT_NUM_MOUSE_BUTTONS:
         return _glut_mouse;
      case GLUT_HAS_SPACEBALL:
      case GLUT_HAS_DIAL_AND_BUTTON_BOX:
      case GLUT_HAS_TABLET:
         return GL_FALSE;
      case GLUT_NUM_SPACEBALL_BUTTONS:
      case GLUT_NUM_BUTTON_BOX_BUTTONS:
      case GLUT_NUM_DIALS:
      case GLUT_NUM_TABLET_BUTTONS:
         return 0;
      default:
         return -1;
   }
}

int APIENTRY
glutGetModifiers (void)
{
   int mod = 0;
   int shifts = pc_keyshifts();

   if (shifts & (KB_SHIFT_FLAG | KB_CAPSLOCK_FLAG)) {
      mod |= GLUT_ACTIVE_SHIFT;
   }

   if (shifts & KB_ALT_FLAG) {
      mod |= GLUT_ACTIVE_ALT;
   }

   if (shifts & KB_CTRL_FLAG) {
      mod |= GLUT_ACTIVE_CTRL;
   }

   return mod;
}

void APIENTRY
glutReportErrors (void)
{
   /* reports all the OpenGL errors that happened till now */
}

/* GAME MODE
 * Hack alert: incomplete... what is GameMode, anyway?
 */
static GLint game;
static GLboolean game_possible;
static GLboolean game_active;
static GLuint game_width;
static GLuint game_height;
static GLuint game_bpp;
static GLuint game_refresh;

void APIENTRY
glutGameModeString (const char *string)
{
   if (sscanf(string, "%ux%u:%u@%u", &game_width, &game_height, &game_bpp, &game_refresh) == 4) {
      game_possible = GL_TRUE;
   }
}

int APIENTRY
glutGameModeGet (GLenum mode)
{
   switch (mode) {
      case GLUT_GAME_MODE_ACTIVE:
         return game_active;
      case GLUT_GAME_MODE_POSSIBLE:
         return game_possible && !_glut_current;
      case GLUT_GAME_MODE_WIDTH:
         return game_active ? (int)game_width : -1;
      case GLUT_GAME_MODE_HEIGHT:
         return game_active ? (int)game_height : -1;
      case GLUT_GAME_MODE_PIXEL_DEPTH:
         return game_active ? (int)game_bpp : -1;
      case GLUT_GAME_MODE_REFRESH_RATE:
         return game_active ? (int)game_refresh : -1;
      default:
         return -1;
   }
}

int APIENTRY
glutEnterGameMode (void)
{
   if (glutGameModeGet(GLUT_GAME_MODE_POSSIBLE)) {
      _glut_visual.bpp = game_bpp;
      _glut_visual.refresh = game_refresh;

      glutInitWindowSize(game_width, game_height);

      if ((game = glutCreateWindow("<game>")) > 0) {
         game_active = GL_TRUE;
      }

      return game;
   } else {
      return 0;
   }
}

void GLUTAPIENTRY
glutLeaveGameMode (void)
{
   if (glutGameModeGet(GLUT_GAME_MODE_ACTIVE)) {
      game_active = GL_FALSE;

      glutDestroyWindow(game);
   }
}


text:
@implementation MCAppModel

+ (MCAppModel*)sharedModel
{
    static MCAppModel *sharedModel = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedModel = [[self alloc] init];
    });
    return sharedModel;
}

-(id)init
{
    if (self = [super init])
    {
        _tabBar = (MCTabBar *)[[MCViewManager sharedManager] createViewController:TAB_VIEW];

        NSLog(@"%@", NSStringFromCGRect(_tabBar.view.frame));

        CGRect tabFrame = _tabBar.view.frame;
        tabFrame.origin.y = [UIScreen mainScreen].bounds.size.height - _tabBar.view.frame.size.height;
        _tabBar.view.frame = tabFrame;
        NSLog(@"%@", NSStringFromCGRect(_tabBar.view.frame));

    }
    return self;
}

@end


text:
/*
Funciones de manera global
var sumaCuadrados = 0;
var suma = 0;
var i = 1;

for(i ; i<= 10; i++){
    sumaCuadrados += Math.pow(i,2);
    suma += i;
}
suma = Math.pow(suma, 2);
console.log(sumaCuadrados - suma);
*/

function diferencia(n){
 	var sumaCuadrados = 0;
	var suma = 0;
	var i = 1;
    for(i ; i<= n; i++){
        sumaCuadrados += Math.pow(i,2);
        suma += i;
    }
    suma = Math.pow(suma, 2);

    return suma - sumaCuadrados;
}
console.log(diferencia(100));

/*
Objetos son mutables y manipulables por referencia
*/

var miObjeto = {
	valor: 20,
	velocidad: 30
};
console.log(miObjeto.valor);

var otroObjeto = miObjeto;//no es una copia, solo una referencia (JAVA Style)
otroObjeto.velocidad = 100;

console.log(miObjeto.velocidad);

var otroObjeto2 = Object.create(miObjeto);
console.log(miObjeto.velocidad);
console.log(otroObjeto2.velocidad);

/*
EJEMPLO 3
*/

var libro = {
	autor : "Stephen King",
	titulo : "Pet Sematary"
};
console.log(libro.autor);

libro.autor = "J.K. Rowling";
console.log(libro.autor);

console.log(libro.fechaLanzamiento);//propiedad indefinida: undefined

delete libro.autor;//la propiedad pierde el valor asignado
console.log(libro.autor);

/*
EJEMPLO 4:
Clases, contener que tiene propiedades tales como metodos y variables.

JavaScripot usa funciones como clases (llamadas constructoras)
*/
 var


text:
'use strict';

var Address      = require('address-rfc2821');
var fixtures     = require('haraka-test-fixtures');

var Header       = require('../../mailheader').Header;

var _set_up = function (done) {

    this.plugin = new fixtures.plugin('data.headers');

    this.plugin.register();

    try {
        this.plugin.addrparser = require('address-rfc2822');
    }
    catch (ignore) {}

    this.connection = fixtures.connection.createConnection();

    this.connection.transaction = {
        header: new Header(),
        results: new fixtures.results(this.plugin),
        rcpt_to: [],
    };

    done();
};

exports.invalid_date = {
    setUp : _set_up,
    'none': function (test) {
        test.expect(0);
        test.done();
    },
};

exports.user_agent = {
    setUp : _set_up,
    'none': function (test) {
        test.expect(2);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /UA/.test(r.fail));
            test.equal(false, /UA/.test(r.pass));
        };
        outer.plugin.cfg.check.user_agent=true;
        outer.plugin.user_agent(next_cb, outer.connection);
        test.done();
    },
    'user-agent': function (test) {
        test.expect(2);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /UA/.test(r.pass));
            test.equal(false, /UA/.test(r.fail));
        };
        outer.plugin.cfg.check.user_agent=true;
        outer.connection.transaction.header.add_end('User-Agent', 'Thunderbird');
        outer.plugin.user_agent(next_cb, outer.connection);
        test.done();
    },
    'X-mailer': function (test) {
        test.expect(2);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /UA/.test(r.pass));
            test.equal(false, /UA/.test(r.fail));
        };
        outer.plugin.cfg.check.user_agent=true;
        outer.connection.transaction.header.add_end('X-Mailer', 'Apple Mail');
        outer.plugin.user_agent(next_cb, outer.connection);
        test.done();
    },
};

exports.direct_to_mx = {
    setUp : _set_up,
    'auth user': function (test) {
        test.expect(3);
        this.connection.notes.auth_user = 'test@example.com';
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /^direct-to-mx/.test(r.skip));
            test.equal(false, /^direct-to-mx/.test(r.pass));
            test.equal(false, /^direct-to-mx/.test(r.fail));
        };
        this.plugin.cfg.check.direct_to_mx=true;
        this.plugin.direct_to_mx(next_cb, this.connection);
        test.done();
    },
    'received 0': function (test) {
        test.expect(3);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /^direct-to-mx/.test(r.fail));
            test.equal(false, /^direct-to-mx/.test(r.pass));
            test.equal(false, /^direct-to-mx/.test(r.skip));
        };
        this.plugin.cfg.check.direct_to_mx=true;
        this.plugin.direct_to_mx(next_cb, this.connection);
        test.done();
    },
    'received 1': function (test) {
        test.expect(1);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /^direct-to-mx/.test(r.fail));
        };
        this.plugin.cfg.check.direct_to_mx=true;
        this.connection.transaction.header.add_end('Received', 'blah');
        this.plugin.direct_to_mx(next_cb, this.connection);
        test.done();
    },
    'received 2': function (test) {
        test.expect(3);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /^direct-to-mx/.test(r.pass));
            test.equal(false, /^direct-to-mx/.test(r.fail));
            test.equal(false, /^direct-to-mx/.test(r.skip));
        };
        this.plugin.cfg.check.direct_to_mx=true;
        this.connection.transaction.header.add_end('Received', 'blah1');
        this.connection.transaction.header.add_end('Received', 'blah2');
        this.plugin.direct_to_mx(next_cb, this.connection);
        test.done();
    },
};

exports.from_match = {
    setUp : _set_up,
    'match bare': function (test) {
        test.expect(1);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.notEqual(-1, r.pass.indexOf('from_match'));
        };
        this.plugin.cfg.check.from_match=true;
        this.connection.transaction.mail_from = new Address.Address('<test@example.com>');
        this.connection.transaction.header.add_end('From', 'test@example.com');
        this.plugin.from_match(next_cb, this.connection);
        test.done();
    },
    'match typical': function (test) {
        test.expect(1);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.notEqual(-1, r.pass.indexOf('from_match'));
        };
        this.plugin.cfg.check.from_match=true;
        this.connection.transaction.mail_from = new Address.Address('<test@example.com>');
        this.connection.transaction.header.add_end('From', '"Test User" <test@example.com>');
        this.plugin.from_match(next_cb, outer.connection);
        test.done();
    },
    'match unquoted': function (test) {
        test.expect(1);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.notEqual(-1, r.pass.indexOf('from_match'));
        };
        this.plugin.cfg.check.from_match=true;
        this.connection.transaction.mail_from = new Address.Address('<test@example.com>');
        this.connection.transaction.header.add_end('From', 'Test User <test@example.com>');
        this.plugin.from_match(next_cb, this.connection);
        test.done();
    },
    'mismatch': function (test) {
        test.expect(1);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /^from_match/.test(r.fail));
        };
        this.plugin.cfg.check.from_match=true;
        this.connection.transaction.mail_from = new Address.Address('<test@example.com>');
        this.connection.transaction.header.add_end('From', "test@example.net");
        this.plugin.from_match(next_cb, this.connection);
        test.done();
    },
};

exports.mailing_list = {
    setUp : _set_up,
    'ezmlm true': function (test) {
        test.expect(2);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /ezmlm/.test(r.pass));
            test.equal(0, r.fail.length);
        };
        this.plugin.cfg.check.mailing_list=true;
        this.connection.transaction.header.add_end('Mailing-List', "blah blah: run by ezmlm");
        this.plugin.mailing_list(next_cb, this.connection);
        test.done();
    },
    'ezmlm false': function (test) {
        test.expect(2);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(r.pass.length, 0);
            test.equal(true, /not/.test(r.msg));
        };
        this.plugin.cfg.check.mailing_list=true;
        this.connection.transaction.header.add_end('Mailing-List', "blah blah random header tokens");
        this.plugin.mailing_list(next_cb, this.connection);
        test.done();
    },
    'yahoogroups': function (test) {
        test.expect(1);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /yahoogroups/.test(r.pass));
        };
        this.plugin.cfg.check.mailing_list=true;
        outer.connection.transaction.header.add_end('Mailing-List', "blah blah such-and-such@yahoogroups.com email list");
        this.plugin.mailing_list(next_cb, this.connection);
        test.done();
    },
    'majordomo': function (test) {
        test.expect(1);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /majordomo/.test(r.pass));
        };
        this.plugin.cfg.check.mailing_list=true;
        outer.connection.transaction.header.add_end('Sender', "owner-blah-blah whatcha");
        outer.plugin.mailing_list(next_cb, outer.connection);
        test.done();
    },
    'mailman': function (test) {
        test.expect(1);
        var outer = this;
        outer.connection.transaction.header.add_end('X-Mailman-Version', "owner-blah-blah whatcha");
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /mailman/.test(r.pass));
        };
        this.plugin.cfg.check.mailing_list=true;
        this.plugin.mailing_list(next_cb, this.connection);
        test.done();
    },
    'majordomo v': function (test) {
        test.expect(1);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /majordomo/.test(r.pass));
        };
        this.plugin.cfg.check.mailing_list=true;
        this.connection.transaction.header.add_end('X-Majordomo-Version', "owner-blah-blah whatcha");
        this.plugin.mailing_list(next_cb, this.connection);
        test.done();
    },
    'google groups': function (test) {
        test.expect(1);
        var outer = this;
        var next_cb = function () {
            var r = outer.connection.transaction.results.get('data.headers');
            test.equal(true, /googlegroups/.test(r.pass));
        };
        this.plugin.cfg.check.mailing_list=true;
        this.connection.transaction.header.add_end('X-Google-Loop', "blah-blah whatcha");
        this.plugin.mailing_list(next_cb, this.connection);
        test.done();
    },
};

exports.delivered_to = {
    setUp : _set_up,
    'disabled': function (test) {
        test.expect(2);
        var next_cb = function (res, msg) {
            test.equal(undefined, res);
            test.equal(undefined, msg);
            test.done();
        }.bind(this);
        this.plugin.cfg.check.delivered_to=false;
        this.plugin.delivered_to(next_cb, this.connection);
    },
    'header not present': function (test) {
        test.expect(2);
        var next_cb = function (res, msg) {
            test.equal(undefined, res);
            test.equal(undefined, msg);
            test.done();
        }.bind(this);
        this.plugin.cfg.check.delivered_to=true;
        this.plugin.delivered_to(next_cb, this.connection);
    },
    'no recipient match': function (test) {
        test.expect(2);
        var next_cb = function (res, msg) {
            test.equal(undefined, res);
            test.equal(undefined, msg);
            test.done();
        }.bind(this);
        this.plugin.cfg.check.delivered_to=true;
        // this.connection.transaction.mail_from = new Address.Address('<test@example.com>');
        this.connection.transaction.header.add_end('Delivered-To', "user@example.com");
        this.plugin.delivered_to(next_cb, this.connection);
    },
    'recipient match': function (test) {
        test.expect(2);
        var next_cb = function (res, msg) {
            test.equal(DENY, res);
            test.equal('Invalid Delivered-To header content', msg);
            test.done();
        }.bind(this);
        this.plugin.cfg.check.delivered_to=true;
        // this.connection.transaction.mail_from = new Address.Address('<test@example.com>');
        this.connection.transaction.header.add_end('Delivered-To', "user@example.com");
        this.connection.transaction.rcpt_to.push(new Address.Address('user@example.com'));
        this.plugin.delivered_to(next_cb, this.connection);
    },
    'recipient match, reject disabled': function (test) {
        test.expect(2);
        var next_cb = function (res, msg) {
            test.equal(undefined, res);
            test.equal(undefined, msg);
            test.done();
        }.bind(this);
        this.plugin.cfg.check.delivered_to=true;
        this.plugin.cfg.reject.delivered_to=false;
        // this.connection.transaction.mail_from = new Address.Address('<test@example.com>');
        this.connection.transaction.header.add_end('Delivered-To', "user@example.com");
        this.connection.transaction.rcpt_to.push(new Address.Address('user@example.com'));
        this.plugin.delivered_to(next_cb, this.connection);
    },
};


text:
require 'spec_helper'
require 'selenium-webdriver'
require 'shared_selenium_session'

CHROME_DRIVER = if ENV['HEADLESS'] then :selenium_chrome_headless else :selenium_chrome end

# if ENV['HEADLESS'] && ENV['TRAVIS']
#   Selenium::WebDriver::Chrome.path='/usr/bin/google-chrome-beta'
# end

Capybara.register_driver :selenium_chrome_clear_storage do |app|
  chrome_options = {
    browser: :chrome,
    options: ::Selenium::WebDriver::Chrome::Options.new()
  }
  chrome_options[:options].args << 'headless' if ENV['HEADLESS']
  Capybara::Selenium::Driver.new(app, chrome_options.merge(clear_local_storage: true, clear_session_storage: true))
end

module TestSessions
  Chrome = Capybara::Session.new(CHROME_DRIVER, TestApp)
end

skipped_tests = [:response_headers, :status_code, :trigger]
# skip window tests when headless for now - closing a window not supported by chromedriver/chrome
skipped_tests << :windows if ENV['TRAVIS']  && (ENV['SKIP_WINDOW'] || ENV['HEADLESS'])

Capybara::SpecHelper.run_specs TestSessions::Chrome, CHROME_DRIVER.to_s, capybara_skip: skipped_tests

RSpec.describe "Capybara::Session with chrome" do
  include Capybara::SpecHelper
  include_examples  "Capybara::Session", TestSessions::Chrome, CHROME_DRIVER

  context "storage" do
    describe "#reset!" do
      it "does not clear either storage by default" do
        @session = TestSessions::Chrome
        @session.visit('/with_js')
        @session.find(:css, '#set-storage').click
        @session.reset!
        @session.visit('/with_js')
        # expect(@session.driver.browser.local_storage.keys).not_to be_empty
        # expect(@session.driver.browser.session_storage.keys).not_to be_empty
        expect(@session.evaluate_script('Object.keys(localStorage)')).not_to be_empty
        expect(@session.evaluate_script('Object.keys(sessionStorage)')).not_to be_empty
      end

      it "clears storage when set" do
        @session = Capybara::Session.new(:selenium_chrome_clear_storage, TestApp)
        @session.visit('/with_js')
        @session.find(:css, '#set-storage').click
        @session.reset!
        @session.visit('/with_js')
        # expect(@session.driver.browser.local_storage.keys).to be_empty
        # expect(@session.driver.browser.session_storage.keys).to be_empty
        expect(@session.evaluate_script('Object.keys(localStorage)')).to be_empty
        expect(@session.evaluate_script('Object.keys(sessionStorage)')).to be_empty
      end
    end
  end
end