text:
package histogram_test

import (
	"testing"

	"v.io/x/ref/lib/stats/histogram"
)

func TestHistogram(t *testing.T) {
	// This creates a histogram with the following buckets:
	//  [1, 2)
	//  [2, 4)
	//  [4, 8)
	//  [8, 16)
	//  [16, Inf)
	opts := histogram.Options{
		NumBuckets:         5,
		GrowthFactor:       1.0,
		SmallestBucketSize: 1.0,
		MinValue:           1.0,
	}
	h := histogram.New(opts)
	// Trying to add a value that's less than MinValue, should return an error.
	if err := h.Add(0); err == nil {
		t.Errorf("unexpected return value for Add(0.0). Want != nil, got nil")
	}
	// Adding good values. Expect no errors.
	for i := 1; i <= 50; i++ {
		if err := h.Add(int64(i)); err != nil {
			t.Errorf("unexpected return value for Add(%d). Want nil, got %v", i, err)
		}
	}
	expectedCount := []int64{1, 2, 4, 8, 35}
	buckets := h.Value().Buckets
	for i := 0; i < opts.NumBuckets; i++ {
		if buckets[i].Count != expectedCount[i] {
			t.Errorf("unexpected count for bucket[%d]. Want %d, got %v", i, expectedCount[i], buckets[i].Count)
		}
	}

	v := h.Value()
	if expected, got := int64(50), v.Count; got != expected {
		t.Errorf("unexpected count in histogram value. Want %d, got %v", expected, got)
	}
	if expected, got := int64(50*(1+50)/2), v.Sum; got != expected {
		t.Errorf("unexpected sum in histogram value. Want %d, got %v", expected, got)
	}
	if expected, got := int64(1), v.Min; got != expected {
		t.Errorf("unexpected min in histogram value. Want %d, got %v", expected, got)
	}
	if expected, got := int64(50), v.Max; got != expected {
		t.Errorf("unexpected max in histogram value. Want %d, got %v", expected, got)
	}
}

func BenchmarkHistogram(b *testing.B) {
	opts := histogram.Options{
		NumBuckets:         30,
		GrowthFactor:       1.0,
		SmallestBucketSize: 1.0,
		MinValue:           1.0,
	}
	h := histogram.New(opts)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		h.Add(int64(i)) //nolint:errcheck
	}
}


text:
import typing

import pytest
import responses

from github_stargazers.github import GitHub
from github_stargazers.github import UsernameRepositoryError, TooManyRequestsHttpError, UrlNotFoundError
from github_stargazers.github import MissingHyperlinkTagError, MissingHrefAttributeError, HrefContentError
from tests import get_examples_invalid_user_repo, get_wrong_href_content, get_page_content_with_href

def test_wrong_argument_raises() -> None:
    wrong_arguments: typing.List[str] = ["foo", "foo/", "/bar", "/", "//", ""]
    for wrong_argument in wrong_arguments:
        with pytest.raises(UsernameRepositoryError):
            GitHub(wrong_argument)

@pytest.fixture
def url_page_content_1() -> str:
    return '
  John Williams
 ' \
           '
  Michael Phelps
'

@pytest.fixture
def url_page_content_2() -> str:
    return '
  John Williams 2
 ' \
           '
  Michael Phelps 2
'

@responses.activate
def test_get_all_stargazers_has_all_stargazers(url_page_content_1: str,
                                               ok_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=url_page_content_1,
        status=ok_status_code
    )
    assert set(GitHub("foo/bar").get_all_stargazers()) == set(['foo', 'bar'])

@responses.activate
def test_get_all_stargazers_sorts_stargazers(url_page_content_1: str,
                                             ok_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=url_page_content_1,
        status=ok_status_code
    )
    assert GitHub("foo/bar").get_all_stargazers() == sorted(['foo', 'bar'])

@pytest.fixture
def url_page_content_without_stargazers() -> str:
    return "
 title
 "

@responses.activate
def test_get_all_stargazers_returns_empty_on_page_without_stargazers(url_page_content_without_stargazers: str,
                                                                     ok_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=url_page_content_without_stargazers,
        status=ok_status_code
    )
    assert GitHub("foo/bar").get_all_stargazers() == []

@responses.activate
def test_get_all_stargazers_sorts_stargazers_two_pages(url_page_content_1: str,
                                                       url_page_content_2: str,
                                                       ok_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=url_page_content_1,
        status=ok_status_code
    )
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=2",
        body=url_page_content_2,
        status=ok_status_code
    )
    assert GitHub("foo/bar").get_all_stargazers() == sorted(['foo', 'bar', 'foo2', 'bar2'])

@pytest.mark.parametrize("invalid_user_and_repo", get_examples_invalid_user_repo())
@responses.activate
def test_get_all_stargazers_on_invalid_user_repo_raises(url_page_content_1: str,
                                                        invalid_user_and_repo: str,
                                                        not_found_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/" + invalid_user_and_repo + "/stargazers?page=1",
        body=url_page_content_1,
        status=not_found_status_code
    )
    with pytest.raises(UrlNotFoundError):
        GitHub(invalid_user_and_repo).get_all_stargazers()

@responses.activate
def test_get_all_stargazers_on_too_many_requests_raises(url_page_content_1: str,
                                                        too_many_requests_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=url_page_content_1,
        status=too_many_requests_status_code
    )
    with pytest.raises(TooManyRequestsHttpError):
        GitHub("foo/bar").get_all_stargazers()

@responses.activate
def test_provided_user_is_stargazer(url_page_content_1: str, ok_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=url_page_content_1,
        status=ok_status_code
    )
    assert GitHub("foo/bar").is_stargazer("foo")

@responses.activate
def test_provided_user_is_stargazer_on_last_page(url_page_content_1: str,
                                                 url_page_content_2: str,
                                                 ok_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=url_page_content_1,
        status=ok_status_code
    )
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=2",
        body=url_page_content_2,
        status=ok_status_code
    )
    assert GitHub("foo/bar").is_stargazer("bar2")

@responses.activate
def test_provided_user_is_not_stargazer(url_page_content_1: str, ok_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=url_page_content_1,
        status=ok_status_code
    )
    assert not GitHub("foo/bar").is_stargazer("another_foo")

@responses.activate
def test_provided_user_is_not_stargazer_on_page_without_stargazers(url_page_content_without_stargazers: str,
                                                                   ok_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=url_page_content_without_stargazers,
        status=ok_status_code
    )
    assert not GitHub("foo/bar").is_stargazer("another_foo")

@responses.activate
def test_provided_user_on_invalid_page(url_page_content_1: str, not_found_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=url_page_content_1,
        status=not_found_status_code
    )
    with pytest.raises(UrlNotFoundError):
        GitHub("foo/bar").is_stargazer("foo")

@responses.activate
def test_provided_user_on_too_many_requests_page(url_page_content_1: str,
                                                 too_many_requests_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=url_page_content_1,
        status=too_many_requests_status_code
    )
    with pytest.raises(TooManyRequestsHttpError):
        GitHub("foo/bar").is_stargazer("foo")

@responses.activate
def test_provided_user_with_missing_hyperlink_tag(url_page_content_no_hyperlink: str,
                                                  ok_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=url_page_content_no_hyperlink,
        status=ok_status_code
    )
    with pytest.raises(MissingHyperlinkTagError):
        GitHub("foo/bar").is_stargazer("foo")

@responses.activate
def test_provided_user_with_missing_href_attribute(url_page_content_no_href: str,
                                                   ok_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=url_page_content_no_href,
        status=ok_status_code
    )
    with pytest.raises(MissingHrefAttributeError):
        GitHub("foo/bar").is_stargazer("foo")

@pytest.mark.parametrize("wrong_href_content", get_wrong_href_content())
@responses.activate
def test_wrong_href_content_raises(wrong_href_content: str,
                                   ok_status_code: int) -> None:
    responses.add(
        responses.GET,
        "https://github.com/foo/bar/stargazers?page=1",
        body=get_page_content_with_href(wrong_href_content),
        status=ok_status_code
    )
    with pytest.raises(HrefContentError):
        GitHub("foo/bar").is_stargazer("foo")

redpajama_set_name: RedPajamaGithub


text:
/* *
 *
 *  (c) 2010-2020 Torstein Honsi
 *
 *  License: www.highcharts.com/license
 *
 *  !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
 *
 * */
'use strict';
import H from './Globals.js';
import U from './Utilities.js';
var addEvent = U.addEvent, seriesType = U.seriesType;
import './Options.js';
import './Series.js';
var Series = H.Series;
/**
 * Scatter series type.
 *
 * @private
 * @class
 * @name Highcharts.seriesTypes.scatter
 *
 * @augments Highcharts.Series
 */
seriesType('scatter', 'line',
/**
 * A scatter plot uses cartesian coordinates to display values for two
 * variables for a set of data.
 *
 * @sample {highcharts} highcharts/demo/scatter/
 *         Scatter plot
 *
 * @extends      plotOptions.line
 * @excluding    pointPlacement, shadow, useOhlcData
 * @product      highcharts highstock
 * @optionparent plotOptions.scatter
 */
{
    /**
     * The width of the line connecting the data points.
     *
     * @sample {highcharts} highcharts/plotoptions/scatter-linewidth-none/
     *         0 by default
     * @sample {highcharts} highcharts/plotoptions/scatter-linewidth-1/
     *         1px
     *
     * @product highcharts highstock
     */
    lineWidth: 0,
    findNearestPointBy: 'xy',
    /**
     * Apply a jitter effect for the rendered markers. When plotting
     * discrete values, a little random noise may help telling the points
     * apart. The jitter setting applies a random displacement of up to `n`
     * axis units in either direction. So for example on a horizontal X
     * axis, setting the `jitter.x` to 0.24 will render the point in a
     * random position between 0.24 units to the left and 0.24 units to the
     * right of the true axis position. On a category axis, setting it to
     * 0.5 will fill up the bin and make the data appear continuous.
     *
     * When rendered on top of a box plot or a column series, a jitter value
     * of 0.24 will correspond to the underlying series' default
     * [groupPadding](
     * https://api.highcharts.com/highcharts/plotOptions.column.groupPadding)
     * and [pointPadding](
     * https://api.highcharts.com/highcharts/plotOptions.column.pointPadding)
     * settings.
     *
     * @sample {highcharts} highcharts/series-scatter/jitter
     *         Jitter on a scatter plot
     *
     * @sample {highcharts} highcharts/series-scatter/jitter-boxplot
     *         Jittered scatter plot on top of a box plot
     *
     * @product highcharts highstock
     * @since 7.0.2
     */
    jitter: {
        /**
         * The maximal X offset for the random jitter effect.
         */
        x: 0,
        /**
         * The maximal Y offset for the random jitter effect.
         */
        y: 0
    },
    marker: {
        enabled: true // Overrides auto-enabling in line series (#3647)
    },
    /**
     * Sticky tracking of mouse events. When true, the `mouseOut` event
     * on a series isn't triggered until the mouse moves over another
     * series, or out of the plot area. When false, the `mouseOut` event on
     * a series is triggered when the mouse leaves the area around the
     * series' graph or markers. This also implies the tooltip. When
     * `stickyTracking` is false and `tooltip.shared` is false, the tooltip
     * will be hidden when moving the mouse between series.
     *
     * @type      {boolean}
     * @default   false
     * @product   highcharts highstock
     * @apioption plotOptions.scatter.stickyTracking
     */
    /**
     * A configuration object for the tooltip rendering of each single
     * series. Properties are inherited from [tooltip](#tooltip).
     * Overridable properties are `headerFormat`, `pointFormat`,
     * `yDecimals`, `xDateFormat`, `yPrefix` and `ySuffix`. Unlike other
     * series, in a scatter plot the series.name by default shows in the
     * headerFormat and point.x and point.y in the pointFormat.
     *
     * @product highcharts highstock
     */
    tooltip: {
        headerFormat: '\u25CF ' +
            ' {series.name}
',
        pointFormat: 'x: {point.x}
y: {point.y}
'
    }
    // Prototype members
}, {
    sorted: false,
    requireSorting: false,
    noSharedTooltip: true,
    trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
    takeOrdinalPosition: false,
    /* eslint-disable valid-jsdoc */
    /**
     * @private
     * @function Highcharts.seriesTypes.scatter#drawGraph
     */
    drawGraph: function () {
        if (this.options.lineWidth) {
            Series.prototype.drawGraph.call(this);
        }
    },
    // Optionally add the jitter effect
    applyJitter: function () {
        var series = this, jitter = this.options.jitter, len = this.points.length;
        /**
         * Return a repeatable, pseudo-random number based on an integer
         * seed.
         * @private
         */
        function unrandom(seed) {
            var rand = Math.sin(seed) * 10000;
            return rand - Math.floor(rand);
        }
        if (jitter) {
            this.points.forEach(function (point, i) {
                ['x', 'y'].forEach(function (dim, j) {
                    var axis, plotProp = 'plot' + dim.toUpperCase(), min, max, translatedJitter;
                    if (jitter[dim] && !point.isNull) {
                        axis = series[dim + 'Axis'];
                        translatedJitter =
                            jitter[dim] * axis.transA;
                        if (axis && !axis.isLog) {
                            // Identify the outer bounds of the jitter range
                            min = Math.max(0, point[plotProp] - translatedJitter);
                            max = Math.min(axis.len, point[plotProp] + translatedJitter);
                            // Find a random position within this range
                            point[plotProp] = min +
                                (max - min) * unrandom(i + j * len);
                            // Update clientX for the tooltip k-d-tree
                            if (dim === 'x') {
                                point.clientX = point.plotX;
                            }
                        }
                    }
                });
            });
        }
    }
    /* eslint-enable valid-jsdoc */
});
/* eslint-disable no-invalid-this */
addEvent(Series, 'afterTranslate', function () {
    if (this.applyJitter) {
        this.applyJitter();
    }
});
/* eslint-enable no-invalid-this */
/**
 * A `scatter` series. If the [type](#series.scatter.type) option is
 * not specified, it is inherited from [chart.type](#chart.type).
 *
 * @extends   series,plotOptions.scatter
 * @excluding dataParser, dataURL, useOhlcData
 * @product   highcharts highstock
 * @apioption series.scatter
 */
/**
 * An array of data points for the series. For the `scatter` series
 * type, points can be given in the following ways:
 *
 * 1. An array of numerical values. In this case, the numerical values will be
 *    interpreted as `y` options. The `x` values will be automatically
 *    calculated, either starting at 0 and incremented by 1, or from
 *    `pointStart` and `pointInterval` given in the series options. If the axis
 *    has categories, these will be used. Example:
 *    ```js
 *    data: [0, 5, 3, 5]
 *    ```
 *
 * 2. An array of arrays with 2 values. In this case, the values correspond to
 *    `x,y`. If the first value is a string, it is applied as the name of the
 *    point, and the `x` value is inferred.
 *    ```js
 *    data: [
 *        [0, 0],
 *        [1, 8],
 *        [2, 9]
 *    ]
 *    ```
 *
 * 3. An array of objects with named values. The following snippet shows only a
 *    few settings, see the complete options set below. If the total number of
 *    data points exceeds the series'
 *    [turboThreshold](#series.scatter.turboThreshold), this option is not
 *    available.
 *    ```js
 *    data: [{
 *        x: 1,
 *        y: 2,
 *        name: "Point2",
 *        color: "#00FF00"
 *    }, {
 *        x: 1,
 *        y: 4,
 *        name: "Point1",
 *        color: "#FF00FF"
 *    }]
 *    ```
 *
 * @sample {highcharts} highcharts/chart/reflow-true/
 *         Numerical values
 * @sample {highcharts} highcharts/series/data-array-of-arrays/
 *         Arrays of numeric x and y
 * @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
 *         Arrays of datetime x and y
 * @sample {highcharts} highcharts/series/data-array-of-name-value/
 *         Arrays of point.name and y
 * @sample {highcharts} highcharts/series/data-array-of-objects/
 *         Config objects
 *
 * @type      {Array<number|Array<(number|string),(number|null)>|null|*>}
 * @extends   series.line.data
 * @product   highcharts highstock
 * @apioption series.scatter.data
 */
''; // adds doclets above to transpilat


text:
import time
from dateutil.tz import tzoffset
from datetime import date, datetime, timedelta
from unittest import TestCase

from ptime import Parser, ParserError, Format, Language

class TestParserMethods(TestCase):
    def setUp(self):
        self.parser = Parser(Format(''), [Language.fromcode('en')])

    def test_complete(self):
        now = datetime.now(tzoffset(None, 0)).replace(microsecond=0)
        target = now + timedelta(hours=1)
        attrs = {'hour': target.hour, 'minute': target.minute, 'second': target.second}
        result = self.parser.complete(attrs, now)
        self.assertEquals(self.parser.mktime(result), now - timedelta(hours=23))

    def test_parse_weekday(self):
        pass

    def test_parse_yearday(self):
        pass

    def test_parse_month_abbr(self):
        self.assertEquals(self.parser.parse_month_abbr('feb', None), {'month': 2})

    def test_parse_month_name(self):
        self.assertEquals(self.parser.parse_month_name('feburary', None), {'month': 2})

    def test_parse_ampm(self):
        self.assertEquals(self.parser.parse_ampm('PM', None), {'ampm': 1})

    # timezones are not tested for the sake of perfomance #

    def test_parse_offset_hours(self):
        expectation = {'tzinfo': tzoffset(None, -2*3600 + 30*60)}
        self.assertEquals(self.parser.parse_offset_hours('-02:30', None), expectation)
        self.assertEquals(self.parser.parse_offset_hours('-0230', None), expectation)

    def test_parse_relative_day(self):
        now = datetime.now()
        result = self.parser.parse_relative_day('today', now)
        self.assertEquals(date(**result), now.date())

    def test_parse_days_ago(self):
        now = datetime.now()
        result = self.parser.parse_days_ago('5 days ago', now)
        self.assertEquals(date(**result), now.date() - timedelta(days=5))

class TestParser(TestCase):
    def test_mysql(self):
        now = datetime.now().replace(microsecond=0)
        string = time.strftime('%Y-%m-%d %H:%M:%S', now.timetuple())
        parser = Parser(Format.mysql())
        self.assertEquals(parser.parse(string), now)

    def test_invalid_date(self):
        parser = Parser(Format('%M'))
        self.assertRaises(ParserError, parser.parse, 'abc')

    def test_relative_date(self):
        now = datetime.now()
        parser = Parser(Format('%L'), [Language.fromcode('en')])
        result = parser.parse('yesterday', now)
        self.assertEquals(result.date(), now.date() - timedelta(days=1))

    def test_custom_base(self):
        base = datetime.now().replace(minute=0, second=0, microsecond=0) - timedelta(hours=1)
        result = Parser(Format('%i')).parse('30', base)
        self.assertEquals(result, base.replace(minute=30) - timedelta(hours=1))

    def test_completion_boundary_cases(self):
        base = datetime(2013, 9, 13, 0)
        result = Parser(Format('%i')).parse('30', base)
        self.assertEquals(result, datetime(2013, 9, 12, 23, 30))

    def test_century_year(self):
        result = Parser(Format('%d.%m.%y')).parse('30.10.13')
        self.assertEquals(result.date(), date(2013, 10, 30))


text:
import collections
import copy

from heatclient import exc
from heatclient.v1 import stacks
import mock
from oslo_config import cfg
import six

from heat.common import exception
from heat.common.i18n import _
from heat.common import template_format
from heat.engine.clients.os import heat_plugin
from heat.engine import environment
from heat.engine.resources.openstack.heat import remote_stack
from heat.engine import rsrc_defn
from heat.engine import scheduler
from heat.engine import stack
from heat.engine import template
from heat.tests import common as tests_common
from heat.tests import utils

cfg.CONF.import_opt('action_retry_limit', 'heat.common.config')

parent_stack_template = '''
heat_template_version: 2013-05-23
resources:
    remote_stack:
        type: OS::Heat::Stack
        properties:
            context:
                region_name: RegionOne
            template: { get_file: remote_template.yaml }
            timeout: 60
            parameters:
                name: foo
'''

remote_template = '''
heat_template_version: 2013-05-23
parameters:
  name:
    type: string
resources:
  resource1:
    type: GenericResourceType
outputs:
  foo:
    value: bar
'''

bad_template = '''
heat_template_version: 2013-05-26
parameters:
  name:
    type: string
resources:
  resource1:
    type: UnknownResourceType
outputs:
  foo:
    value: bar
'''

def get_stack(stack_id='c8a19429-7fde-47ea-a42f-40045488226c',
              stack_name='teststack', description='No description',
              creation_time='2013-08-04T20:57:55Z',
              updated_time='2013-08-04T20:57:55Z',
              stack_status='CREATE_COMPLETE',
              stack_status_reason='',
              outputs=None):
    action = stack_status[:stack_status.index('_')]
    status = stack_status[stack_status.index('_') + 1:]
    data = {
        'id': stack_id,
        'stack_name': stack_name,
        'description': description,
        'creation_time': creation_time,
        'updated_time': updated_time,
        'stack_status': stack_status,
        'stack_status_reason': stack_status_reason,
        'action': action,
        'status': status,
        'outputs': outputs or None,
    }
    return stacks.Stack(mock.MagicMock(), data)

class FakeClients(object):
    def __init__(self, context, region_name=None):
        self.ctx = context
        self.region_name = region_name or 'RegionOne'
        self.hc = None
        self.plugin = None

    def client(self, name):
        if self.region_name in ['RegionOne', 'RegionTwo']:
            if self.hc is None:
                self.hc = mock.MagicMock()
            return self.hc
        else:
            raise Exception('Failed connecting to Heat')

    def client_plugin(self, name):
        if self.plugin is None:
            self.plugin = heat_plugin.HeatClientPlugin(self.ctx)
        return self.plugin

class RemoteStackTest(tests_common.HeatTestCase):

    def setUp(self):
        super(RemoteStackTest, self).setUp()
        self.this_region = 'RegionOne'
        self.that_region = 'RegionTwo'
        self.bad_region = 'RegionNone'

        cfg.CONF.set_override('action_retry_limit', 0)
        self.parent = None
        self.heat = None
        self.client_plugin = None
        self.this_context = None
        self.old_clients = None

        def unset_clients_property():
            if self.this_context is not None:
                type(self.this_context).clients = self.old_clients

        self.addCleanup(unset_clients_property)

    def initialize(self):
        parent, rsrc = self.create_parent_stack(remote_region='RegionTwo')
        self.parent = parent
        self.heat = rsrc._context().clients.client("heat")
        self.client_plugin = rsrc._context().clients.client_plugin('heat')

    def create_parent_stack(self, remote_region=None, custom_template=None):
        snippet = template_format.parse(parent_stack_template)
        self.files = {
            'remote_template.yaml': custom_template or remote_template
        }

        region_name = remote_region or self.this_region
        props = snippet['resources']['remote_stack']['properties']

        # context property is not required, default to current region
        if remote_region is None:
            del props['context']
        else:
            props['context']['region_name'] = region_name

        if self.this_context is None:
            self.this_context = utils.dummy_context(
                region_name=self.this_region)

        tmpl = template.Template(snippet, files=self.files)
        parent = stack.Stack(self.this_context, 'parent_stack', tmpl)

        # parent context checking
        ctx = parent.context.to_dict()
        self.assertEqual(self.this_region, ctx['region_name'])
        self.assertEqual(self.this_context.to_dict(), ctx)

        parent.store()

        resource_defns = parent.t.resource_definitions(parent)
        rsrc = remote_stack.RemoteStack(
            'remote_stack_res',
            resource_defns['remote_stack'],
            parent)

        # remote stack resource checking
        self.assertEqual(60, rsrc.properties.get('timeout'))

        remote_context = rsrc._context()
        hc = FakeClients(self.this_context, rsrc._region_name)
        if self.old_clients is None:
            self.old_clients = type(remote_context).clients
            type(remote_context).clients = mock.PropertyMock(return_value=hc)

        return parent, rsrc

    def create_remote_stack(self):
        # This method default creates a stack on RegionTwo (self.other_region)
        defaults = [get_stack(stack_status='CREATE_IN_PROGRESS'),
                    get_stack(stack_status='CREATE_COMPLETE')]

        if self.parent is None:
            self.initialize()

        # prepare clients to return status
        self.heat.stacks.create.return_value = {'stack': get_stack().to_dict()}
        self.heat.stacks.get = mock.MagicMock(side_effect=defaults)
        rsrc = self.parent['remote_stack']
        scheduler.TaskRunner(rsrc.create)()

        return rsrc

    def test_create_remote_stack_default_region(self):
        parent, rsrc = self.create_parent_stack()

        self.assertEqual((rsrc.INIT, rsrc.COMPLETE), rsrc.state)
        self.assertEqual(self.this_region, rsrc._region_name)
        ctx = rsrc.properties.get('context')
        self.assertIsNone(ctx)

        self.assertIsNone(rsrc.validate())

    def test_create_remote_stack_this_region(self):
        parent, rsrc = self.create_parent_stack(remote_region=self.this_region)

        self.assertEqual((rsrc.INIT, rsrc.COMPLETE), rsrc.state)
        self.assertEqual(self.this_region, rsrc._region_name)
        ctx = rsrc.properties.get('context')
        self.assertEqual(self.this_region, ctx['region_name'])

        self.assertIsNone(rsrc.validate())

    def test_create_remote_stack_that_region(self):
        parent, rsrc = self.create_parent_stack(remote_region=self.that_region)

        self.assertEqual((rsrc.INIT, rsrc.COMPLETE), rsrc.state)
        self.assertEqual(self.that_region, rsrc._region_name)
        ctx = rsrc.properties.get('context')
        self.assertEqual(self.that_region, ctx['region_name'])

        self.assertIsNone(rsrc.validate())

    def test_create_remote_stack_bad_region(self):
        parent, rsrc = self.create_parent_stack(remote_region=self.bad_region)

        self.assertEqual((rsrc.INIT, rsrc.COMPLETE), rsrc.state)
        self.assertEqual(self.bad_region, rsrc._region_name)
        ctx = rsrc.properties.get('context')
        self.assertEqual(self.bad_region, ctx['region_name'])

        ex = self.assertRaises(exception.StackValidationFailed,
                               rsrc.validate)
        msg = ('Cannot establish connection to Heat endpoint '
               'at region "%s"' % self.bad_region)
        self.assertIn(msg, six.text_type(ex))

    def test_remote_validation_failed(self):
        parent, rsrc = self.create_parent_stack(remote_region=self.that_region,
                                                custom_template=bad_template)

        self.assertEqual((rsrc.INIT, rsrc.COMPLETE), rsrc.state)
        self.assertEqual(self.that_region, rsrc._region_name)
        ctx = rsrc.properties.get('context')
        self.assertEqual(self.that_region, ctx['region_name'])

        # not setting or using self.heat because this test case is a special
        # one with the RemoteStack resource initialized but not created.
        heat = rsrc._context().clients.client("heat")

        # heatclient.exc.BadRequest is the exception returned by a failed
        # validation
        heat.stacks.validate = mock.MagicMock(side_effect=exc.HTTPBadRequest)
        ex = self.assertRaises(exception.StackValidationFailed, rsrc.validate)
        msg = ('Failed validating stack template using Heat endpoint at region'
               ' "%s"') % self.that_region
        self.assertIn(msg, six.text_type(ex))

    def test_create(self):
        rsrc = self.create_remote_stack()

        self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state)
        self.assertEqual('c8a19429-7fde-47ea-a42f-40045488226c',
                         rsrc.resource_id)
        env = environment.get_child_environment(rsrc.stack.env,
                                                {'name': 'foo'})
        args = {
            'stack_name': rsrc.physical_resource_name(),
            'template': template_format.parse(remote_template),
            'timeout_mins': 60,
            'disable_rollback': True,
            'parameters': {'name': 'foo'},
            'files': self.files,
            'environment': env.user_env_as_dict(),
        }
        self.heat.stacks.create.assert_called_with(**args)
        self.assertEqual(2, len(self.heat.stacks.get.call_args_list))

    def test_create_failed(self):
        returns = [get_stack(stack_status='CREATE_IN_PROGRESS'),
                   get_stack(stack_status='CREATE_FAILED',
                             stack_status_reason='Remote stack creation '
                                                 'failed')]

        # Note: only this test case does a out-of-band intialization, most of
        # the other test cases will have self.parent initialized.
        if self.parent is None:
            self.initialize()

        self.heat.stacks.create.return_value = {'stack': get_stack().to_dict()}
        self.heat.stacks.get = mock.MagicMock(side_effect=returns)

        rsrc = self.parent['remote_stack']
        error = self.assertRaises(exception.ResourceFailure,
                                  scheduler.TaskRunner(rsrc.create))
        error_msg = ('ResourceInError: resources.remote_stack: '
                     'Went to status CREATE_FAILED due to '
                     '"Remote stack creation failed"')
        self.assertEqual(error_msg, six.text_type(error))
        self.assertEqual((rsrc.CREATE, rsrc.FAILED), rsrc.state)

    def test_delete(self):
        returns = [get_stack(stack_status='DELETE_IN_PROGRESS'),
                   get_stack(stack_status='DELETE_COMPLETE')]

        rsrc = self.create_remote_stack()

        self.heat.stacks.get = mock.MagicMock(side_effect=returns)
        self.heat.stacks.delete = mock.MagicMock()
        remote_stack_id = rsrc.resource_id
        scheduler.TaskRunner(rsrc.delete)()

        self.assertEqual((rsrc.DELETE, rsrc.COMPLETE), rsrc.state)
        self.heat.stacks.delete.assert_called_with(stack_id=remote_stack_id)

    def test_delete_already_gone(self):
        rsrc = self.create_remote_stack()

        self.heat.stacks.delete = mock.MagicMock(
            side_effect=exc.HTTPNotFound())
        self.heat.stacks.get = mock.MagicMock(side_effect=exc.HTTPNotFound())

        remote_stack_id = rsrc.resource_id
        scheduler.TaskRunner(rsrc.delete)()

        self.assertEqual((rsrc.DELETE, rsrc.COMPLETE), rsrc.state)
        self.heat.stacks.delete.assert_called_with(stack_id=remote_stack_id)

    def test_delete_failed(self):
        returns = [get_stack(stack_status='DELETE_IN_PROGRESS'),
                   get_stack(stack_status='DELETE_FAILED',
                             stack_status_reason='Remote stack deletion '
                                                 'failed')]
        rsrc = self.create_remote_stack()

        self.heat.stacks.get = mock.MagicMock(side_effect=returns)
        self.heat.stacks.delete = mock.MagicMock()

        remote_stack_id = rsrc.resource_id
        error = self.assertRaises(exception.ResourceFailure,
                                  scheduler.TaskRunner(rsrc.delete))
        error_msg = ('ResourceInError: resources.remote_stack: '
                     'Went to status DELETE_FAILED due to '
                     '"Remote stack deletion failed"')
        self.assertIn(error_msg, six.text_type(error))
        self.assertEqual((rsrc.DELETE, rsrc.FAILED), rsrc.state)
        self.heat.stacks.delete.assert_called_with(stack_id=remote_stack_id)
        self.assertEqual(rsrc.resource_id, remote_stack_id)

    def test_attribute(self):
        rsrc = self.create_remote_stack()

        outputs = [
            {
                'output_key': 'foo',
                'output_value': 'bar'
            }
        ]
        created_stack = get_stack(stack_name='stack1', outputs=outputs)
        self.heat.stacks.get = mock.MagicMock(return_value=created_stack)
        self.assertEqual('stack1', rsrc.FnGetAtt('stack_name'))
        self.assertEqual('bar', rsrc.FnGetAtt('outputs')['foo'])
        self.heat.stacks.get.assert_called_with(
            stack_id='c8a19429-7fde-47ea-a42f-40045488226c')

    def test_attribute_failed(self):
        rsrc = self.create_remote_stack()

        error = self.assertRaises(exception.InvalidTemplateAttribute,
                                  rsrc.FnGetAtt, 'non-existent_property')
        self.assertEqual(
            'The Referenced Attribute (remote_stack non-existent_property) is '
            'incorrect.',
            six.text_type(error))

    def test_snapshot(self):
        stacks = [get_stack(stack_status='SNAPSHOT_IN_PROGRESS'),
                  get_stack(stack_status='SNAPSHOT_COMPLETE')]
        snapshot = {
            'id': 'a29bc9e25aa44f99a9a3d59cd5b0e263',
            'status': 'IN_PROGRESS'
        }

        rsrc = self.create_remote_stack()

        self.heat.stacks.get = mock.MagicMock(side_effect=stacks)
        self.heat.stacks.snapshot = mock.MagicMock(return_value=snapshot)
        scheduler.TaskRunner(rsrc.snapshot)()

        self.assertEqual((rsrc.SNAPSHOT, rsrc.COMPLETE), rsrc.state)
        self.assertEqual('a29bc9e25aa44f99a9a3d59cd5b0e263',
                         rsrc.data().get('snapshot_id'))
        self.heat.stacks.snapshot.assert_called_with(
            stack_id=rsrc.resource_id)

    def test_restore(self):
        snapshot = {
            'id': 'a29bc9e25aa44f99a9a3d59cd5b0e263',
            'status': 'IN_PROGRESS'
        }
        remote_stack = mock.MagicMock()
        remote_stack.action = 'SNAPSHOT'
        remote_stack.status = 'COMPLETE'

        parent, rsrc = self.create_parent_stack()
        rsrc.action = rsrc.SNAPSHOT

        heat = rsrc._context().clients.client("heat")
        heat.stacks.snapshot = mock.MagicMock(return_value=snapshot)
        heat.stacks.get = mock.MagicMock(return_value=remote_stack)
        scheduler.TaskRunner(parent.snapshot, None)()
        self.assertEqual((parent.SNAPSHOT, parent.COMPLETE), parent.state)

        data = parent.prepare_abandon()
        remote_stack_snapshot = {
            'snapshot': {
                'id': 'a29bc9e25aa44f99a9a3d59cd5b0e263',
                'status': 'COMPLETE',
                'data': {
                    'files': data['files'],
                    'environment': data['environment'],
                    'template': template_format.parse(
                        data['files']['remote_template.yaml'])
                }
            }
        }
        fake_snapshot = collections.namedtuple(
            'Snapshot', ('data', 'stack_id'))(data, parent.id)
        heat.stacks.snapshot_show = mock.MagicMock(
            return_value=remote_stack_snapshot)
        self.patchobject(rsrc, 'update').return_value = None
        rsrc.action = rsrc.UPDATE
        rsrc.status = rsrc.COMPLETE
        remote_stack.action = 'UPDATE'

        parent.restore(fake_snapshot)

        self.assertEqual((parent.RESTORE, parent.COMPLETE), parent.state)

    def test_check(self):
        stacks = [get_stack(stack_status='CHECK_IN_PROGRESS'),
                  get_stack(stack_status='CHECK_COMPLETE')]

        rsrc = self.create_remote_stack()

        self.heat.stacks.get = mock.MagicMock(side_effect=stacks)
        self.heat.actions.check = mock.MagicMock()
        scheduler.TaskRunner(rsrc.check)()

        self.assertEqual((rsrc.CHECK, rsrc.COMPLETE), rsrc.state)
        self.heat.actions.check.assert_called_with(stack_id=rsrc.resource_id)

    def test_check_failed(self):
        returns = [get_stack(stack_status='CHECK_IN_PROGRESS'),
                   get_stack(stack_status='CHECK_FAILED',
                             stack_status_reason='Remote stack check failed')]

        rsrc = self.create_remote_stack()

        self.heat.stacks.get = mock.MagicMock(side_effect=returns)
        self.heat.actions.resume = mock.MagicMock()
        error = self.assertRaises(exception.ResourceFailure,
                                  scheduler.TaskRunner(rsrc.check))
        error_msg = ('ResourceInError: resources.remote_stack: '
                     'Went to status CHECK_FAILED due to '
                     '"Remote stack check failed"')
        self.assertEqual(error_msg, six.text_type(error))
        self.assertEqual((rsrc.CHECK, rsrc.FAILED), rsrc.state)
        self.heat.actions.check.assert_called_with(stack_id=rsrc.resource_id)

    def test_resume(self):
        stacks = [get_stack(stack_status='RESUME_IN_PROGRESS'),
                  get_stack(stack_status='RESUME_COMPLETE')]

        rsrc = self.create_remote_stack()
        rsrc.action = rsrc.SUSPEND

        self.heat.stacks.get = mock.MagicMock(side_effect=stacks)
        self.heat.actions.resume = mock.MagicMock()
        scheduler.TaskRunner(rsrc.resume)()

        self.assertEqual((rsrc.RESUME, rsrc.COMPLETE), rsrc.state)
        self.heat.actions.resume.assert_called_with(stack_id=rsrc.resource_id)

    def test_resume_failed(self):
        returns = [get_stack(stack_status='RESUME_IN_PROGRESS'),
                   get_stack(stack_status='RESUME_FAILED',
                             stack_status_reason='Remote stack resume failed')]

        rsrc = self.create_remote_stack()
        rsrc.action = rsrc.SUSPEND

        self.heat.stacks.get = mock.MagicMock(side_effect=returns)
        self.heat.actions.resume = mock.MagicMock()
        error = self.assertRaises(exception.ResourceFailure,
                                  scheduler.TaskRunner(rsrc.resume))
        error_msg = ('ResourceInError: resources.remote_stack: '
                     'Went to status RESUME_FAILED due to '
                     '"Remote stack resume failed"')
        self.assertEqual(error_msg, six.text_type(error))
        self.assertEqual((rsrc.RESUME, rsrc.FAILED), rsrc.state)
        self.heat.actions.resume.assert_called_with(stack_id=rsrc.resource_id)

    def test_resume_failed_not_created(self):
        self.initialize()
        rsrc = self.parent['remote_stack']
        rsrc.action = rsrc.SUSPEND
        error = self.assertRaises(exception.ResourceFailure,
                                  scheduler.TaskRunner(rsrc.resume))
        error_msg = ('Error: resources.remote_stack: '
                     'Cannot resume remote_stack, resource not found')
        self.assertEqual(error_msg, six.text_type(error))
        self.assertEqual((rsrc.RESUME, rsrc.FAILED), rsrc.state)

    def test_suspend(self):
        stacks = [get_stack(stack_status='SUSPEND_IN_PROGRESS'),
                  get_stack(stack_status='SUSPEND_COMPLETE')]

        rsrc = self.create_remote_stack()

        self.heat.stacks.get = mock.MagicMock(side_effect=stacks)
        self.heat.actions.suspend = mock.MagicMock()
        scheduler.TaskRunner(rsrc.suspend)()

        self.assertEqual((rsrc.SUSPEND, rsrc.COMPLETE), rsrc.state)
        self.heat.actions.suspend.assert_called_with(stack_id=rsrc.resource_id)

    def test_suspend_failed(self):
        stacks = [get_stack(stack_status='SUSPEND_IN_PROGRESS'),
                  get_stack(stack_status='SUSPEND_FAILED',
                            stack_status_reason='Remote stack suspend failed')]

        rsrc = self.create_remote_stack()

        self.heat.stacks.get = mock.MagicMock(side_effect=stacks)
        self.heat.actions.suspend = mock.MagicMock()
        error = self.assertRaises(exception.ResourceFailure,
                                  scheduler.TaskRunner(rsrc.suspend))
        error_msg = ('ResourceInError: resources.remote_stack: '
                     'Went to status SUSPEND_FAILED due to '
                     '"Remote stack suspend failed"')
        self.assertEqual(error_msg, six.text_type(error))
        self.assertEqual((rsrc.SUSPEND, rsrc.FAILED), rsrc.state)
        # assert suspend was not called
        self.heat.actions.suspend.assert_has_calls([])

    def test_suspend_failed_not_created(self):
        self.initialize()
        rsrc = self.parent['remote_stack']
        # Note: the resource is not created so far
        self.heat.actions.suspend = mock.MagicMock()
        error = self.assertRaises(exception.ResourceFailure,
                                  scheduler.TaskRunner(rsrc.suspend))
        error_msg = ('Error: resources.remote_stack: '
                     'Cannot suspend remote_stack, resource not found')
        self.assertEqual(error_msg, six.text_type(error))
        self.assertEqual((rsrc.SUSPEND, rsrc.FAILED), rsrc.state)
        # assert suspend was not called
        self.heat.actions.suspend.assert_has_calls([])

    def test_update(self):
        stacks = [get_stack(stack_status='UPDATE_IN_PROGRESS'),
                  get_stack(stack_status='UPDATE_COMPLETE')]

        rsrc = self.create_remote_stack()

        props = copy.deepcopy(rsrc.parsed_template()['Properties'])
        props['parameters']['name'] = 'bar'
        update_snippet = rsrc_defn.ResourceDefinition(rsrc.name,
                                                      rsrc.type(),
                                                      props)

        self.heat.stacks.get = mock.MagicMock(side_effect=stacks)
        scheduler.TaskRunner(rsrc.update, update_snippet)()

        self.assertEqual((rsrc.UPDATE, rsrc.COMPLETE), rsrc.state)
        self.assertEqual('bar', rsrc.properties.get('parameters')['name'])
        env = environment.get_child_environment(rsrc.stack.env,
                                                {'name': 'bar'})
        fields = {
            'stack_id': rsrc.resource_id,
            'template': template_format.parse(remote_template),
            'timeout_mins': 60,
            'disable_rollback': True,
            'parameters': {'name': 'bar'},
            'files': self.files,
            'environment': env.user_env_as_dict(),
        }
        self.heat.stacks.update.assert_called_with(**fields)
        self.assertEqual(2, len(self.heat.stacks.get.call_args_list))

    def test_update_with_replace(self):
        rsrc = self.create_remote_stack()

        props = copy.deepcopy(rsrc.parsed_template()['Properties'])
        props['context']['region_name'] = 'RegionOne'
        update_snippet = rsrc_defn.ResourceDefinition(rsrc.name,
                                                      rsrc.type(),
                                                      props)
        self.assertRaises(exception.UpdateReplace,
                          scheduler.TaskRunner(rsrc.update, update_snippet))

    def test_update_failed(self):
        stacks = [get_stack(stack_status='UPDATE_IN_PROGRESS'),
                  get_stack(stack_status='UPDATE_FAILED',
                            stack_status_reason='Remote stack update failed')]

        rsrc = self.create_remote_stack()

        props = copy.deepcopy(rsrc.parsed_template()['Properties'])
        props['parameters']['name'] = 'bar'
        update_snippet = rsrc_defn.ResourceDefinition(rsrc.name,
                                                      rsrc.type(),
                                                      props)

        self.heat.stacks.get = mock.MagicMock(side_effect=stacks)
        error = self.assertRaises(exception.ResourceFailure,
                                  scheduler.TaskRunner(rsrc.update,
                                                       update_snippet))
        error_msg = _('ResourceInError: resources.remote_stack: '
                      'Went to status UPDATE_FAILED due to '
                      '"Remote stack update failed"')
        self.assertEqual(error_msg, six.text_type(error))
        self.assertEqual((rsrc.UPDATE, rsrc.FAILED), rsrc.state)
        self.assertEqual(2, len(self.heat.stacks.get.call_args_list))

    def test_update_no_change(self):
        stacks = [get_stack(stack_status='UPDATE_IN_PROGRESS'),
                  get_stack(stack_status='UPDATE_COMPLETE')]

        rsrc = self.create_remote_stack()

        props = copy.deepcopy(rsrc.parsed_template()['Properties'])
        update_snippet = rsrc_defn.ResourceDefinition(rsrc.name,
                                                      rsrc.type(),
                                                      props)

        self.heat.stacks.get = mock.MagicMock(side_effect=stacks)
        scheduler.TaskRunner(rsrc.update, update_snippet)()
        self.assertEqual((rsrc.UPDATE, rsrc.COMPLETE), rsrc.state)

    def test_remote_stack_refid(self):
        t = template_format.parse(parent_stack_template)
        stack = utils.parse_stack(t)
        rsrc = stack['remote_stack']
        rsrc.resource_id = 'xyz'
        self.assertEqual('xyz', rsrc.FnGetRefId())

    def test_remote_stack_refid_convergence_cache_data(self):
        t = template_format.parse(parent_stack_template)
        cache_data = {'remote_stack': {
            'uuid': mock.ANY,
            'id': mock.ANY,
            'action': 'CREATE',
            'status': 'COMPLETE',
            'reference_id': 'convg_xyz'
        }}
        stack = utils.parse_stack(t, cache_data=cache_data)
        rsrc = stack['remote_stack']
        self.assertEqual('convg_xyz', rsrc.FnGetRefId())

    def test_update_in_check_failed_state(self):
        rsrc = self.create_remote_stack()
        rsrc.state_set(rsrc.CHECK, rsrc.FAILED)

        props = copy.deepcopy(rsrc.parsed_template()['Properties'])
        update_snippet = rsrc_defn.ResourceDefinition(rsrc.name,
                                                      rsrc.type(),
                                                      props)
        self.assertRaises(exception.UpdateReplace,
                          scheduler.TaskRunner(rsrc.update, update_snippet))


text:
/**
 * @fileoverview Start provider sign in handler.
 */

goog.provide('firebaseui.auth.widget.handler.handleProviderSignIn');

goog.require('firebaseui.auth.ui.page.ProviderSignIn');
goog.require('firebaseui.auth.widget.Handler');
goog.require('firebaseui.auth.widget.HandlerName');
goog.require('firebaseui.auth.widget.handler');
goog.require('firebaseui.auth.widget.handler.common');

/**
 * Handles provider sign in.
 *
 * @param {firebaseui.auth.AuthUI} app The current Firebase UI instance whose
 *     configuration is used.
 * @param {Element} container The container DOM element.
 * @param {string=} opt_infoBarMessage The message to show on info bar.
 */
firebaseui.auth.widget.handler.handleProviderSignIn = function(
    app,
    container,
    opt_infoBarMessage) {
  var component = new firebaseui.auth.ui.page.ProviderSignIn(
      function(providerId) {
        // TODO: Consider deleting pending credentials on new sign in.
        if (providerId == firebase.auth.EmailAuthProvider.PROVIDER_ID) {
          // User clicks create password account button.
          component.dispose();
          // Handle sign in with email.
          firebaseui.auth.widget.handler.common.handleSignInWithEmail(
              app, container);
        } else if (providerId ==
                   firebase.auth.PhoneAuthProvider.PROVIDER_ID) {
          // User clicks sign in with phone number button.
          component.dispose();
          // Handle start sign in with phone number.
          firebaseui.auth.widget.handler.handle(
              firebaseui.auth.widget.HandlerName.PHONE_SIGN_IN_START, app,
              container);
        } else {
          // User clicks other IdP.
          firebaseui.auth.widget.handler.common.federatedSignIn(
              /** @type {!firebaseui.auth.AuthUI} */ (app),
              component,
              providerId);
        }
      },
      app.getConfig().getProviders());
  component.render(container);
  // Set current UI component.
  app.setCurrentComponent(component);
  // Show info bar if necessary.
  if (opt_infoBarMessage) {
    component.showInfoBar(opt_infoBarMessage);
  }
};

// Register handler.
firebaseui.auth.widget.handler.register(
    firebaseui.auth.widget.HandlerName.PROVIDER_SIGN_IN,
    /** @type {firebaseui.auth.widget.Handler} */
    (firebaseui.auth.widget.handler.handleProviderSignIn));


text:
package abi44_0_0.host.exp.exponent.modules.api.reanimated;

import abi44_0_0.com.facebook.react.bridge.ReadableArray;
import abi44_0_0.com.facebook.react.bridge.ReadableMap;
import abi44_0_0.com.facebook.react.bridge.ReadableMapKeySetIterator;
import java.util.HashMap;
import java.util.Map;

public class Utils {

  public static Map<String, Integer> processMapping(ReadableMap style) {
    ReadableMapKeySetIterator iter = style.keySetIterator();
    HashMap<String, Integer> mapping = new HashMap<>();
    while (iter.hasNextKey()) {
      String propKey = iter.nextKey();
      int nodeIndex = style.getInt(propKey);
      mapping.put(propKey, nodeIndex);
    }
    return mapping;
  }

  public static int[] processIntArray(ReadableArray ary) {
    int size = ary.size();
    int[] res = new int[size];
    for (int i = 0; i < size; i++) {
      res[i] = ary.getInt(i);
    }
    return res;
  }
}


text:
module DeviseHelper
  def devise_error_messages!
    return '' if resource.errors.empty?
    messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
    sentence = I18n.t('errors.messages.not_saved',
      count: resource.errors.count,
      resource: resource.class.model_name.human.downcase)
    html = <<-HTML

      <button type='button' class='close' data-dismiss='alert'>×Close</button>
      #{sentence}

        #{messages}

    HTML

    html.html_safe
  end
end


text:
[![Build Status](https://travis-ci.org/openc/sqlite_magic.png)](https://travis-ci.org/openc/sqlite_magic)
Experimental abstraction and refactoring of sqlite utility methods from
scraperwiki-ruby gem
Note: Not all functionality has yet been duplicated, and this may not work for
you. Developed and tested on Ruby 1.9.3

## Installation

Add this line to your application's Gemfile:

    gem 'sqlite_magic', :git => 'git@github.com:openc/sqlite_magic.git'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install sqlite_magic

## Usage

TODO: Write usage instructions here

## Changes
* Allow options to be passed when initializing connection (which will be passed to Sqlite)
* insert\_or\_update now defers to #save\_data when hitting error (which caused a problem when missing field)
* busy_timeout can now be set in options

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package me.timhung.dap;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends Activity implements LoaderCallbacks<Cursor> {

    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[]{
            "foo@example.com:hello", "bar@example.com:world"
    };
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;

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

        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();

        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    private void populateAutoComplete() {
        getLoaderManager().initLoader(0, null, this);
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        //Test go to dashboard activity
        startActivity(new Intent(LoginActivity.this, DashboardActivity.class));

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();

//        try{
//            URL url = new URL("http://104.236.92.98:3000/users/" + sha1Converter.SHA1(email));
//            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//            try {
//                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
//                Log.w("JSON from dapapp.me", readStream(in));
//            }
//            finally {
//                urlConnection.disconnect();
//            }
//        }
//        catch(MalformedURLException e){}
//        catch(IOException e){}

//        new RequestTask().execute("http://104.236.92.98:3000/users/" + sha1Converter.SHA1(email));
//        new RequestTask().onPostExecute();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
//            mAuthTask = new UserLoginTask(email, password);
//            mAuthTask.execute((Void) null);

        }

    }

    private boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this,
                // Retrieve data rows for the device user's 'profile' contact.
                Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                        ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

                // Select only email addresses.
                ContactsContract.Contacts.Data.MIMETYPE +
                        " = ?", new String[]{ContactsContract.CommonDataKinds.Email
                .CONTENT_ITEM_TYPE},

                // Show primary email addresses first. Note that there won't be
                // a primary email address if the user hasn't specified one.
                ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<String>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }

        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {

    }

    private interface ProfileQuery {
        String[] PROJECTION = {
                ContactsContract.CommonDataKinds.Email.ADDRESS,
                ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
        };

        int ADDRESS = 0;
        int IS_PRIMARY = 1;
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter =
                new ArrayAdapter<String>(LoginActivity.this,
                        android.R.layout.simple_dropdown_item_1line, emailAddressCollection);

        mEmailView.setAdapter(adapter);
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;
        private final String mPassword;

        UserLoginTask(String email, String password) {
            mEmail = email;
            mPassword = password;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.

            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }

            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the password matches.
                    return pieces[1].equals(mPassword);
                }
            }

            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                finish();
            } else {
                mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }

//    public static Context getAppContext(){
//        return LoginActivity.;
//    }

    private static String readStream(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            Log.e("TAG SHIT", "IOException", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                Log.e("TAG SHIT", "IOException", e);
            }
        }
        return sb.toString();
    }
}


text:
//
//  HP_AnimationUtils.h
//  common4ios
//
//  Created by Yi Xu on 12-10-18.
//  Copyright (c) 2012年 Yi Xu. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

typedef void (^AnimationBlock)();

typedef void (^AnimationCompletionBlock)(BOOL finished);

@interface HP_AnimationUtils : NSObject

/**
 *  旋转X轴
 */
+ (id)rotateXFromValue:(float)fromValue toValue:(float)toValue duration:(float)duration;
/**
 *  旋转Y轴
 */
+ (id)rotateYFromValue:(float)fromValue toValue:(float)toValue duration:(float)duration;
/**
 *  旋转Z轴
 */
+ (id)rotateZFromValue:(float)fromValue toValue:(float)toValue duration:(float)duration;

/**
 *  透明度
 */
+ (void)doAnimationForView:(UIView *)view toAlpha:(float)toAlpha duration:(float)duration;

/**
 *  透明度
 */
+ (void)doAnimationForView:(UIView *)view fromAlpha:(float)fromAlpha toAlpha:(float)toAlpha duration:(float)duration;

/**
 *  位移
 */
+ (void)doAnimationForView:(UIView *)view toX:(float)toX duration:(float)duration;

/**
 *  位移
 */
+ (void)doAnimationForView:(UIView *)view fromX:(float)fromX toX:(float)toX duration:(float)duration;
/**
 *  位移
 */
+ (void)doAnimationForView:(UIView *)view toPoint:(CGPoint)toPoint duration:(float)duration;

/**
 *  位移
 */
+ (void)doAnimationForView:(UIView *)view fromPoint:(CGPoint)fromPoint toPoint:(CGPoint)toPoint duration:(float)duration;

/**
 *  缩放/变形
 */
+(void)doAnimationForView:(UIView *)view toSize:(CGSize)toSize duration:(float)duration;

/**
 *  缩放/变形
 */
+(void)doAnimationForView:(UIView *)view fromSize:(CGSize)fromSize toSize:(CGSize)toSize duration:(float)duration;

/**
 *  自定义
 */
+(void)doAnimationForView:(UIView *)view duration:(float)duration AnimationBlock:(AnimationBlock)AnimationBlock AnimationCompletionBlock:(AnimationCompletionBlock)AnimationCompletionBlock;

@end


text:
package data;

public class Entity{

	private int id;
	private String name;
	private int count = 1;
	private String type;
	private double idf;

	public Entity(String name, String type){
		this.name = name;
		this.type = type;
		this.count = 1;
	}

	@Override
	public String toString()
	{
		return "Entity [name=" + name + ", type=" + type + "]";
	}

	public Entity(String name, String type, String count){
		this.name = name;
		this.type = type;
		this.count = Integer.parseInt(count);
	}

	public Entity(int id, int counter, double idf) {
		this.setId(id);
		this.count = counter;
		this.setIdf(idf);
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public double getIdf() {
		return idf;
	}

	public void setIdf(double idf) {
		this.idf = idf;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
}


text:
<?php

use Illuminate\Database\Seeder;
use gotham\Http\Controllers\MyUtilController;

class UserTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //
        $util = new MyUtilController();

        \gotham\User::create([
            'first_name' => $util->firstlettertoupper('bruce'),
            'last_name' => $util->firstlettertoupper('wayne'),
            'permission_level' => $util->firstlettertoupper('administrators'),
            'account_status' => 'Enabled',
            'email' => 'brucewayne@gotham.local',
            'password' => bcrypt('Gotham1')
        ]);

        $bruce = \gotham\User::find(1);
        $adminGroup = \gotham\Group::where('name', 'Administrators')->first();
        $bruce->groups()->save($adminGroup);

        foreach(\gotham\RFI::get() as $rfi){
            $bruce->rfis()->save($rfi);
        }

        \gotham\User::create([
            'first_name' => $util->firstlettertoupper('robin'),
            'last_name' => $util->firstlettertoupper('johnson'),
            'permission_level' => $util->firstlettertoupper('administrators'),
            'account_status' => 'Enabled',
            'email' => 'robinjohnson@gotham.local',
            'password' => bcrypt('Gotham1')
        ]);

        $bobby = \gotham\User::find(2);
        $bobby->groups()->save($adminGroup);

        for ($x = 1; $x <= 0; $x++) {
            $one = 1;

            $user = factory(gotham\User::class, 1)->create();
            $userGroup = \gotham\Group::where('name', 'Guests')->first();
            $user->groups()->save($userGroup);

            $this->command->info("Created " . number_format($x * $one) ." of " . number_format(1000) . " User records.");
        }
    }
}


text:
FROM node:16-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat

WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile

# 2. Rebuild the source code only when needed
FROM node:16-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# This will do the trick, use the corresponding env file for each environment.
COPY .env.development.sample .env.production
RUN yarn build

# 3. Production image, copy all the files and run next
FROM node:16-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# You only need to copy next.config.js if you are NOT using the default configuration
# COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000

CMD ["node", "server.js"]


text:
<?php

namespace Cysha\Casino\Holdem\Tests\Exceptions;

use Cysha\Casino\Game\Chips;
use Cysha\Casino\Holdem\Exceptions\RoundException;
use PHPUnit_Framework_TestCase;

class RoundExceptionTest extends PHPUnit_Framework_TestCase
{
    /** @test */
    public function the_flop_has_been_dealt_can_accept_custom_messages()
    {
        $expectedException = new RoundException('custom message');
        $this->assertEquals($expectedException, RoundException::flopHasBeenDealt('custom message'));
    }

    /** @test */
    public function the_turn_has_been_dealt_can_accept_custom_messages()
    {
        $expectedException = new RoundException('custom message');
        $this->assertEquals($expectedException, RoundException::turnHasBeenDealt('custom message'));
    }

    /** @test */
    public function the_river_has_been_dealt_can_accept_custom_messages()
    {
        $expectedException = new RoundException('custom message');
        $this->assertEquals($expectedException, RoundException::riverHasBeenDealt('custom message'));
    }

    /** @test */
    public function the_invalid_button_position_can_accept_custom_messages()
    {
        $expectedException = new RoundException('custom message');
        $this->assertEquals($expectedException, RoundException::invalidButtonPosition('custom message'));
    }

    /** @test */
    public function cant_check_with_bet_active_can_accept_custom_messages()
    {
        $expectedException = new RoundException('custom message');
        $this->assertEquals($expectedException, RoundException::cantCheckWithBetActive('custom message'));
    }

    /** @test */
    public function cant_raise_lower_amount_than_highest_bet_custom_message()
    {
        $expectedException = new RoundException('custom message');
        $raise = Chips::fromAmount(10);
        $bet = Chips::fromAmount(20);
        $this->assertEquals($expectedException, RoundException::raiseNotHighEnough($raise, $bet, 'custom message'));
    }
}


text:
Start Crossbar.io using

```
make crossbar_standalone
```

and run a client (from a new terminal) using

```
make client_good
```

To run a client that fails to authenticate successfully:

```
make client_bad
```

These tests are also integrated into the automated CI tests for WAMP-Authentication:

```
cd crossbar-examples/authentication
make test_all
```

![WAMP authentication test results](auth-tests-results.png "WAMP authentication test results")

## Test Accounts

All key pairs, both WAMP-Cryptosign and Ethereum, for this demo are generated from one seedphrase defined in the [Makefile](Makefile)

```python
seedphrase = "avocado style uncover thrive same grace crunch want essay reduce current edge"
```

From this seedphrase, an in-memory security module with multiple Ethereum and WAMP-Cryptosign keys can be created:

```python
sm: SecurityModuleMemory = SecurityModuleMemory.from_seedphrase(seedphrase, num_eth_keys=10, num_cs_keys=6)
await sm.open()
```

The 16 keys (asymmetric key pairs of private and public keys) generated in the security module for this demo are 10 Ethereum keys and 6 Cryptosign keys:

| Key No.     | Key Type    | Variable            | Usage                     | Authority
|-------------|-------------|---------------------|---------------------------|------------------
| 0           | Ethereum    | -                   | *unused*                  | -
| 1           | Ethereum    | `root_ca1_ekey`     | Root CA Owner             | **User 1**
| 2           | Ethereum    | `relay_ca1_ekey`    | Relay CA Owner            | User 2
| 3           | Ethereum    | `relay_ca2_ekey`    | Relay CA Owner            | User 3
| 4           | Ethereum    | `gateway_ca1_ekey`  | Gateway CA Owner          | User 4
| 5           | Ethereum    | `gateway_ca2_ekey`  | Gateway CA Owner          | User 5
| 6           | Ethereum    | `relay_ep1_ekey`    | Relay Endpoint            | User 2
| 7           | Ethereum    | `relay_ep2_ekey`    | Relay Endpoint            | User 3
| 8           | Ethereum    | `gateway_ep1_ekey`  | Gateway Endpoint          | User 4
| 9           | Ethereum    | `gateway_ep2_ekey`  | Gateway Endpoint          | User 5
| 10          | Cryptosign  | `relay_dl1_ckey`    | Relay Node                | User 2
| 11          | Cryptosign  | `relay_dl2_ckey`    | Relay Node                | User 3
| 12          | Cryptosign  | `gateway_dl1_ckey`  | Gateway Node              | User 4
| 13          | Cryptosign  | `gateway_dl2_ckey`  | Gateway Node              | User 5
| 14          | Cryptosign  | -                   | *unused*                  | -
| 15          | Cryptosign  | -                   | *unused*                  | -

The keys can be accessed from the security module using the *Key No.*:

```python
# Ethereum key pair used to sign the root CA certificate with
root_ca1_ekey: EthereumKey = sm[1]
```

and used to sign certificates

```python
# create and sign root CA certificate
certificate = EIP712AuthorityCertificate(...)
signature = await cert.sign(root_ca1_ekey, binary=True)
```

## Test Certificates

To create a new self-signed *Root CA Certificate* you can use the included script [generate_certificates.py](generate_certificates.py)

```console
(cpy39_1) (base) oberstet@intel-nuci7:~/scm/crossbario/crossbar-examples/authentication/cryptosign/trustroot$ make generate_certificates
python generate_certificates.py --debug \
	--seedphrase="avocado style uncover thrive same grace crunch want essay reduce current edge" \
	--realm=0x72b3486d38E9f49215b487CeAaDF27D6acf22115 \
	--outdir=./.crossbar/
2022-08-10T23:43:27+0200 EIP712AuthorityCertificate issued by 0xf5173a6111B2A6B3C20fceD53B2A8405EC142bF6 for subject 0xf5173a6111B2A6B3C20fceD53B2A8405EC142bF6 saved to "./.crossbar/root_ca1.crt"
2022-08-10T23:43:27+0200 EIP712AuthorityCertificate issued by 0xf5173a6111B2A6B3C20fceD53B2A8405EC142bF6 for subject 0xecdb40C2B34f3bA162C413CC53BA3ca99ff8A047 saved to "./.crossbar/relay_ca1.crt"
2022-08-10T23:43:27+0200 EIP712AuthorityCertificate issued by 0xecdb40C2B34f3bA162C413CC53BA3ca99ff8A047 for subject 0xeD22Fd82230B613a638e09E90dfBFeE6d604D3D2 saved to "./.crossbar/relay_ep1.crt"
2022-08-10T23:43:27+0200 Main loop terminated.
```

This will use the provided BIP-39 seedphrase ("Mnemonic") to generate security module keys from (both Ethereum and Cryptosign).
The index within these auto-generated (Ethereum) key which we will use is specified using `--keyno=0`.
The certificate will have an `issuer` with address matching this key, and since we generate a Root CA certificate, the
certificate will be self-signed, and hence `subject` will match that same address.

To read certificate files and print information from the loaded certificates:

```
(cpy39_1) (base) oberstet@intel-nuci7:~/scm/crossbario/crossbar-examples/authentication/cryptosign/trustroot$ make print_certificates
python print_certificates.py
Loaded certificate with hash a695cbb338aebc7ee66826251bb2df46996b9d50d36317141a3d9f161316e836 by issuer 0xecdb40C2B34f3bA162C413CC53BA3ca99ff8A047 with 1 signatures:

{'domain': {'name': 'WMP', 'version': '1'},
 'message': {'capabilities': 12,
             'chainId': 1,
             'issuer': '0xecdb40C2B34f3bA162C413CC53BA3ca99ff8A047',
             'meta': '',
             'realm': '0x72b3486d38E9f49215b487CeAaDF27D6acf22115',
             'subject': '0xeD22Fd82230B613a638e09E90dfBFeE6d604D3D2',
             'validFrom': 15321256,
             'verifyingContract': '0xf766Dc789CF04CD18aE75af2c5fAf2DA6650Ff57'},
 'primaryType': 'EIP712AuthorityCertificate',
 'types': {'EIP712AuthorityCertificate': [{'name': 'chainId',
                                           'type': 'uint256'},
                                          {'name': 'verifyingContract',
                                           'type': 'address'},
                                          {'name': 'validFrom',
                                           'type': 'uint256'},
                                          {'name': 'issuer', 'type': 'address'},
                                          {'name': 'subject',
                                           'type': 'address'},
                                          {'name': 'realm', 'type': 'address'},
                                          {'name': 'capabilities',
                                           'type': 'uint64'},
                                          {'name': 'meta', 'type': 'string'}],
           'EIP712Domain': [{'name': 'name', 'type': 'string'},
                            {'name': 'version', 'type': 'string'}]}}

Loaded certificate with hash ce21b90a2cb3f043383283c611bd435e8a1f1beea4b171ee652aff3576a74421 by issuer 0xf5173a6111B2A6B3C20fceD53B2A8405EC142bF6 with 1 signatures:

{'domain': {'name': 'WMP', 'version': '1'},
 'message': {'capabilities': 62,
             'chainId': 1,
             'issuer': '0xf5173a6111B2A6B3C20fceD53B2A8405EC142bF6',
             'meta': '',
             'realm': '0x72b3486d38E9f49215b487CeAaDF27D6acf22115',
             'subject': '0xecdb40C2B34f3bA162C413CC53BA3ca99ff8A047',
             'validFrom': 15321256,
             'verifyingContract': '0xf766Dc789CF04CD18aE75af2c5fAf2DA6650Ff57'},
 'primaryType': 'EIP712AuthorityCertificate',
 'types': {'EIP712AuthorityCertificate': [{'name': 'chainId',
                                           'type': 'uint256'},
                                          {'name': 'verifyingContract',
                                           'type': 'address'},
                                          {'name': 'validFrom',
                                           'type': 'uint256'},
                                          {'name': 'issuer', 'type': 'address'},
                                          {'name': 'subject',
                                           'type': 'address'},
                                          {'name': 'realm', 'type': 'address'},
                                          {'name': 'capabilities',
                                           'type': 'uint64'},
                                          {'name': 'meta', 'type': 'string'}],
           'EIP712Domain': [{'name': 'name', 'type': 'string'},
                            {'name': 'version', 'type': 'string'}]}}

Loaded certificate with hash 442f7ba7960a43a71dd37e7793d99d668dce82384f87a7be4bbd358cb52d5f14 by issuer 0xf5173a6111B2A6B3C20fceD53B2A8405EC142bF6 with 1 signatures:

{'domain': {'name': 'WMP', 'version': '1'},
 'message': {'capabilities': 63,
             'chainId': 1,
             'issuer': '0xf5173a6111B2A6B3C20fceD53B2A8405EC142bF6',
             'meta': '',
             'realm': '0x72b3486d38E9f49215b487CeAaDF27D6acf22115',
             'subject': '0xf5173a6111B2A6B3C20fceD53B2A8405EC142bF6',
             'validFrom': 15321256,
             'verifyingContract': '0xf766Dc789CF04CD18aE75af2c5fAf2DA6650Ff57'},
 'primaryType': 'EIP712AuthorityCertificate',
 'types': {'EIP712AuthorityCertificate': [{'name': 'chainId',
                                           'type': 'uint256'},
                                          {'name': 'verifyingContract',
                                           'type': 'address'},
                                          {'name': 'validFrom',
                                           'type': 'uint256'},
                                          {'name': 'issuer', 'type': 'address'},
                                          {'name': 'subject',
                                           'type': 'address'},
                                          {'name': 'realm', 'type': 'address'},
                                          {'name': 'capabilities',
                                           'type': 'uint64'},
                                          {'name': 'meta', 'type': 'string'}],
           'EIP712Domain': [{'name': 'name', 'type': 'string'},
                            {'name': 'version', 'type': 'string'}]}}

(cpy39_1) (base) oberstet@intel-nuci7:~/scm/crossbario/crossbar-examples/authentication/cryptosign/trustroot$
```

## Standalone Trustroots

A complete Crossbar.io node configuration using *Standalone Trustroots* can be found [here](.crossbar/config-standalone-trustroot.json).

This example configures one realm

* `realm1`

and a WebSocket listening transport with an authentication item `auth` for *WAMP-Cryptosign*

```json
{
    "cryptosign": {
        "type": "static",
        "trustroots": {
            "realm1": {
                "certificate": "root_ca1.crt"
            }
        }
    }
}
```

The `trustroots` item for `cryptosign` configures a map from realm names (here only `realm1`) to files with WAMP EIP712  *Root CA Certificates*

* `root_ca1.crt`

These certificate filenames are relative to the Crossbar.io node directory (`.crossbar`), and are binary files which contain the CBOR serialized certificate and signature `[certificate, signature]`.

## Shared Trustroots

Write me.


text:
package com.pie.tlatoani.WebSocket;

import ch.njol.skript.lang.Effect;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;

import java.util.Optional;

/**
 * Created by Tlatoani on 5/5/17.
 */
public class EffStartWebSocketServer extends Effect {
    private Expression<String> idExpr;
    private Expression<Number> portExpr;

    @Override
    protected void execute(Event event) {
        String id = idExpr.getSingle(event);
        Integer port = Optional.ofNullable(portExpr.getSingle(event)).map(Number::intValue).orElse(null);
        if (id != null && port != null) {
            WebSocketManager.startServer(portExpr.getSingle(event).intValue(), idExpr.getSingle(event));
        }
    }

    @Override
    public String toString(Event event, boolean b) {
        return "start websocket server " + idExpr + " at port " + portExpr;
    }

    @Override
    public boolean init(Expression<?>[] expressions, int i, Kleenean kleenean, SkriptParser.ParseResult parseResult) {
        idExpr = (Expression<String>) expressions[0];
        portExpr = (Expression<Number>) expressions[1];
        return true;
    }
}


text:
package com.Da_Technomancer.crossroads.tileentities.magic;

import com.Da_Technomancer.crossroads.API.Capabilities;
import com.Da_Technomancer.crossroads.API.IAdvancedRedstoneHandler;
import com.Da_Technomancer.crossroads.API.Properties;
import com.Da_Technomancer.crossroads.API.magic.*;
import com.Da_Technomancer.crossroads.API.packets.IIntReceiver;
import com.Da_Technomancer.crossroads.blocks.ModBlocks;
import com.Da_Technomancer.crossroads.items.ModItems;
import com.Da_Technomancer.crossroads.items.itemSets.OreSetup;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumFacing.Axis;
import net.minecraft.util.EnumFacing.AxisDirection;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import org.apache.commons.lang3.tuple.Triple;

import javax.annotation.Nullable;
import java.awt.*;

public class LensHolderTileEntity extends BeamRenderTEBase implements IIntReceiver{

	private Triple<Color, Integer, Integer> trip;
	private Triple<Color, Integer, Integer> tripUp;

	@Override
	public void refresh(){
		if(beamerUp != null){
			beamerUp.emit(null, world);
		}
		if(beamer != null){
			beamer.emit(null, world);
		}
	}

	@Override
	@Nullable
	public MagicUnit[] getLastFullSent(){
		return new MagicUnit[] {beamer == null ? null : beamer.getLastFullSent(), beamerUp == null ? null : beamerUp.getLastFullSent()};
	}

	private double lastRedstone;

	public double getRedstone(){
		return lastRedstone;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Triple<Color, Integer, Integer>[] getBeam(){
		if(world.getBlockState(pos).getBlock() != ModBlocks.lensHolder){
			return null;
		}
		Triple<Color, Integer, Integer>[] out = new Triple[6];
		out[EnumFacing.getFacingFromAxis(AxisDirection.POSITIVE, world.getBlockState(pos).getValue(Properties.ORIENT) ? Axis.X : Axis.Z).getIndex()] = tripUp;
		out[EnumFacing.getFacingFromAxis(AxisDirection.NEGATIVE, world.getBlockState(pos).getValue(Properties.ORIENT) ? Axis.X : Axis.Z).getIndex()] = trip;
		return out;
	}

	private BeamManager beamer;
	private BeamManager beamerUp;

	@Override
	public void receiveInt(int identifier, int message, EntityPlayerMP player){
		if(identifier < 6 && identifier > 1){
			if(EnumFacing.getFront(identifier).getAxisDirection() == AxisDirection.NEGATIVE){
				trip = BeamManager.getTriple(message);
			}else{
				tripUp = BeamManager.getTriple(message);
			}
		}
	}

	private int memTrip;
	private int memTripUp;

	@Override
	public NBTTagCompound getUpdateTag(){
		NBTTagCompound nbt = super.getUpdateTag();
		nbt.setInteger("beam", memTrip);
		nbt.setInteger("beamUp", memTripUp);
		return nbt;
	}

	@Override
	public NBTTagCompound writeToNBT(NBTTagCompound nbt){
		super.writeToNBT(nbt);
		nbt.setInteger("memTrip", beamer == null ? 0 : beamer.getPacket());
		nbt.setInteger("memTripUp", beamerUp == null ? 0 : beamerUp.getPacket());
		nbt.setDouble("reds", lastRedstone);
		return nbt;
	}

	@Override
	public void readFromNBT(NBTTagCompound nbt){
		super.readFromNBT(nbt);
		memTrip = nbt.getInteger("memTrip");
		memTripUp = nbt.getInteger("memTripUp");
		lastRedstone = nbt.getDouble("reds");
		if(nbt.hasKey("beam")){
			trip = BeamManager.getTriple(nbt.getInteger("beam"));
		}
		if(nbt.hasKey("beamUp")){
			tripUp = BeamManager.getTriple(nbt.getInteger("beamUp"));
		}
	}

	@Override
	public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newState){
		return ModBlocks.lensHolder != newState.getBlock();
	}

	private final IMagicHandler magicHandler = new MagicHandler(AxisDirection.NEGATIVE);
	private final IMagicHandler magicHandlerNeg = new MagicHandler(AxisDirection.POSITIVE);
	private final IItemHandler lensHandler = new LensHandler();
	private final RedstoneHandler redstoneHandler = new RedstoneHandler();

	@Override
	public boolean hasCapability(Capability<?> cap, EnumFacing side){
		if(cap == Capabilities.MAGIC_HANDLER_CAPABILITY && (side == null || (world.getBlockState(pos).getValue(Properties.ORIENT) ? side.getAxis() == Axis.X : side.getAxis() == Axis.Z))){
			return true;
		}
		if(cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || cap == Capabilities.ADVANCED_REDSTONE_HANDLER_CAPABILITY){
			return true;
		}

		return super.hasCapability(cap, side);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T getCapability(Capability<T> cap, EnumFacing side){
		if(cap == Capabilities.MAGIC_HANDLER_CAPABILITY && (side == null || (world.getBlockState(pos).getValue(Properties.ORIENT) ? side.getAxis() == Axis.X : side.getAxis() == Axis.Z))){
			return side == null || side.getAxisDirection() == AxisDirection.POSITIVE ? (T) magicHandler : (T) magicHandlerNeg;
		}
		if(cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY){
			return (T) lensHandler;
		}
		if(cap == Capabilities.ADVANCED_REDSTONE_HANDLER_CAPABILITY){
			return (T) redstoneHandler;
		}

		return super.getCapability(cap, side);
	}

	private class RedstoneHandler implements IAdvancedRedstoneHandler{

		@Override
		public double getOutput(boolean read){
			return read ? lastRedstone : 0;
		}
	}

	private class MagicHandler implements IMagicHandler{

		private final AxisDirection dir;

		private MagicHandler(AxisDirection dir){
			this.dir = dir;
		}

		@Override
		public void setMagic(MagicUnit mag){
			if(beamer == null || beamerUp == null){
				beamer = new BeamManager(EnumFacing.getFacingFromAxis(AxisDirection.NEGATIVE, world.getBlockState(pos).getValue(Properties.ORIENT) ? Axis.X : Axis.Z), pos);
				beamerUp = new BeamManager(EnumFacing.getFacingFromAxis(AxisDirection.POSITIVE, world.getBlockState(pos).getValue(Properties.ORIENT) ? Axis.X : Axis.Z), pos);
			}

			if(mag != null && mag.getVoid() != 0 && world.getBlockState(pos).getValue(Properties.TEXTURE_7) != 0){
				world.setBlockState(pos, world.getBlockState(pos).withProperty(Properties.TEXTURE_7, 0));
				(dir == AxisDirection.POSITIVE ? beamerUp : beamer).emit(mag, world);
				lastRedstone = Math.max(beamer.getLastSent() == null ? 0 : ((double) beamer.getLastSent().getPower()), beamerUp.getLastSent() == null ? 0 : ((double) beamerUp.getLastSent().getPower()));
				markDirty();
				return;
			}

			switch(world.getBlockState(pos).getValue(Properties.TEXTURE_7)){
				case 0:
					(dir == AxisDirection.POSITIVE ? beamerUp : beamer).emit(mag, world);
					break;
				case 1:
					(dir == AxisDirection.POSITIVE ? beamerUp : beamer).emit(mag == null || mag.getEnergy() == 0 ? null : new MagicUnit(mag.getEnergy(), 0, 0, 0), world);
					break;
				case 2:
					(dir == AxisDirection.POSITIVE ? beamerUp : beamer).emit(mag == null || mag.getPotential() == 0 ? null : new MagicUnit(0, mag.getPotential(), 0, 0), world);
					break;
				case 3:
					(dir == AxisDirection.POSITIVE ? beamerUp : beamer).emit(mag == null || mag.getStability() == 0 ? null : new MagicUnit(0, 0, mag.getStability(), 0), world);
					break;
				case 4:
					if(EnumMagicElements.getElement(mag) == EnumMagicElements.LIGHT){
						world.setBlockState(pos, ModBlocks.lensHolder.getDefaultState().withProperty(Properties.ORIENT, world.getBlockState(pos).getValue(Properties.ORIENT)).withProperty(Properties.TEXTURE_7, 5));
					}
					(dir == AxisDirection.POSITIVE ? beamerUp : beamer).emit(mag, world);
					break;
				case 5:
					(dir == AxisDirection.POSITIVE ? beamerUp : beamer).emit(mag, world);
					break;
				case 6:
					(dir == AxisDirection.POSITIVE ? beamerUp : beamer).emit(mag == null || EnumMagicElements.getElement(mag) != EnumMagicElements.RIFT ? null : new MagicUnit(0, 0, 0, mag.getPower()), world);
					break;
			}

			lastRedstone = Math.max(beamer.getLastSent() == null ? 0 : beamer.getLastSent().getPower(), beamerUp.getLastSent() == null ? 0 : beamerUp.getLastSent().getPower());
			markDirty();
		}
	}

	private class LensHandler implements IItemHandler{

		private ItemStack getLens(){
			switch(world.getBlockState(pos).getValue(Properties.TEXTURE_7)){
				case 0:
					return ItemStack.EMPTY;
				case 1:
					return new ItemStack(OreSetup.gemRuby, 1);
				case 2:
					return new ItemStack(Items.EMERALD, 1);
				case 3:
					return new ItemStack(Items.DIAMOND, 1);
				case 4:
					return new ItemStack(ModItems.pureQuartz, 1);
				case 5:
					return new ItemStack(ModItems.luminescentQuartz, 1);
				default:
					return ItemStack.EMPTY;
			}
		}

		@Override
		public int getSlots(){
			return 1;
		}

		@Override
		public ItemStack getStackInSlot(int slot){
			return slot == 0 ? getLens() : ItemStack.EMPTY;
		}

		@Override
		public ItemStack insertItem(int slot, ItemStack stack, boolean simulate){
			if(slot != 0 || !getLens().isEmpty() || stack.isEmpty() || (stack.getItem() != Items.DIAMOND && stack.getItem() != Items.EMERALD && stack.getItem() != ModItems.pureQuartz && stack.getItem() != OreSetup.gemRuby)){
				return stack;
			}

			if(!simulate){
				world.setBlockState(pos, ModBlocks.lensHolder.getDefaultState().withProperty(Properties.ORIENT, world.getBlockState(pos).getValue(Properties.ORIENT)).withProperty(Properties.TEXTURE_7, stack.getItem() == ModItems.pureQuartz ? 4 : stack.getItem() == Items.EMERALD ? 2 : stack.getItem() == Items.DIAMOND ? 3 : 1));
				markDirty();
			}

			return stack.getCount() - 1 <= 0 ? ItemStack.EMPTY : new ItemStack(stack.getItem(), stack.getCount() - 1);
		}

		@Override
		public ItemStack extractItem(int slot, int amount, boolean simulate){
			if(slot != 0 || amount < 1 || getLens() == ItemStack.EMPTY){
				return ItemStack.EMPTY;
			}
			ItemStack holder = getLens();
			if(!simulate){
				world.setBlockState(pos, ModBlocks.lensHolder.getDefaultState().withProperty(Properties.ORIENT, world.getBlockState(pos).getValue(Properties.ORIENT)).withProperty(Properties.TEXTURE_7, 0));
				markDirty();
			}
			return holder;
		}

		@Override
		public int getSlotLimit(int slot){
			return slot == 0 ? 1 : 0;
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
						http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sivalabs</groupId>
	<artifactId>springboot-actuator-demo</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.1.RELEASE</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.hateoas</groupId>
			<artifactId>spring-hateoas</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-actuator-docs</artifactId>
		</dependency>
		<dependency>
		   <groupId>org.springframework.boot</groupId>
		   <artifactId>spring-boot-starter-remote-shell</artifactId>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>