text:
var path = require('path');
var __path__ = path.join(__dirname, '../../src/js/components/Chart');

var GrommetTestUtils = require('../../src/utils/test/GrommetTestUtils');
var expect = require('expect');

var testSeries = [
  {
    label: 'ascending',
    values: [[3, 3], [2, 2], [1, 1]],
    colorIndex: "graph-1"
  },
  {
    label: 'descending',
    values: [[3, 1], [2, 2], [1, 3]],
    colorIndex: "graph-2"
  },
  {
    label: 'peak',
    values: [[3, 1], [2, 2], [1, 1]],
    colorIndex: "graph-3"
  }
];

var testXAxis = [
  {value: 1, label: 'one'},
  {value: 2, label: 'two'},
  {value: 3, label: 'three'}
];

describe('Grommet Chart', function() {
  it('loads an empty Chart', function() {
    var Component = GrommetTestUtils.getComponent(__path__, undefined, {
      series: []
    });

    GrommetTestUtils.componentShouldExist(Component, 'chart');

    var React = require('react/addons');
    var TestUtils = React.addons.TestUtils;
    var linePaths = TestUtils.scryRenderedDOMComponentsWithClass(Component,
                      'chart__values-line');

    expect(linePaths.length).toBe(0);
  });

  it('loads a line Chart', function() {
    var Component = GrommetTestUtils.getComponent(__path__, undefined, {
      series: testSeries
    });

    GrommetTestUtils.componentShouldExist(Component, 'chart');

    var React = require('react/addons');
    var TestUtils = React.addons.TestUtils;
    var linePaths = TestUtils.scryRenderedDOMComponentsWithClass(Component,
                      'chart__values-line');

    expect(linePaths.length).toBe(3);
  });

  it('loads a line Chart with threshold, min, max, small', function() {
    var Component = GrommetTestUtils.getComponent(__path__, undefined, {
      series: testSeries,
      threshold: 1,
      min: 0,
      max: 10,
      small: true
    });

    GrommetTestUtils.componentShouldExist(Component, 'chart');

    var React = require('react/addons');
    var TestUtils = React.addons.TestUtils;
    var linePaths = TestUtils.scryRenderedDOMComponentsWithClass(Component,
                      'chart__threshold');

    expect(linePaths.length).toBe(1);
  });

  it('loads a line Chart with legend, xAxis, large, important', function() {
    var Component = GrommetTestUtils.getComponent(__path__, undefined, {
      series: testSeries,
      legend: true,
      xAxis: testXAxis,
      large: true,
      important: 1
    });

    GrommetTestUtils.componentShouldExist(Component, 'chart');
    GrommetTestUtils.componentShouldExist(Component, 'chart__legend');

    var React = require('react/addons');
    var TestUtils = React.addons.TestUtils;
    var xAxis = TestUtils.scryRenderedDOMComponentsWithClass(Component,
                      'chart__xaxis-index');

    expect(xAxis.length).toBe(3);
  });

  it('loads an area Chart', function() {
    var Component = GrommetTestUtils.getComponent(__path__, undefined, {
      series: testSeries,
      type: 'area'
    });

    GrommetTestUtils.componentShouldExist(Component, 'chart');

    var React = require('react/addons');
    var TestUtils = React.addons.TestUtils;
    var areaPaths = TestUtils.scryRenderedDOMComponentsWithClass(Component,
                      'chart__values-area');

    expect(areaPaths.length).toBe(3);
  });

  it('loads a smooth area Chart', function() {
    var Component = GrommetTestUtils.getComponent(__path__, undefined, {
      series: testSeries,
      type: 'area',
      smooth: true
    });

    GrommetTestUtils.componentShouldExist(Component, 'chart');

    var React = require('react/addons');
    var TestUtils = React.addons.TestUtils;
    var areaPaths = TestUtils.scryRenderedDOMComponentsWithClass(Component,
                      'chart__values-area');

    expect(areaPaths.length).toBe(3);
  });

  it('loads a bar Chart', function() {
    var Component = GrommetTestUtils.getComponent(__path__, undefined, {
      series: testSeries,
      type: 'bar'
    });

    GrommetTestUtils.componentShouldExist(Component, 'chart');

    var React = require('react/addons');
    var TestUtils = React.addons.TestUtils;
    var areaPaths = TestUtils.scryRenderedDOMComponentsWithClass(Component,
                      'chart__values-bar');

    expect(areaPaths.length).toBe(9);
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2015 Bernd Busse
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<resources>

    <string name="app_name">HMINTP - Measuring Device</string>

    <!-- MenuItem titles -->
    <string name="menu_item_help">Help</string>
    <string name="menu_item_about">About</string>
    <string name="menu_action_share">Share</string>

    <!-- SplashFragment texts -->
    <string name="splash_text_title">How much I need to poop measuring device</string>
    <string name="splash_banner_start">Startup</string>
    <string name="splash_button_start">Start Measure!</string>

    <!-- InputFragment texts -->
    <string name="input_label_header">Following data is necessary:</string>
    <string name="input_divider_desc">Divider</string>

    <string name="input_label_lasttime">How long ago did you poop?</string>
    <string name="input_hint_lasttime">in hours</string>
    <string name="input_label_masseaten">How much did you eat?</string>
    <string name="input_hint_masseaten">in gram</string>
    <string name="input_label_bodymass">How much do you weight?</string>
    <string name="input_hint_bodymass">in kilogram</string>

    <string name="input_button_calculate">Calculate!</string>

    <!-- ResultFragment texts -->
    <string name="result_wait">Calculate Energydensity…</string>
    <string name="result_empty">0.0 kDoil</string>
    <string name="result_nolevel">Nothing, absolutely nothing!</string>

    <!-- DialogFragment titles / Button titles -->
    <string name="dialog_help_title">Help</string>
    <string name="dialog_about_title">About</string>
    <string name="dialog_error_title">Error</string>
    <string name="dialog_info_title">Info</string>
    <string name="dialog_close">Close</string>
    <string name="dialog_info">Info</string>

    <!-- ShareAction texts -->
    <string name="share_name">How much I need to poop</string>
    <string name="share_msg_value">Measured the need to poop of about %1$s kDoil.</string>
    <string name="share_msg_low">That\'s %1$s.</string>
    <string name="share_msg_mid">WOW!!! %1$s</string>
    <string name="share_msg_high">Our independent assessment: \"%1$s\"</string>

    <string name="msg_error_missing_input">Error: Please insert all values.</string>

    <!-- ResultFragment level names -->
    <string-array name="result_levels">
        <item>Unharmful</item>
        <item>Hefty</item>
        <item>Really big turd!</item>
        <item>Fasten your seatbelts!</item>
        <item>Analdetonation!!!</item>
        <item>Unbelievable shitstorm!</item>
        <item>Are you kidding me???</item>
    </string-array>

    <!-- SplashFragment messages -->
    <string-array name="splash_messages">
        <item>Initialize Device…</item>
        <item>Start Darm-Uplink…</item>
        <item>Load Graphics…</item>
        <item>Search Toiletpaper…</item>
        <item>Finished Loading!</item>
    </string-array>

    <!-- ErrorDialog titles -->
    <string-array name="dialog_error_titles">
        <item>Error 500</item>
        <item>Error 027</item>
        <item>Error 400</item>
        <item>Error 404</item>
    </string-array>

    <!-- ErrorDialog messages -->
    <string-array name="dialog_error_messages">
        <item>Internal Runtimeerror!</item>
        <item>Darm-Uplink faulty"</item>
        <item>Found version for blind men!</item>
        <item>Toiletpaper not found!</item>
    </string-array>

</resources>

redpajama_set_name: RedPajamaGithub


text:
Package.describe({
  name: 'liberation:reactive-var-unset',
  summary: 'Adds a method "unset" to ReactiveVar',
  version: '1.0.0',
  git: 'https://github.com/dolgarev/reactive-var-unset.git'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0');
  api.use('reactive-var');
  api.addFiles('unset.js', 'client');
});


text:
from __future__ import unicode_literals

import django
from django.test import TestCase
from mock import MagicMock, patch

from job.configuration.data.data_file import AbstractDataFileStore
from job.configuration.interface.scale_file import ScaleFileDescription
from recipe.configuration.data.exceptions import InvalidRecipeData
from recipe.configuration.data.recipe_data import LegacyRecipeData
from storage.test import utils as storage_utils

class DummyDataFileStore(AbstractDataFileStore):

    def get_workspaces(self, workspace_ids):
        results = {}
        if 1 in workspace_ids:
            results[long(1)] = True
        if 3 in workspace_ids:
            results[long(3)] = False
        return results

    def store_files(self, files, input_file_ids, job_exe):
        pass

class TestRecipeDataAddInputToData(TestCase):

    def setUp(self):
        django.setup()

    def test_successful_file(self):
        """Tests calling RecipeData.add_input_to_data() successfully with a file parameter"""

        recipe_input_name = 'foo'
        file_id = 1337
        job_input_name = 'bar'

        recipe_data = LegacyRecipeData({'input_data': [{'name': recipe_input_name, 'file_id': file_id}]})
        job_data = MagicMock()

        recipe_data.add_input_to_data(recipe_input_name, job_data, job_input_name)
        job_data.add_file_input.assert_called_with(job_input_name, file_id)

    def test_successful_file_list(self):
        """Tests calling RecipeData.add_input_to_data() successfully with a file list parameter"""

        recipe_input_name = 'foo'
        file_ids = [1, 2, 3, 4]
        job_input_name = 'bar'

        recipe_data = LegacyRecipeData({'input_data': [{'name': recipe_input_name, 'file_ids': file_ids}]})
        job_data = MagicMock()

        recipe_data.add_input_to_data(recipe_input_name, job_data, job_input_name)
        job_data.add_file_list_input.assert_called_with(job_input_name, file_ids)

    def test_successful_property(self):
        """Tests calling RecipeData.add_input_to_data() successfully with a property parameter"""

        recipe_input_name = 'foo'
        value = 'Doctor Who?'
        job_input_name = 'bar'

        recipe_data = LegacyRecipeData({'input_data': [{'name': recipe_input_name, 'value': value}]})
        job_data = MagicMock()

        recipe_data.add_input_to_data(recipe_input_name, job_data, job_input_name)
        job_data.add_property_input.assert_called_with(job_input_name, value)

class TestRecipeDataInit(TestCase):

    def setUp(self):
        django.setup()

    def test_init_blank(self):
        """Tests calling RecipeData constructor with blank JSON."""

        # No exception is success
        LegacyRecipeData({})

    def test_init_bad_version(self):
        """Tests calling RecipeData constructor with bad version number."""

        data = {'version': 'BAD VERSION'}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData, data)

    def test_init_no_input_name(self):
        """Tests calling RecipeData constructor with missing data input name."""

        data = {'input_data': [{'value': '1'}]}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData, data)

    def test_init_duplicate_input_name(self):
        """Tests calling RecipeData constructor with duplicate data input name."""

        data = {'input_data': [{'name': 'My Name', 'value': '1'},
                                {'name': 'My Name', 'value': '1'}]}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData, data)

    def test_init_workspace_id_not_integer(self):
        """Tests calling RecipeData constructor with a non-integral value for workspace_id"""

        data = {'workspace_id': 'foo'}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData, data)

    def test_init_successful_one_property(self):
        """Tests calling RecipeData constructor successfully with a single property input."""

        data = {'input_data': [{'name': 'My Name', 'value': '1'}]}

        # No exception is success
        LegacyRecipeData(data)

class TestRecipeDataValidateInputFiles(TestCase):

    def setUp(self):
        django.setup()

        self.file_1 = storage_utils.create_file(file_name='my_json_file.json', media_type='application/json')
        self.file_2 = storage_utils.create_file(file_name='my_text_file_1.txt', media_type='text/plain')
        self.file_3 = storage_utils.create_file(file_name='my_text_file_2.txt', media_type='text/plain')

    def test_missing_required(self):
        """Tests calling RecipeData.validate_input_files() when a file is required, but missing"""

        data = {'input_data': []}
        files = {'File1': (True, True, ScaleFileDescription())}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData(data).validate_input_files, files)

    def test_not_required(self):
        """Tests calling RecipeData.validate_input_files() when a file is missing, but required"""

        data = {'input_data': []}
        files = {'File1': (False, True, ScaleFileDescription())}
        # No exception is success
        warnings = LegacyRecipeData(data).validate_input_files(files)
        self.assertFalse(warnings)

    def test_multiple_missing_file_ids(self):
        """Tests calling RecipeData.validate_input_files() with a multiple file param missing the file_ids field"""

        data = {'input_data': [{'name': 'File1'}]}
        files = {'File1': (True, True, ScaleFileDescription())}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData(data).validate_input_files, files)

    def test_multiple_non_list(self):
        """Tests calling RecipeData.validate_input_files() with a multiple file param with a non-list for file_ids field"""

        data = {'input_data': [{'name': 'File1', 'file_ids': 'STRING'}]}
        files = {'File1': (True, True, ScaleFileDescription())}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData(data).validate_input_files, files)

    def test_multiple_non_integrals(self):
        """Tests calling RecipeData.validate_input_files() with a multiple file param with a list of non-integrals for file_ids field"""

        data = {'input_data': [{'name': 'File1', 'file_ids': [123, 'STRING']}]}
        files = {'File1': (True, True, ScaleFileDescription())}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData(data).validate_input_files, files)

    def test_multiple_given_single(self):
        """Tests calling RecipeData.validate_input_files() with a multiple file param that is provided with a single file ID"""

        data = {'input_data': [{'name': 'File1', 'file_id': self.file_1.id}]}
        files = {'File1': (True, True, ScaleFileDescription())}
        # No exception is success
        warnings = LegacyRecipeData(data).validate_input_files(files)
        self.assertFalse(warnings)

    def test_single_missing_file_id(self):
        """Tests calling RecipeData.validate_input_files() with a single file param missing the file_id field"""

        data = {'input_data': [{'name': 'File1'}]}
        files = {'File1': (True, False, ScaleFileDescription())}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData(data).validate_input_files, files)

    def test_single_non_integral(self):
        """Tests calling RecipeData.validate_input_files() with a single file param with a non-integral for file_id field"""

        data = {'input_data': [{'name': 'File1', 'file_id': 'STRING'}]}
        files = {'File1': (True, False, ScaleFileDescription())}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData(data).validate_input_files, files)

    def test_bad_media_type(self):
        """Tests calling RecipeData.validate_input_files() with a file that has an invalid media type"""

        data = {'input_data': [{'name': 'File1', 'file_id': self.file_1.id}]}
        file_desc_1 = ScaleFileDescription()
        file_desc_1.add_allowed_media_type('text/plain')
        files = {'File1': (True, False, file_desc_1)}
        warnings = LegacyRecipeData(data).validate_input_files(files)
        self.assertTrue(warnings)

    def test_bad_file_id(self):
        """Tests calling RecipeData.validate_input_files() with a file that has an invalid ID"""

        data = {'input_data': [{'name': 'File1', 'file_id': 999999}]}
        files = {'File1': (True, False, ScaleFileDescription())}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData(data).validate_input_files, files)

    def test_successful(self):
        """Tests calling RecipeData.validate_input_files() with a valid set of job data"""

        data = {'input_data': [{'name': 'File1', 'file_id': self.file_1.id},
                                {'name': 'File3', 'file_ids': [self.file_2.id]}]}
        file_desc_1 = ScaleFileDescription()
        file_desc_1.add_allowed_media_type('application/json')
        file_desc_3 = ScaleFileDescription()
        file_desc_3.add_allowed_media_type('text/plain')
        files = {'File1': (True, False, file_desc_1),
                 'File3': (True, True, file_desc_3)}
        # No exception is success
        warnings = LegacyRecipeData(data).validate_input_files(files)
        self.assertFalse(warnings)

class TestRecipeDataValidateProperties(TestCase):

    def setUp(self):
        django.setup()

    def test_missing_value(self):
        """Tests calling RecipeData.validate_properties() when a property is missing a value"""

        data = {'input_data': [{'name': 'Param1'}]}
        properties = {'Param1': False}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData(data).validate_properties, properties)

    def test_value_not_string(self):
        """Tests calling RecipeData.validate_properties() when a property has a non-string value"""

        data = {'input_data': [{'name': 'Param1', 'value': 123}]}
        properties = {'Param1': False}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData(data).validate_properties, properties)

    def test_missing_required(self):
        """Tests calling RecipeData.validate_properties() when a property is required, but missing"""

        data = {'input_data': []}
        properties = {'Param1': True}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData(data).validate_properties, properties)

    def test_not_required(self):
        """Tests calling RecipeData.validate_properties() when a property is missing, but is not required"""

        data = {'input_data': []}
        properties = {'Param1': False}
        # No exception is success
        warnings = LegacyRecipeData(data).validate_properties(properties)
        self.assertFalse(warnings)

    def test_required_successful(self):
        """Tests calling RecipeData.validate_properties() successfully with a required property"""

        data = {'input_data': [{'name': 'Param1', 'value': 'Value1'}]}
        properties = {'Param1': True}
        # No exception is success
        warnings = LegacyRecipeData(data).validate_properties(properties)
        self.assertFalse(warnings)

class TestRecipeDataValidateWorkspace(TestCase):

    def setUp(self):
        django.setup()

    @patch('recipe.configuration.data.recipe_data.DATA_FILE_STORE', new_callable=lambda: {'DATA_FILE_STORE': DummyDataFileStore()})
    def test_missing_workspace_id(self, mock_store):
        """Tests calling RecipeData.validate_workspace() when missing the workspace_id field"""

        data = {}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData(data).validate_workspace)

    @patch('recipe.configuration.data.recipe_data.DATA_FILE_STORE', new_callable=lambda: {'DATA_FILE_STORE': DummyDataFileStore()})
    def test_workspace_not_exist(self, mock_store):
        """Tests calling RecipeData.validate_workspace() with a workspace that does not exist"""

        data = {'workspace_id': 2}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData(data).validate_workspace)

    @patch('recipe.configuration.data.recipe_data.DATA_FILE_STORE', new_callable=lambda: {'DATA_FILE_STORE': DummyDataFileStore()})
    def test_workspace_not_active(self, mock_store):
        """Tests calling RecipeData.validate_workspace() with a workspace that is not active"""

        data = {'workspace_id': 3}
        self.assertRaises(InvalidRecipeData, LegacyRecipeData(data).validate_workspace)

    @patch('recipe.configuration.data.recipe_data.DATA_FILE_STORE', new_callable=lambda: {'DATA_FILE_STORE': DummyDataFileStore()})
    def test_successful(self, mock_store):
        """Tests calling RecipeData.validate_workspace() with successful data"""

        data = {'workspace_id': 1}
        # No exception is success
        warnings = LegacyRecipeData(data).validate_workspace()
        self.assertFalse(warnings)


text:
<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>AASHE Bulletin</title>

  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

  <link rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">

    <link rel="stylesheet"
          href="/static/assets/plugins/bootstrap/css/bootstrap.css">
    <link rel="stylesheet"
          href="/static/assets/css/style.css">
    <link rel="stylesheet"
          href="/static/assets/css/headers/header1.css">
    <link rel="stylesheet"
          href="/static/assets/css/responsive.css">
    <link rel="shortcut icon"
          href="/static/favicon.ico">

    <link rel="stylesheet"
          href="/static/assets/plugins/font-awesome/css/font-awesome.css">

    <link rel="stylesheet"
          href="/static/assets/css/pages/blog.css">
    <link rel="stylesheet"
          href="/static/assets/css/pages/page_magazine.css">

    <link rel="stylesheet"
          href="/static/assets/css/themes/default.css"
          id="style_color">
    <link rel="stylesheet"
          href="/static/assets/css/themes/headers/default.css"
          id="style_color-header-1">

              Login/Logout

                  Home

                  Front Page

      <div class="headline"
Issue Template

If you can see this, something is broken (or JS is not enabled)!!.


text:
#ifndef SHTTPD_HEADER_INCLUDED
#define	SHTTPD_HEADER_INCLUDED

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

/*
 * This structure is passed to the user callback function
 */
struct shttpd_arg {
	void		*priv;		/* Private! Do not touch!	*/
	void		*state;		/* User state			*/
	void		*user_data;	/* User-defined data		*/

	struct {
		char	*buf;		/* Buffer pointer		*/
		int	len;		/* Size of a buffer		*/
		int	num_bytes;	/* Bytes processed by callback	*/
	} in, out;	/* POST data buffer (in) and output buffer (out) */

	unsigned int	flags;
#define	SHTTPD_END_OF_OUTPUT	1
#define	SHTTPD_CONNECTION_ERROR	2
#define	SHTTPD_MORE_POST_DATA	4
#define	SHTTPD_POST_BUFFER_FULL	8
};

/*
 * User callback function. Called when certain registered URLs have been
 * requested. These are the requirements to the callback function:
 *
 * 1. it must copy data into 'out_buf', not more than 'out_buf_max_len' bytes,
 *	and record how many bytes are copied, into 'out_buf_written_len'
 * 2. it must not block the execution
 * 3. it must set 'last' in shttpd_arg to 1 if there is no more data
 * 4. for POST requests, it must process the incoming data (in_buf), and
 *	set 'in_buf_read_len', which is how many bytes of POST data is read
 *	and can be discarded by SHTTPD.
 */
typedef void (*shttpd_callback_t)(struct shttpd_arg *);

/*
 * shttpd_init		Initialize shttpd context. Parameters: configuration
 *			file name (may be NULL), then NULL-terminated
 *			sequence of pairs "option_name", "option_value".
 * shttpd_init2		Same as shttpd_init, but the list of option/value
 *			pairs is passed in arrays
 * shttpd_fini		Dealocate the context
 * shttpd_register_uri	Setup the callback function for specified URL.
 * shttpd_protect_uri	Associate authorization file with an URL.
 * shttpd_add_mime_type	Add mime type
 * shtppd_listen	Setup a listening socket in the SHTTPD context
 * shttpd_poll		Do connections processing
 * shttpd_version	return string with SHTTPD version
 * shttpd_get_var	Return POST/GET variable value for given variable name.
 * shttpd_get_header	return value of the specified HTTP header
 * shttpd_get_env	return string values for the following
 *			pseudo-variables: "REQUEST_METHOD", "REQUEST_URI",
 *			"REMOTE_USER" and "REMOTE_ADDR".
 */

struct shttpd_ctx;

struct shttpd_ctx *shttpd_init(const char *config_file, ...);
struct shttpd_ctx *shttpd_init2(const char *config_file,
		char *names[], char *values[], size_t num_options);
void shttpd_fini(struct shttpd_ctx *);
void shttpd_add_mime_type(struct shttpd_ctx *,
		const char *ext, const char *mime);
int shttpd_listen(struct shttpd_ctx *ctx, int port);
void shttpd_register_uri(struct shttpd_ctx *ctx,
		const char *uri, shttpd_callback_t callback, void *user_data);
void shttpd_protect_uri(struct shttpd_ctx *ctx,
		const char *uri, const char *file);
void shttpd_poll(struct shttpd_ctx *, int milliseconds);
const char *shttpd_version(void);
int shttpd_get_var(const char *var, const char *buf, int buf_len,
		char *value, int value_len);
const char *shttpd_get_header(struct shttpd_arg *, const char *);
const char *shttpd_get_env(struct shttpd_arg *, const char *);
void shttpd_get_http_version(struct shttpd_arg *,
		unsigned long *major, unsigned long *minor);
size_t shttpd_printf(struct shttpd_arg *, const char *fmt, ...);
void shttpd_handle_error(struct shttpd_ctx *ctx, int status,
		shttpd_callback_t func, void *data);

/*
 * The following three functions are for applications that need to
 * load-balance the connections on their own. Many threads may be spawned
 * with one SHTTPD context per thread. Boss thread may only wait for
 * new connections by means of shttpd_accept(). Then it may scan thread
 * pool for the idle thread by means of shttpd_active(), and add new
 * connection to the context by means of shttpd_add().
 */
void shttpd_add_socket(struct shttpd_ctx *, int sock);
int shttpd_accept(int lsn_sock, int milliseconds);
int shttpd_active(struct shttpd_ctx *);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* SHTTPD_HEADER_INCLUDED */


text:
.. _quickstart:
.. module:: marshmallow

Quickstart
==========

This guide will walk you through the basics of creating schemas for serializing and deserializing data.

Declaring Schemas
-----------------

Let's start with a basic user "model".

.. code-block:: python

    import datetime as dt

    class User(object):
        def __init__(self, name, email):
            self.name = name
            self.email = email
            self.created_at = dt.datetime.now()

        def __repr__(self):
            return '<User(name={self.name!r})>'.format(self=self)

Create a schema by defining a class with variables mapping attribute names to :class:`Field <fields.Field>` objects.

.. code-block:: python

    from marshmallow import Schema, fields

    class UserSchema(Schema):
        name = fields.Str()
        email = fields.Email()
        created_at = fields.DateTime()

.. seealso::

    For a full reference on the available field classes, see the :ref:`API Docs <api_fields>`.

Serializing Objects ("Dumping")
-------------------------------

Serialize objects by passing them to your schema's :meth:`dump <marshmallow.Schema.dump>` method, which returns the formatted result (as well as a dictionary of validation errors, which we'll :ref:`revisit later <validation>`).

.. code-block:: python

    from marshmallow import pprint

    user = User(name="Monty", email="monty@python.org")
    schema = UserSchema()
    result = schema.dump(user)
    pprint(result.data)
    # {"name": "Monty",
    #  "email": "monty@python.org",
    #  "created_at": "2014-08-17T14:54:16.049594+00:00"}

You can also serialize to a JSON-encoded string using :meth:`dumps <marshmallow.Schema.dumps>`.

.. code-block:: python

    json_result = schema.dumps(user)
    pprint(json_result.data)
    # '{"name": "Monty", "email": "monty@python.org", "created_at": "2014-08-17T14:54:16.049594+00:00"}'

Filtering output
++++++++++++++++

You may not need to output all declared fields every time you use a schema. You can specify which fields to output with the ``only`` parameter.

.. code-block:: python

    summary_schema = UserSchema(only=('name', 'email'))
    summary_schema.dump(user).data
    # {"name": "Monty Python", "email": "monty@python.org"}

You can also exclude fields by passing in the ``exclude`` parameter.

Deserializing Objects ("Loading")
---------------------------------

The opposite of the :meth:`dump <Schema.dump>` method is the :meth:`load <Schema.load>` method, which deserializes an input dictionary to an application-level data structure.

By default, :meth:`load <Schema.load>` will return a dictionary of field names mapped to the deserialized values.

.. code-block:: python

    from pprint import pprint

    user_data = {
        'created_at': '2014-08-11T05:26:03.869245',
        'email': u'ken@yahoo.com',
        'name': u'Ken'
    }
    schema = UserSchema()
    result = schema.load(user_data)
    pprint(result.data)
    # {'name': 'Ken',
    #  'email': 'ken@yahoo.com',
    #  'created_at': datetime.datetime(2014, 8, 11, 5, 26, 3, 869245)},

Notice that the datetime string was converted to a `datetime` object.

Deserializing to Objects
++++++++++++++++++++++++

In order to deserialize to an object, define a method of your :class:`Schema` and decorate it with `post_load <marshmallow.decorators.post_load>`. The method receives a dictionary of deserialized data as its only parameter.

.. code-block:: python
    :emphasize-lines: 8-10

    from marshmallow import Schema, fields, post_load

    class UserSchema(Schema):
        name = fields.Str()
        email = fields.Email()
        created_at = fields.DateTime()

        @post_load
        def make_user(self, data):
            return User(**data)

Now, the :meth:`load <Schema.load>` method will return a ``User`` object.

.. code-block:: python

    user_data = {
        'name': 'Ronnie',
        'email': 'ronnie@stones.com'
    }
    schema = UserSchema()
    result = schema.load(user_data)
    result.data  # => <User(name='Ronnie')>

Handling Collections of Objects
-------------------------------

Iterable collections of objects are also serializable and deserializable. Just set ``many=True``.

.. code-block:: python
    :emphasize-lines: 3,4

    user1 = User(name="Mick", email="mick@stones.com")
    user2 = User(name="Keith", email="keith@stones.com")
    users = [user1, user2]
    schema = UserSchema(many=True)
    result = schema.dump(users)  # OR UserSchema().dump(users, many=True)
    result.data
    # [{'name': u'Mick',
    #   'email': u'mick@stones.com',
    #   'created_at': '2014-08-17T14:58:57.600623+00:00'}
    #  {'name': u'Keith',
    #   'email': u'keith@stones.com',
    #   'created_at': '2014-08-17T14:58:57.600623+00:00'}]

.. _validation:

Validation
----------

:meth:`Schema.load` (and its JSON-decoding counterpart, :meth:`Schema.loads`) returns a dictionary of validation errors as the second element of its return value. Some fields, such as the :class:`Email <fields.Email>` and :class:`URL <fields.URL>` fields, have built-in validation.

.. code-block:: python

    data, errors = UserSchema().load({'email': 'foo'})
    errors  # => {'email': ['"foo" is not a valid email address.']}
    # OR, equivalently
    result = UserSchema().load({'email': 'foo'})
    result.errors  # => {'email': ['"foo" is not a valid email address.']}

When validating a collection, the errors dictionary will be keyed on the indicies of invalid items.

.. code-block:: python

    class BandMemberSchema(Schema):
        name = fields.String(required=True)
        email = fields.Email()

    user_data = [
        {'email': 'mick@stones.com', 'name': 'Mick'},
        {'email': 'invalid', 'name': 'Invalid'},  # invalid email
        {'email': 'keith@stones.com', 'name': 'Keith'},
        {'email': 'charlie@stones.com'},  # missing "name"
    ]

    result = BandMemberSchema(many=True).load(user_data)
    result.errors
    # {1: {'email': ['"invalid" is not a valid email address.']},
    #  3: {'name': ['Missing data for required field.']}}

You can perform additional validation for a field by passing it a ``validate`` callable (function, lambda, or object with ``__call__`` defined).

.. code-block:: python
    :emphasize-lines: 4

    class ValidatedUserSchema(UserSchema):
        # NOTE: This is a contrived example.
        # You could use marshmallow.validate.Range instead of an anonymous function here
        age = fields.Number(validate=lambda n: 18 <= n <= 40)

    in_data = {'name': 'Mick', 'email': 'mick@stones.com', 'age': 71}
    result = ValidatedUserSchema().load(in_data)
    result.errors  # => {'age': ['Validator <lambda>(71.0) is False']}

Validation functions either return a boolean or raise a :exc:`ValidationError`. If a :exc:`ValidationError <marshmallow.exceptions.ValidationError>` is raised, its message is stored when validation fails.

.. code-block:: python
    :emphasize-lines: 7,10,14

    from marshmallow import Schema, fields, ValidationError

    def validate_quantity(n):
        if n < 0:
            raise ValidationError('Quantity must be greater than 0.')
        if n > 30:
            raise ValidationError('Quantity must not be greater than 30.')

    class ItemSchema(Schema):
        quantity = fields.Integer(validate=validate_quantity)

    in_data = {'quantity': 31}
    result, errors = ItemSchema().load(in_data)
    errors  # => {'quantity': ['Quantity must not be greater than 30.']}

.. note::

    If you have multiple validations to perform, you may also pass a collection (list, tuple, generator) of callables.

.. note::

    :meth:`Schema.dump` also returns a dictionary of errors, which will include any ``ValidationErrors`` raised during serialization. However, the ``required``, ``allow_none``, and ``validate`` parameters only apply during deserialization.

Field Validators as Methods
+++++++++++++++++++++++++++

It is often convenient to write validators as methods. Use the `validates <marshmallow.decorators.validates>` decorator to register field validator methods.

.. code-block:: python

    from marshmallow import fields, Schema, validates

    class ItemSchema(Schema):
        quantity = fields.Integer()

        @validates('quantity')
        def validate_quantity(self, value):
            if n < 0:
                raise ValidationError('Quantity must be greater than 0.')
            if n > 30:
                raise ValidationError('Quantity must not be greater than 30.')

``strict`` Mode
+++++++++++++++

    If you set ``strict=True`` in either the Schema constructor or as a ``class Meta`` option, an error will be raised when invalid data are passed in. You can access the dictionary of validation errors from the `ValidationError.messages <marshmallow.exceptions.ValidationError.messages>` attribute.

    .. code-block:: python

        from marshmallow import ValidationError

        try:
            UserSchema(strict=True).load({'email': 'foo'})
        except ValidationError as err:
            print(err.messages)# => {'email': ['"foo" is not a valid email address.']}

.. seealso::

    You can register a custom error handler function for a schema using the :func:`error_handler <Schema.error_handler>` decorator. See the :ref:`Extending Schemas <extending>` page for more info.

.. seealso::

    Need schema-level validation? See the :ref:`Extending Schemas <schemavalidation>` page.

Required Fields
+++++++++++++++

You can make a field required by passing ``required=True``. An error will be stored if the the value is missing from the input to :meth:`Schema.load`.

Alternatively, you can provide a custom error message by passing ``required='My custom message'``.
Dictionaries or lists are also accepted as the custom error message, in case you want to provide more information with the error.

.. code-block:: python
    :emphasize-lines: 2,3,4

    class UserSchema(Schema):
        name = fields.String(required=True)
        age = fields.Integer(required='Age is required.')
        city = fields.String(required={'message': 'City required', 'code': 400})
        email = fields.Email()

    data, errors = UserSchema().load({'email': 'foo@bar.com'})
    errors
    # {'name': ['Missing data for required field.'],
    #  'age': ['Age is required.'],
    #  'city': {'message': 'City required', 'code': 400}}

Schema.validate
+++++++++++++++

If you only need to validate input data (without deserializing to an object), you can use :meth:`Schema.validate`.

.. code-block:: python

    errors = UserSchema().validate({'name': 'Ronnie', 'email': 'invalid-email'})
    errors  # {'email': ['"invalid-email" is not a valid email address.']}

Specifying Attribute Names
--------------------------

By default, `Schemas` will marshal the object attributes that are identical to the schema's field names. However, you may want to have different field and attribute names. In this case, you can explicitly specify which attribute names to use.

.. code-block:: python
    :emphasize-lines: 3,4,11,12

    class UserSchema(Schema):
        name = fields.String()
        email_addr = fields.String(attribute="email")
        date_created = fields.DateTime(attribute="created_at")

    user = User('Keith', email='keith@stones.com')
    ser = UserSchema()
    result, errors = ser.dump(user)
    pprint(result)
    # {'name': 'Keith',
    #  'email_addr': 'keith@stones.com',
    #  'date_created': '2014-08-17T14:58:57.600623+00:00'}

Specifying Deserialization Keys
-------------------------------

By default `Schemas` will unmarshal an input dictionary to an output dictionary whose keys are identical to the field names.  However, if you are consuming data that does not exactly match your schema, you can specify additional keys to load values by passing the `load_from` argument.

.. code-block:: python
    :emphasize-lines: 2,3,11,12

    class UserSchema(Schema):
        name = fields.String()
        email = fields.Email(load_from='emailAddress')

    data = {
        'name': 'Mike',
        'emailAddress': 'foo@bar.com'
    }
    s = UserSchema()
    result, errors = s.load(data)
    #{'name': u'Mike',
    # 'email': 'foo@bar.com'}

.. _meta_options:

Refactoring: Implicit Field Creation
------------------------------------

When your model has many attributes, specifying the field type for every attribute can get repetitive, especially when many of the attributes are already native Python datatypes.

The *class Meta* paradigm allows you to specify which attributes you want to serialize. Marshmallow will choose an appropriate field type based on the attribute's type.

Let's refactor our User schema to be more concise.

.. code-block:: python
    :emphasize-lines: 4,5

    # Refactored schema
    class UserSchema(Schema):
        uppername = fields.Function(lambda obj: obj.name.upper())
        class Meta:
            fields = ("name", "email", "created_at", "uppername")

Note that ``name`` will be automatically formatted as a :class:`String <marshmallow.fields.String>` and ``created_at`` will be formatted as a :class:`DateTime <marshmallow.fields.DateTime>`.

.. note::

    If instead you want to specify which field names to include *in addition* to the explicitly declared fields, you can use the ``additional`` option.

    The schema below is equivalent to above:

    .. code-block:: python

        class UserSchema(Schema):
            uppername = fields.Function(lambda obj: obj.name.upper())
            class Meta:
                # No need to include 'uppername'
                additional = ("name", "email", "created_at")

Ordering Output
---------------

For some use cases, it may be useful to maintain field ordering of serialized output. To enable ordering, set the ``ordered`` option to `True`. This will instruct marshmallow to serialize data to a `collections.OrderedDict`.

.. code-block:: python
    :emphasize-lines: 7

    from collections import OrderedDict

    class UserSchema(Schema):
        uppername = fields.Function(lambda obj: obj.name.upper())
        class Meta:
            fields = ("name", "email", "created_at", "uppername")
            ordered = True

    u = User('Charlie', 'charlie@stones.com')
    schema = UserSchema()
    result = schema.dump(u)
    assert isinstance(result.data, OrderedDict)
    # marshmallow's pprint function maintains order
    pprint(result.data, indent=2)
    # {
    #   "name": "Charlie",
    #   "email": "charlie@stones.com",
    #   "created_at": "2014-10-30T08:27:48.515735+00:00",
    #   "uppername": "CHARLIE"
    # }

"Read-only" and "Write-only" Fields
-----------------------------------

In the context of a web API, the ``dump_only`` and ``load_only`` parameters are conceptually equivalent to "read-only" and "write-only" fields, respectively.

.. code-block:: python

    class UserSchema(Schema):
        name = fields.Str()
        # password is "write-only"
        password = fields.Str(load_only=True)
        # created_at is "read-only"
        created_at = fields.DateTime(dump_only=True)

Next Steps
----------

- Need to represent relationships between objects? See the :ref:`Nesting Schemas <nesting>` page.
- Want to create your own field type? See the :ref:`Custom Fields <custom_fields>` page.
- Need to add schema-level validation, post-processing, or error handling behavior? See the :ref:`Extending Schemas <extending>` page.
- For example applications using marshmallow, check out the :ref:`Examples <examples>` page.


text:
require 'pathname'

Puppet::Type.newtype(:dsc_xarchive) do
  require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc'

  provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do
    defaultfor :operatingsystem => :windows
  end

  @doc = %q{
    The DSC xArchive resource type.
    Originally generated from the following schema.mof file:
      import/dsc_resources/xPSDesiredStateConfiguration/DSCResources/MSFT_xArchive/MSFT_xArchive.schema.mof
  }

  validate do
      fail('dsc_destination is a required attribute') if self[:dsc_destination].nil?
    end

  newparam(:dscmeta_resource_friendly_name) do
    defaultto "xArchive"
  end

  newparam(:dscmeta_resource_name) do
    defaultto "MSFT_xArchive"
  end

  newparam(:dscmeta_import_resource) do
    newvalues(true, false)

    munge do |value|
      provider.munge_boolean(value.to_s)
    end

    defaultto true
  end

  newparam(:dscmeta_module_name) do
    defaultto "xPSDesiredStateConfiguration"
  end

  newparam(:dscmeta_module_version) do
    defaultto "3.4.0.0"
  end

  newparam(:name, :namevar => true ) do
  end

  ensurable do
    newvalue(:exists?) { provider.exists? }
    newvalue(:present) { provider.create }
    defaultto { :present }
  end

  # Name:         Destination
  # Type:         string
  # IsMandatory:  True
  # Values:       None
  newparam(:dsc_destination) do
    isrequired
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         Path
  # Type:         string[]
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_path, :array_matching => :all) do
    desc "Represnts the source path to one or more files or directories.\n"
    validate do |value|
      unless value.kind_of?(Array) || value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string or an array of strings")
      end
    end
    munge do |value|
      Array(value)
    end
  end

  # Name:         CompressionLevel
  # Type:         string
  # IsMandatory:  False
  # Values:       ["Optimal", "NoCompression", "Fastest"]
  newparam(:dsc_compressionlevel) do
    desc "Specifies values that indicate whether a compression operation emphasizes speed or compression size.\nOptimal {default} \n"
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
      unless ['Optimal', 'optimal', 'NoCompression', 'nocompression', 'Fastest', 'fastest'].include?(value)
        fail("Invalid value '#{value}'. Valid values are Optimal, NoCompression, Fastest")
      end
    end
  end

  # Name:         DestinationType
  # Type:         string
  # IsMandatory:  False
  # Values:       ["File", "Directory"]
  newparam(:dsc_destinationtype) do
    desc "An enumerated value that describes if the Destination path points to a File or Directory. If Directory is specified then the archive file contents would be expanded to the specified path on the other hand if File is specified, an archive file would be created at the specified destination path.\nDirectory {default} \n"
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
      unless ['File', 'file', 'Directory', 'directory'].include?(value)
        fail("Invalid value '#{value}'. Valid values are File, Directory")
      end
    end
  end

  # Name:         MatchSource
  # Type:         boolean
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_matchsource) do
    desc "An boolean value to indicate if the destination contents have to be always kept in sync with the files or directories specified in the source path.\n"
    validate do |value|
    end
    newvalues(true, false)
    munge do |value|
      provider.munge_boolean(value.to_s)
    end
  end

  # Name:         CreationTime
  # Type:         datetime
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_creationtime) do
    desc "Specifies the local time at which the file or directory was created in datetime format.\n"
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         Attributes
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_attributes) do
    desc "Specifies the attributes of the file or directory in string format.\n"
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         Mode
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_mode) do
    desc "Specifies the mode of the file or directory.\n"
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         Size
  # Type:         uint64
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_size) do
    desc "Specifis the size of the file or directory in bytes.\n"
    validate do |value|
      unless (value.kind_of?(Numeric) && value >= 0) || (value.to_i.to_s == value && value.to_i >= 0)
          fail("Invalid value #{value}. Should be a unsigned Integer")
      end
    end
    munge do |value|
      value.to_i
    end
  end

end


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

import com.google.inject.Binder;
import com.google.inject.Module;
import io.airlift.configuration.AbstractConfigurationAwareModule;
import io.trino.plugin.base.security.ConnectorAccessControlModule;
import io.trino.plugin.base.security.FileBasedAccessControlModule;
import io.trino.plugin.base.security.ReadOnlySecurityModule;

import static io.airlift.configuration.ConditionalModule.conditionalModule;
import static io.airlift.configuration.ConfigurationAwareModule.combine;

public class HiveSecurityModule
        extends AbstractConfigurationAwareModule
{
    public static final String LEGACY = "legacy";
    public static final String FILE = "file";
    public static final String READ_ONLY = "read-only";
    public static final String SQL_STANDARD = "sql-standard";
    public static final String ALLOW_ALL = "allow-all";
    public static final String SYSTEM = "system";

    @Override
    protected void setup(Binder binder)
    {
        install(new ConnectorAccessControlModule());
        bindSecurityModule(
                LEGACY,
                combine(
                        new LegacySecurityModule(),
                        new StaticAccessControlMetadataModule()));
        bindSecurityModule(
                FILE,
                combine(
                        new FileBasedAccessControlModule(),
                        new StaticAccessControlMetadataModule()));
        bindSecurityModule(
                READ_ONLY,
                combine(
                        new ReadOnlySecurityModule(),
                        new StaticAccessControlMetadataModule()));
        bindSecurityModule(SQL_STANDARD, new SqlStandardSecurityModule());
        bindSecurityModule(ALLOW_ALL, new AllowAllSecurityModule());
        bindSecurityModule(SYSTEM, new SystemSecurityModule());
    }

    private void bindSecurityModule(String name, Module module)
    {
        install(conditionalModule(
                SecurityConfig.class,
                security -> name.equalsIgnoreCase(security.getSecuritySystem()),
                module));
    }

    private static class StaticAccessControlMetadataModule
            implements Module
    {
        @Override
        public void configure(Binder binder)
        {
            binder.bind(AccessControlMetadataFactory.class).toInstance((metastore) -> new AccessControlMetadata() {});
        }
    }
}


text:
/* This particular implementation was written by Eric Blake, 2008.  */

#ifndef _LIBC
# include <config.h>
#endif

/* Specification of memmem.  */
#include <string.h>

#ifndef _LIBC
# define __builtin_expect(expr, val)   (expr)
#endif

#define RETURN_TYPE void *
#define AVAILABLE(h, h_l, j, n_l) ((j) <= (h_l) - (n_l))
#include "str-two-way.h"

/* Return the first occurrence of NEEDLE in HAYSTACK.  Return HAYSTACK
   if NEEDLE_LEN is 0, otherwise NULL if NEEDLE is not found in
   HAYSTACK.  */
void *
memmem (const void *haystack_start, size_t haystack_len,
        const void *needle_start, size_t needle_len)
{
  /* Abstract memory is considered to be an array of 'unsigned char' values,
     not an array of 'char' values.  See ISO C 99 section 6.2.6.1.  */
  const unsigned char *haystack = (const unsigned char *) haystack_start;
  const unsigned char *needle = (const unsigned char *) needle_start;

  if (needle_len == 0)
    /* The first occurrence of the empty string is deemed to occur at
       the beginning of the string.  */
    return (void *) haystack;

  /* Sanity check, otherwise the loop might search through the whole
     memory.  */
  if (__builtin_expect (haystack_len < needle_len, 0))
    return NULL;

  /* Use optimizations in memchr when possible, to reduce the search
     size of haystack using a linear algorithm with a smaller
     coefficient.  However, avoid memchr for long needles, since we
     can often achieve sublinear performance.  */
  if (needle_len < LONG_NEEDLE_THRESHOLD)
    {
      haystack = memchr (haystack, *needle, haystack_len);
      if (!haystack || __builtin_expect (needle_len == 1, 0))
        return (void *) haystack;
      haystack_len -= haystack - (const unsigned char *) haystack_start;
      if (haystack_len < needle_len)
        return NULL;
      return two_way_short_needle (haystack, haystack_len, needle, needle_len);
    }
  else
    return two_way_long_needle (haystack, haystack_len, needle, needle_len);
}

#undef LONG_NEEDLE_THRESHOLD


text:
static NSMutableArray *sharedConnectionList = nil;

@implementation PlayFabConnection
@synthesize request,completionBlock,internalConnection;

-(void)postURL:(NSString*)url body:(NSString*)body authType:(NSString*)authType authKey:(NSString*)authKey
{
    NSLog(@"postURL");

    NSURL *sRequestURL = [NSURL URLWithString:url];

    NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:sRequestURL];
    NSString *sMessageLength = [NSString stringWithFormat:@"%d", (int)[body length]];

    [myRequest addValue: @"application/json" forHTTPHeaderField:@"Content-Type"];
    [myRequest addValue: sMessageLength forHTTPHeaderField:@"Content-Length"];
    [myRequest addValue: versionString forHTTPHeaderField:@"X-PlayFabSDK"];
    if ([authType length] != 0)
    {
        [myRequest addValue: authKey forHTTPHeaderField:authType];
    }
    [myRequest setHTTPMethod:@"POST"];
    [myRequest setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:self];

    if( theConnection ) {
        container = [NSMutableData data];

        if(!sharedConnectionList)
            sharedConnectionList = [[NSMutableArray alloc] init];
        [sharedConnectionList addObject:self];
    }else {
        NSLog(@"Some error occurred in Connection");
    }

}

#pragma mark NSURLConnectionDelegate methods

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [container appendData:data];

}

//If finish, return the data and the error nil
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

    if([self completionBlock])
        [self completionBlock](container,nil);

    [sharedConnectionList removeObject:self];

}

//If fail, return nil and an error
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

    if([self completionBlock])
        [self completionBlock](nil,error);

    [sharedConnectionList removeObject:self];

}

@end


text:
<?xml version="1.0" encoding="UTF-8" ?>

<wicket:panel xmlns:wicket="http://wicket.apache.org">

        <button class="btn dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false">

        </button>

</wicket:panel>


text:
#include "ScriptV8.h"

#include <iostream>

#include "AttrImp.h"
#include "CaretPositionImp.h"
#include "CharacterDataImp.h"
#include "CommentImp.h"
#include "DocumentFragmentImp.h"
#include "DocumentImp.h"
#include "DocumentTypeImp.h"
#include "DOMErrorImp.h"
// #include "DOMExceptionImp.h"
#include "DOMImplementationImp.h"
#include "DOMSettableTokenListImp.h"
#include "DOMStringListImp.h"
#include "DOMStringMapImp.h"
#include "DOMTokenListImp.h"
#include "ElementImp.h"
#include "NodeImp.h"
#include "NodeListImp.h"
#include "ProcessingInstructionImp.h"
#include "TextImp.h"
#include "XMLDocumentImp.h"

#include "css/CounterImp.h"
#include "css/CSS2PropertiesImp.h"
#include "css/CSSCharsetRuleImp.h"
#include "css/CSSFontFaceRuleImp.h"
#include "css/CSSImportRuleImp.h"
#include "css/CSSMediaRuleImp.h"
#include "css/CSSNamespaceRuleImp.h"
#include "css/CSSPageRuleImp.h"
#include "css/CSSPrimitiveValueImp.h"
#include "css/CSSRuleImp.h"
#include "css/CSSRuleListImp.h"
#include "css/CSSStyleDeclarationImp.h"
#include "css/CSSStyleRuleImp.h"
#include "css/CSSStyleSheetImp.h"
#include "css/CSSUnknownRuleImp.h"
#include "css/CSSValueImp.h"
#include "css/CSSValueListImp.h"
// #include "css/DocumentCSSImp.h"
// #include "css/DOMImplementationCSSImp.h"
// #include "css/ElementCSSInlineStyleImp.h"
#include "css/RectImp.h"
#include "css/RGBColorImp.h"

// events
#include "CompositionEventImp.h"
#include "CompositionEventInitImp.h"
#include "CustomEventImp.h"
#include "CustomEventInitImp.h"
#include "EventImp.h"
#include "EventHandlerNonNullImp.h"
#include "EventInitImp.h"
#include "EventListenerImp.h"
#include "EventTargetImp.h"
// #include "EventXBLImp.h"
#include "FocusEventImp.h"
#include "FocusEventInitImp.h"
#include "KeyboardEventImp.h"
#include "KeyboardEventInitImp.h"
#include "MouseEventImp.h"
#include "MouseEventInitImp.h"
#include "MutationCallbackImp.h"
#include "MutationEventImp.h"
#include "MutationObserverImp.h"
#include "MutationObserverInitImp.h"
#include "MutationRecordImp.h"
#include "OnErrorEventHandlerNonNullImp.h"
#include "ProgressEventImp.h"
#include "UIEventImp.h"
#include "UIEventInitImp.h"
#include "WheelEventImp.h"
#include "WheelEventInitImp.h"

// eventsource
#include "EventSourceImp.h"

// file
#include "file/BlobImp.h"
#include "file/BlobPropertyBagImp.h"
#include "file/FileCallbackImp.h"
#include "file/FileImp.h"
#include "file/FileListImp.h"
#include "file/FileReaderImp.h"
#include "file/FileReaderSyncImp.h"
#include "file/LineEndingsImp.h"

// html
#include "html/ApplicationCacheImp.h"
#include "html/AudioTrackImp.h"
#include "html/AudioTrackListImp.h"
#include "html/BarPropImp.h"
#include "BeforeUnloadEventImp.h"
#include "html/CanvasDrawingStylesImp.h"
#include "html/CanvasGradientImp.h"
#include "html/CanvasPathMethodsImp.h"
#include "html/CanvasPatternImp.h"
#include "html/CanvasRenderingContext2DImp.h"
#include "html/DataTransferImp.h"
#include "html/DataTransferItemImp.h"
#include "html/DataTransferItemListImp.h"
#include "DragEventImp.h"
#include "DragEventInitImp.h"
#include "html/DrawingStyleImp.h"
#include "ExternalImp.h"
#include "FunctionStringCallbackImp.h"
#include "HashChangeEventImp.h"
#include "HashChangeEventInitImp.h"
#include "HistoryImp.h"
#include "html/HitRegionOptionsImp.h"
#include "html/HTMLAllCollectionImp.h"
#include "html/HTMLAnchorElementImp.h"
#include "html/HTMLAppletElementImp.h"
#include "html/HTMLAreaElementImp.h"
#include "html/HTMLAudioElementImp.h"
#include "html/HTMLBaseElementImp.h"
#include "html/HTMLBaseFontElementImp.h"
#include "html/HTMLBindingElementImp.h"
#include "html/HTMLBodyElementImp.h"
#include "html/HTMLBRElementImp.h"
#include "html/HTMLButtonElementImp.h"
#include "html/HTMLCanvasElementImp.h"
#include "html/HTMLCollectionImp.h"
#include "html/HTMLCommandElementImp.h"
#include "html/HTMLDataListElementImp.h"
#include "html/HTMLDetailsElementImp.h"
#include "html/HTMLDialogElementImp.h"
#include "html/HTMLDirectoryElementImp.h"
#include "html/HTMLDivElementImp.h"
#include "html/HTMLDListElementImp.h"
#include "html/HTMLElementImp.h"
#include "html/HTMLEmbedElementImp.h"
#include "html/HTMLFieldSetElementImp.h"
#include "html/HTMLFontElementImp.h"
#include "html/HTMLFormControlsCollectionImp.h"
#include "html/HTMLFormElementImp.h"
#include "html/HTMLFrameElementImp.h"
#include "html/HTMLFrameSetElementImp.h"
#include "html/HTMLHeadElementImp.h"
#include "html/HTMLHeadingElementImp.h"
#include "html/HTMLHRElementImp.h"
#include "html/HTMLHtmlElementImp.h"
#include "html/HTMLIFrameElementImp.h"
#include "html/HTMLImageElementImp.h"
#include "html/HTMLInputElementImp.h"
#include "html/HTMLKeygenElementImp.h"
#include "html/HTMLLabelElementImp.h"
#include "html/HTMLLegendElementImp.h"
#include "html/HTMLLIElementImp.h"
#include "html/HTMLLinkElementImp.h"
#include "html/HTMLMapElementImp.h"
#include "html/HTMLMarqueeElementImp.h"
#include "html/HTMLMediaElementImp.h"
#include "html/HTMLMenuElementImp.h"
#include "html/HTMLMetaElementImp.h"
#include "html/HTMLMeterElementImp.h"
#include "html/HTMLModElementImp.h"
#include "html/HTMLObjectElementImp.h"
#include "html/HTMLOListElementImp.h"
#include "html/HTMLOptGroupElementImp.h"
#include "html/HTMLOptionElementImp.h"
#include "html/HTMLOptionsCollectionImp.h"
#include "html/HTMLOutputElementImp.h"
#include "html/HTMLParagraphElementImp.h"
#include "html/HTMLParamElementImp.h"
#include "html/HTMLPreElementImp.h"
#include "html/HTMLProgressElementImp.h"
#include "html/HTMLQuoteElementImp.h"
#include "html/HTMLScriptElementImp.h"
#include "html/HTMLSelectElementImp.h"
#include "html/HTMLSourceElementImp.h"
#include "html/HTMLSpanElementImp.h"
#include "html/HTMLStyleElementImp.h"
#include "html/HTMLTableCaptionElementImp.h"
#include "html/HTMLTableCellElementImp.h"
#include "html/HTMLTableColElementImp.h"
#include "html/HTMLTableDataCellElementImp.h"
#include "html/HTMLTableElementImp.h"
#include "html/HTMLTableHeaderCellElementImp.h"
#include "html/HTMLTableRowElementImp.h"
#include "html/HTMLTableSectionElementImp.h"
#include "html/HTMLTemplateElementImp.h"
#include "html/HTMLTextAreaElementImp.h"
#include "html/HTMLTimeElementImp.h"
#include "html/HTMLTitleElementImp.h"
#include "html/HTMLTrackElementImp.h"
#include "html/HTMLUListElementImp.h"
#include "html/HTMLUnknownElementImp.h"
#include "html/HTMLVideoElementImp.h"
#include "html/ImageDataImp.h"
#include "LocationImp.h"
#include "html/MediaControllerImp.h"
#include "html/MediaErrorImp.h"
#include "html/MediaQueryListImp.h"
#include "html/MediaQueryListListenerImp.h"
#include "html/MessageChannelImp.h"
#include "MessageEventImp.h"
#include "MessageEventInitImp.h"
#include "html/MessagePortImp.h"
#include "NavigatorContentUtilsImp.h"
#include "NavigatorImp.h"
#include "NavigatorIDImp.h"
#include "NavigatorOnLineImp.h"
#include "NavigatorStorageUtilsImp.h"
#include "PageTransitionEventImp.h"
#include "PageTransitionEventInitImp.h"
#include "html/PathImp.h"
#include "PopStateEventImp.h"
#include "PopStateEventInitImp.h"
#include "html/RadioNodeListImp.h"
#include "html/ScreenImp.h"
#include "html/TextMetricsImp.h"
#include "html/TextTrackCueImp.h"
#include "html/TextTrackCueListImp.h"
#include "html/TextTrackImp.h"
#include "html/TextTrackListImp.h"
#include "html/TimeRangesImp.h"
#include "TrackEventImp.h"
#include "TrackEventInitImp.h"
#include "html/TransferableImp.h"
#include "html/ValidityStateImp.h"
#include "html/VideoTrackImp.h"
#include "html/VideoTrackListImp.h"
// #include "WindowBase64Imp.h"
#include "WindowProxy.h"
// #include "WindowModalImp.h"
// #include "WindowTimersImp.h"

// ranges
// #include "RangeExceptionImp.h"
#include "RangeImp.h"

// stylesheets
#include "MediaListImp.h"
#include "StyleSheetImp.h"

// svg
#include "svg/SVGMatrixImp.h"

// traversal
#include "NodeFilterImp.h"
#include "NodeIteratorImp.h"
#include "TreeWalkerImp.h"

// typedarray
#include "typedarray/ArrayBufferImp.h"
#include "typedarray/ArrayBufferViewImp.h"
#include "typedarray/DataViewImp.h"
#include "typedarray/Float32ArrayImp.h"
#include "typedarray/Float64ArrayImp.h"
#include "typedarray/Int16ArrayImp.h"
#include "typedarray/Int32ArrayImp.h"
#include "typedarray/Int8ArrayImp.h"
#include "typedarray/Uint16ArrayImp.h"
#include "typedarray/Uint32ArrayImp.h"
#include "typedarray/Uint8ArrayImp.h"
#include "typedarray/Uint8ClampedArrayImp.h"

// geometry
#include "DOMRectImp.h"
#include "DOMRectReadOnlyImp.h"
#include "DOMRectListImp.h"

// xbl2
// #include "xbl/DocumentXBLImp.h"
// #include "xbl/ElementXBLImp.h"
#include "xbl/XBLContentElementImp.h"
#include "xbl/XBLImplementationImp.h"
#include "xbl/XBLImplementationListImp.h"

// xhr
#include "xhr/FormDataImp.h"
#include "xhr/XMLHttpRequestEventTargetImp.h"
#include "xhr/XMLHttpRequestImp.h"
#include "xhr/XMLHttpRequestOptionsImp.h"
#include "xhr/XMLHttpRequestUploadImp.h"

#include "utf.h"

using namespace org::w3c::dom::bootstrap;
using namespace org::w3c::dom;

// JSAPI bridge

namespace {

void reportError(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
{
    v8::String::Value s(message->Get());
    std::u16string m(reinterpret_cast<const char16_t*>(*s));
    std::cerr << message->GetLineNumber() << ": " << m << '\n';
}

void registerClasses(v8::Handle<v8::ObjectTemplate> global)
{
    // prototype roots
    AttrImp::setStaticPrivate(new NativeClass(global, AttrImp::getMetaData()));
    CSSRuleImp::setStaticPrivate(new NativeClass(global, CSSRuleImp::getMetaData()));
    CSSStyleDeclarationImp::setStaticPrivate(new NativeClass(global, CSSStyleDeclarationImp::getMetaData()));
    CSSValueImp::setStaticPrivate(new NativeClass(global, CSSValueImp::getMetaData()));
    DOMImplementationImp::setStaticPrivate(new NativeClass(global, DOMImplementationImp::getMetaData()));
    DOMTokenListImp::setStaticPrivate(new NativeClass(global, DOMTokenListImp::getMetaData()));
    EventImp::setStaticPrivate(new NativeClass(global, EventImp::getMetaData()));
    EventInitImp::setStaticPrivate(new NativeClass(global, EventInitImp::getMetaData()));
    EventTargetImp::setStaticPrivate(new NativeClass(global, EventTargetImp::getMetaData()));
    HTMLCollectionImp::setStaticPrivate(new NativeClass(global, HTMLCollectionImp::getMetaData()));
    LocationImp::setStaticPrivate(new NativeClass(global, LocationImp::getMetaData()));
    MediaListImp::setStaticPrivate(new NativeClass(global, MediaListImp::getMetaData()));
    NodeImp::setStaticPrivate(new NativeClass(global, NodeImp::getMetaData()));
    NodeListImp::setStaticPrivate(new NativeClass(global, NodeListImp::getMetaData()));
    StyleSheetImp::setStaticPrivate(new NativeClass(global, StyleSheetImp::getMetaData()));
    UIEventImp::setStaticPrivate(new NativeClass(global, UIEventImp::getMetaData()));

    ElementImp::setStaticPrivate(new NativeClass(global, ElementImp::getMetaData()));
    HTMLElementImp::setStaticPrivate(new NativeClass(global, HTMLElementImp::getMetaData()));
    HTMLMediaElementImp::setStaticPrivate(new NativeClass(global, HTMLMediaElementImp::getMetaData()));

//    AttrImp::setStaticPrivate(new NativeClass(global, AttrImp::getMetaData()));
    CaretPositionImp::setStaticPrivate(new NativeClass(global, CaretPositionImp::getMetaData()));
    CharacterDataImp::setStaticPrivate(new NativeClass(global, CharacterDataImp::getMetaData()));
    CommentImp::setStaticPrivate(new NativeClass(global, CommentImp::getMetaData()));
    DocumentFragmentImp::setStaticPrivate(new NativeClass(global, DocumentFragmentImp::getMetaData()));
    DocumentImp::setStaticPrivate(new NativeClass(global, DocumentImp::getMetaData()));
    DocumentTypeImp::setStaticPrivate(new NativeClass(global, DocumentTypeImp::getMetaData()));
    DOMErrorImp::setStaticPrivate(new NativeClass(global, DOMErrorImp::getMetaData()));
//    DOMImplementationImp::setStaticPrivate(new NativeClass(global, DOMImplementationImp::getMetaData()));
    DOMSettableTokenListImp::setStaticPrivate(new NativeClass(global, DOMSettableTokenListImp::getMetaData()));
    DOMStringListImp::setStaticPrivate(new NativeClass(global, DOMStringListImp::getMetaData()));
    DOMStringMapImp::setStaticPrivate(new NativeClass(global, DOMStringMapImp::getMetaData()));
//    DOMTokenListImp::setStaticPrivate(new NativeClass(global, DOMTokenListImp::getMetaData()));
//    ElementImp::setStaticPrivate(new NativeClass(global, ElementImp::getMetaData()));
//    NodeImp::setStaticPrivate(new NativeClass(global, NodeImp::getMetaData()));
//    NodeListImp::setStaticPrivate(new NativeClass(global, NodeListImp::getMetaData()));
    ProcessingInstructionImp::setStaticPrivate(new NativeClass(global, ProcessingInstructionImp::getMetaData()));
    TextImp::setStaticPrivate(new NativeClass(global, TextImp::getMetaData()));
    XMLDocumentImp::setStaticPrivate(new NativeClass(global, XMLDocumentImp::getMetaData()));
    CounterImp::setStaticPrivate(new NativeClass(global, CounterImp::getMetaData()));
    CSS2PropertiesImp::setStaticPrivate(new NativeClass(global, CSS2PropertiesImp::getMetaData()));
    CSSCharsetRuleImp::setStaticPrivate(new NativeClass(global, CSSCharsetRuleImp::getMetaData()));
    CSSFontFaceRuleImp::setStaticPrivate(new NativeClass(global, CSSFontFaceRuleImp::getMetaData()));
    CSSImportRuleImp::setStaticPrivate(new NativeClass(global, CSSImportRuleImp::getMetaData()));
    CSSMediaRuleImp::setStaticPrivate(new NativeClass(global, CSSMediaRuleImp::getMetaData()));
    CSSNamespaceRuleImp::setStaticPrivate(new NativeClass(global, CSSNamespaceRuleImp::getMetaData()));
    CSSPageRuleImp::setStaticPrivate(new NativeClass(global, CSSPageRuleImp::getMetaData()));
    CSSPrimitiveValueImp::setStaticPrivate(new NativeClass(global, CSSPrimitiveValueImp::getMetaData()));
//    CSSRuleImp::setStaticPrivate(new NativeClass(global, CSSRuleImp::getMetaData()));
    CSSRuleListImp::setStaticPrivate(new NativeClass(global, CSSRuleListImp::getMetaData()));
//    CSSStyleDeclarationImp::setStaticPrivate(new NativeClass(global, CSSStyleDeclarationImp::getMetaData()));
    CSSStyleRuleImp::setStaticPrivate(new NativeClass(global, CSSStyleRuleImp::getMetaData()));
    CSSStyleSheetImp::setStaticPrivate(new NativeClass(global, CSSStyleSheetImp::getMetaData()));
    CSSUnknownRuleImp::setStaticPrivate(new NativeClass(global, CSSUnknownRuleImp::getMetaData()));
//    CSSValueImp::setStaticPrivate(new NativeClass(global, CSSValueImp::getMetaData()));
    CSSValueListImp::setStaticPrivate(new NativeClass(global, CSSValueListImp::getMetaData()));
    RectImp::setStaticPrivate(new NativeClass(global, RectImp::getMetaData()));
    RGBColorImp::setStaticPrivate(new NativeClass(global, RGBColorImp::getMetaData()));
    CompositionEventImp::setStaticPrivate(new NativeClass(global, CompositionEventImp::getMetaData()));
    CompositionEventInitImp::setStaticPrivate(new NativeClass(global, CompositionEventInitImp::getMetaData()));
    CustomEventImp::setStaticPrivate(new NativeClass(global, CustomEventImp::getMetaData()));
    CustomEventInitImp::setStaticPrivate(new NativeClass(global, CustomEventInitImp::getMetaData()));
//    EventImp::setStaticPrivate(new NativeClass(global, EventImp::getMetaData()));
    EventHandlerNonNullImp::setStaticPrivate(new NativeClass(global, EventHandlerNonNullImp::getMetaData()));
//    EventInitImp::setStaticPrivate(new NativeClass(global, EventInitImp::getMetaData()));
    EventListenerImp::setStaticPrivate(new NativeClass(global, EventListenerImp::getMetaData()));
//    EventTargetImp::setStaticPrivate(new NativeClass(global, EventTargetImp::getMetaData()));
    FocusEventImp::setStaticPrivate(new NativeClass(global, FocusEventImp::getMetaData()));
    FocusEventInitImp::setStaticPrivate(new NativeClass(global, FocusEventInitImp::getMetaData()));
    KeyboardEventImp::setStaticPrivate(new NativeClass(global, KeyboardEventImp::getMetaData()));
    KeyboardEventInitImp::setStaticPrivate(new NativeClass(global, KeyboardEventInitImp::getMetaData()));
    MouseEventImp::setStaticPrivate(new NativeClass(global, MouseEventImp::getMetaData()));
    MouseEventInitImp::setStaticPrivate(new NativeClass(global, MouseEventInitImp::getMetaData()));
    MutationCallbackImp::setStaticPrivate(new NativeClass(global, MutationCallbackImp::getMetaData()));
    MutationEventImp::setStaticPrivate(new NativeClass(global, MutationEventImp::getMetaData()));
    MutationObserverImp::setStaticPrivate(new NativeClass(global, MutationObserverImp::getMetaData()));
    MutationObserverInitImp::setStaticPrivate(new NativeClass(global, MutationObserverInitImp::getMetaData()));
    MutationRecordImp::setStaticPrivate(new NativeClass(global, MutationRecordImp::getMetaData()));
    OnErrorEventHandlerNonNullImp::setStaticPrivate(new NativeClass(global, OnErrorEventHandlerNonNullImp::getMetaData()));
    ProgressEventImp::setStaticPrivate(new NativeClass(global, ProgressEventImp::getMetaData()));
//    UIEventImp::setStaticPrivate(new NativeClass(global, UIEventImp::getMetaData()));
    UIEventInitImp::setStaticPrivate(new NativeClass(global, UIEventInitImp::getMetaData()));
    WheelEventImp::setStaticPrivate(new NativeClass(global, WheelEventImp::getMetaData()));
    WheelEventInitImp::setStaticPrivate(new NativeClass(global, WheelEventInitImp::getMetaData()));
    EventSourceImp::setStaticPrivate(new NativeClass(global, EventSourceImp::getMetaData()));
    BlobImp::setStaticPrivate(new NativeClass(global, BlobImp::getMetaData()));
    BlobPropertyBagImp::setStaticPrivate(new NativeClass(global, BlobPropertyBagImp::getMetaData()));
    FileCallbackImp::setStaticPrivate(new NativeClass(global, FileCallbackImp::getMetaData()));
    FileImp::setStaticPrivate(new NativeClass(global, FileImp::getMetaData()));
    FileListImp::setStaticPrivate(new NativeClass(global, FileListImp::getMetaData()));
    FileReaderImp::setStaticPrivate(new NativeClass(global, FileReaderImp::getMetaData()));
    FileReaderSyncImp::setStaticPrivate(new NativeClass(global, FileReaderSyncImp::getMetaData()));
    LineEndingsImp::setStaticPrivate(new NativeClass(global, LineEndingsImp::getMetaData()));
    ApplicationCacheImp::setStaticPrivate(new NativeClass(global, ApplicationCacheImp::getMetaData()));
    AudioTrackImp::setStaticPrivate(new NativeClass(global, AudioTrackImp::getMetaData()));
    AudioTrackListImp::setStaticPrivate(new NativeClass(global, AudioTrackListImp::getMetaData()));
    BarPropImp::setStaticPrivate(new NativeClass(global, BarPropImp::getMetaData()));
    BeforeUnloadEventImp::setStaticPrivate(new NativeClass(global, BeforeUnloadEventImp::getMetaData()));
    CanvasDrawingStylesImp::setStaticPrivate(new NativeClass(global, CanvasDrawingStylesImp::getMetaData()));
    CanvasGradientImp::setStaticPrivate(new NativeClass(global, CanvasGradientImp::getMetaData()));
    CanvasPathMethodsImp::setStaticPrivate(new NativeClass(global, CanvasPathMethodsImp::getMetaData()));
    CanvasPatternImp::setStaticPrivate(new NativeClass(global, CanvasPatternImp::getMetaData()));
    CanvasRenderingContext2DImp::setStaticPrivate(new NativeClass(global, CanvasRenderingContext2DImp::getMetaData()));
    DataTransferImp::setStaticPrivate(new NativeClass(global, DataTransferImp::getMetaData()));
    DataTransferItemImp::setStaticPrivate(new NativeClass(global, DataTransferItemImp::getMetaData()));
    DataTransferItemListImp::setStaticPrivate(new NativeClass(global, DataTransferItemListImp::getMetaData()));
    DragEventImp::setStaticPrivate(new NativeClass(global, DragEventImp::getMetaData()));
    DragEventInitImp::setStaticPrivate(new NativeClass(global, DragEventInitImp::getMetaData()));
    DrawingStyleImp::setStaticPrivate(new NativeClass(global, DrawingStyleImp::getMetaData()));
    ExternalImp::setStaticPrivate(new NativeClass(global, ExternalImp::getMetaData()));
    FunctionStringCallbackImp::setStaticPrivate(new NativeClass(global, FunctionStringCallbackImp::getMetaData()));
    HashChangeEventImp::setStaticPrivate(new NativeClass(global, HashChangeEventImp::getMetaData()));
    HashChangeEventInitImp::setStaticPrivate(new NativeClass(global, HashChangeEventInitImp::getMetaData()));
    HistoryImp::setStaticPrivate(new NativeClass(global, HistoryImp::getMetaData()));
    HitRegionOptionsImp::setStaticPrivate(new NativeClass(global, HitRegionOptionsImp::getMetaData()));
    HTMLAllCollectionImp::setStaticPrivate(new NativeClass(global, HTMLAllCollectionImp::getMetaData()));
    HTMLAnchorElementImp::setStaticPrivate(new NativeClass(global, HTMLAnchorElementImp::getMetaData()));
    HTMLAppletElementImp::setStaticPrivate(new NativeClass(global, HTMLAppletElementImp::getMetaData()));
    HTMLAreaElementImp::setStaticPrivate(new NativeClass(global, HTMLAreaElementImp::getMetaData()));
    HTMLAudioElementImp::setStaticPrivate(new NativeClass(global, HTMLAudioElementImp::getMetaData()));
    HTMLBaseElementImp::setStaticPrivate(new NativeClass(global, HTMLBaseElementImp::getMetaData()));
    HTMLBaseFontElementImp::setStaticPrivate(new NativeClass(global, HTMLBaseFontElementImp::getMetaData()));
    HTMLBindingElementImp::setStaticPrivate(new NativeClass(global, HTMLBindingElementImp::getMetaData()));
    HTMLBodyElementImp::setStaticPrivate(new NativeClass(global, HTMLBodyElementImp::getMetaData()));
    HTMLBRElementImp::setStaticPrivate(new NativeClass(global, HTMLBRElementImp::getMetaData()));
    HTMLButtonElementImp::setStaticPrivate(new NativeClass(global, HTMLButtonElementImp::getMetaData()));
    HTMLCanvasElementImp::setStaticPrivate(new NativeClass(global, HTMLCanvasElementImp::getMetaData()));
//    HTMLCollectionImp::setStaticPrivate(new NativeClass(global, HTMLCollectionImp::getMetaData()));
    HTMLCommandElementImp::setStaticPrivate(new NativeClass(global, HTMLCommandElementImp::getMetaData()));
    HTMLDataListElementImp::setStaticPrivate(new NativeClass(global, HTMLDataListElementImp::getMetaData()));
    HTMLDetailsElementImp::setStaticPrivate(new NativeClass(global, HTMLDetailsElementImp::getMetaData()));
    HTMLDialogElementImp::setStaticPrivate(new NativeClass(global, HTMLDialogElementImp::getMetaData()));
    HTMLDirectoryElementImp::setStaticPrivate(new NativeClass(global, HTMLDirectoryElementImp::getMetaData()));
    HTMLDivElementImp::setStaticPrivate(new NativeClass(global, HTMLDivElementImp::getMetaData()));
    HTMLDListElementImp::setStaticPrivate(new NativeClass(global, HTMLDListElementImp::getMetaData()));
//    HTMLElementImp::setStaticPrivate(new NativeClass(global, HTMLElementImp::getMetaData()));
    HTMLEmbedElementImp::setStaticPrivate(new NativeClass(global, HTMLEmbedElementImp::getMetaData()));
    HTMLFieldSetElementImp::setStaticPrivate(new NativeClass(global, HTMLFieldSetElementImp::getMetaData()));
    HTMLFontElementImp::setStaticPrivate(new NativeClass(global, HTMLFontElementImp::getMetaData()));
    HTMLFormControlsCollectionImp::setStaticPrivate(new NativeClass(global, HTMLFormControlsCollectionImp::getMetaData()));
    HTMLFormElementImp::setStaticPrivate(new NativeClass(global, HTMLFormElementImp::getMetaData()));
    HTMLFrameElementImp::setStaticPrivate(new NativeClass(global, HTMLFrameElementImp::getMetaData()));
    HTMLFrameSetElementImp::setStaticPrivate(new NativeClass(global, HTMLFrameSetElementImp::getMetaData()));
    HTMLHeadElementImp::setStaticPrivate(new NativeClass(global, HTMLHeadElementImp::getMetaData()));
    HTMLHeadingElementImp::setStaticPrivate(new NativeClass(global, HTMLHeadingElementImp::getMetaData()));
    HTMLHRElementImp::setStaticPrivate(new NativeClass(global, HTMLHRElementImp::getMetaData()));
    HTMLHtmlElementImp::setStaticPrivate(new NativeClass(global, HTMLHtmlElementImp::getMetaData()));
    HTMLIFrameElementImp::setStaticPrivate(new NativeClass(global, HTMLIFrameElementImp::getMetaData()));
    HTMLImageElementImp::setStaticPrivate(new NativeClass(global, HTMLImageElementImp::getMetaData()));
    HTMLInputElementImp::setStaticPrivate(new NativeClass(global, HTMLInputElementImp::getMetaData()));
    HTMLKeygenElementImp::setStaticPrivate(new NativeClass(global, HTMLKeygenElementImp::getMetaData()));
    HTMLLabelElementImp::setStaticPrivate(new NativeClass(global, HTMLLabelElementImp::getMetaData()));
    HTMLLegendElementImp::setStaticPrivate(new NativeClass(global, HTMLLegendElementImp::getMetaData()));
    HTMLLIElementImp::setStaticPrivate(new NativeClass(global, HTMLLIElementImp::getMetaData()));
    HTMLLinkElementImp::setStaticPrivate(new NativeClass(global, HTMLLinkElementImp::getMetaData()));
    HTMLMapElementImp::setStaticPrivate(new NativeClass(global, HTMLMapElementImp::getMetaData()));
    HTMLMarqueeElementImp::setStaticPrivate(new NativeClass(global, HTMLMarqueeElementImp::getMetaData()));
//    HTMLMediaElementImp::setStaticPrivate(new NativeClass(global, HTMLMediaElementImp::getMetaData()));
    HTMLMenuElementImp::setStaticPrivate(new NativeClass(global, HTMLMenuElementImp::getMetaData()));
    HTMLMetaElementImp::setStaticPrivate(new NativeClass(global, HTMLMetaElementImp::getMetaData()));
    HTMLMeterElementImp::setStaticPrivate(new NativeClass(global, HTMLMeterElementImp::getMetaData()));
    HTMLModElementImp::setStaticPrivate(new NativeClass(global, HTMLModElementImp::getMetaData()));
    HTMLObjectElementImp::setStaticPrivate(new NativeClass(global, HTMLObjectElementImp::getMetaData()));
    HTMLOListElementImp::setStaticPrivate(new NativeClass(global, HTMLOListElementImp::getMetaData()));
    HTMLOptGroupElementImp::setStaticPrivate(new NativeClass(global, HTMLOptGroupElementImp::getMetaData()));
    HTMLOptionElementImp::setStaticPrivate(new NativeClass(global, HTMLOptionElementImp::getMetaData()));
    HTMLOptionsCollectionImp::setStaticPrivate(new NativeClass(global, HTMLOptionsCollectionImp::getMetaData()));
    HTMLOutputElementImp::setStaticPrivate(new NativeClass(global, HTMLOutputElementImp::getMetaData()));
    HTMLParagraphElementImp::setStaticPrivate(new NativeClass(global, HTMLParagraphElementImp::getMetaData()));
    HTMLParamElementImp::setStaticPrivate(new NativeClass(global, HTMLParamElementImp::getMetaData()));
    HTMLPreElementImp::setStaticPrivate(new NativeClass(global, HTMLPreElementImp::getMetaData()));
    HTMLProgressElementImp::setStaticPrivate(new NativeClass(global, HTMLProgressElementImp::getMetaData()));
    HTMLQuoteElementImp::setStaticPrivate(new NativeClass(global, HTMLQuoteElementImp::getMetaData()));
    HTMLScriptElementImp::setStaticPrivate(new NativeClass(global, HTMLScriptElementImp::getMetaData()));
    HTMLSelectElementImp::setStaticPrivate(new NativeClass(global, HTMLSelectElementImp::getMetaData()));
    HTMLSourceElementImp::setStaticPrivate(new NativeClass(global, HTMLSourceElementImp::getMetaData()));
    HTMLSpanElementImp::setStaticPrivate(new NativeClass(global, HTMLSpanElementImp::getMetaData()));
    HTMLStyleElementImp::setStaticPrivate(new NativeClass(global, HTMLStyleElementImp::getMetaData()));
    HTMLTableCaptionElementImp::setStaticPrivate(new NativeClass(global, HTMLTableCaptionElementImp::getMetaData()));
    HTMLTableCellElementImp::setStaticPrivate(new NativeClass(global, HTMLTableCellElementImp::getMetaData()));
    HTMLTableColElementImp::setStaticPrivate(new NativeClass(global, HTMLTableColElementImp::getMetaData()));
    HTMLTableDataCellElementImp::setStaticPrivate(new NativeClass(global, HTMLTableDataCellElementImp::getMetaData()));
    HTMLTableElementImp::setStaticPrivate(new NativeClass(global, HTMLTableElementImp::getMetaData()));
    HTMLTableHeaderCellElementImp::setStaticPrivate(new NativeClass(global, HTMLTableHeaderCellElementImp::getMetaData()));
    HTMLTableRowElementImp::setStaticPrivate(new NativeClass(global, HTMLTableRowElementImp::getMetaData()));
    HTMLTableSectionElementImp::setStaticPrivate(new NativeClass(global, HTMLTableSectionElementImp::getMetaData()));
    HTMLTemplateElementImp::setStaticPrivate(new NativeClass(global, HTMLTemplateElementImp::getMetaData()));
    HTMLTextAreaElementImp::setStaticPrivate(new NativeClass(global, HTMLTextAreaElementImp::getMetaData()));
    HTMLTimeElementImp::setStaticPrivate(new NativeClass(global, HTMLTimeElementImp::getMetaData()));
    HTMLTitleElementImp::setStaticPrivate(new NativeClass(global, HTMLTitleElementImp::getMetaData()));
    HTMLTrackElementImp::setStaticPrivate(new NativeClass(global, HTMLTrackElementImp::getMetaData()));
    HTMLUListElementImp::setStaticPrivate(new NativeClass(global, HTMLUListElementImp::getMetaData()));
    HTMLUnknownElementImp::setStaticPrivate(new NativeClass(global, HTMLUnknownElementImp::getMetaData()));
    HTMLVideoElementImp::setStaticPrivate(new NativeClass(global, HTMLVideoElementImp::getMetaData()));
    ImageDataImp::setStaticPrivate(new NativeClass(global, ImageDataImp::getMetaData()));
//    LocationImp::setStaticPrivate(new NativeClass(global, LocationImp::getMetaData()));
    MediaControllerImp::setStaticPrivate(new NativeClass(global, MediaControllerImp::getMetaData()));
    MediaErrorImp::setStaticPrivate(new NativeClass(global, MediaErrorImp::getMetaData()));
    MediaQueryListImp::setStaticPrivate(new NativeClass(global, MediaQueryListImp::getMetaData()));
    MediaQueryListListenerImp::setStaticPrivate(new NativeClass(global, MediaQueryListListenerImp::getMetaData()));
    MessageChannelImp::setStaticPrivate(new NativeClass(global, MessageChannelImp::getMetaData()));
    MessageEventImp::setStaticPrivate(new NativeClass(global, MessageEventImp::getMetaData()));
    MessageEventInitImp::setStaticPrivate(new NativeClass(global, MessageEventInitImp::getMetaData()));
    MessagePortImp::setStaticPrivate(new NativeClass(global, MessagePortImp::getMetaData()));
    NavigatorContentUtilsImp::setStaticPrivate(new NativeClass(global, NavigatorContentUtilsImp::getMetaData()));
    NavigatorImp::setStaticPrivate(new NativeClass(global, NavigatorImp::getMetaData()));
    NavigatorIDImp::setStaticPrivate(new NativeClass(global, NavigatorIDImp::getMetaData()));
    NavigatorOnLineImp::setStaticPrivate(new NativeClass(global, NavigatorOnLineImp::getMetaData()));
    NavigatorStorageUtilsImp::setStaticPrivate(new NativeClass(global, NavigatorStorageUtilsImp::getMetaData()));
    PageTransitionEventImp::setStaticPrivate(new NativeClass(global, PageTransitionEventImp::getMetaData()));
    PageTransitionEventInitImp::setStaticPrivate(new NativeClass(global, PageTransitionEventInitImp::getMetaData()));
    PathImp::setStaticPrivate(new NativeClass(global, PathImp::getMetaData()));
    PopStateEventImp::setStaticPrivate(new NativeClass(global, PopStateEventImp::getMetaData()));
    PopStateEventInitImp::setStaticPrivate(new NativeClass(global, PopStateEventInitImp::getMetaData()));
    RadioNodeListImp::setStaticPrivate(new NativeClass(global, RadioNodeListImp::getMetaData()));
    ScreenImp::setStaticPrivate(new NativeClass(global, ScreenImp::getMetaData()));
    TextMetricsImp::setStaticPrivate(new NativeClass(global, TextMetricsImp::getMetaData()));
    TextTrackCueImp::setStaticPrivate(new NativeClass(global, TextTrackCueImp::getMetaData()));
    TextTrackCueListImp::setStaticPrivate(new NativeClass(global, TextTrackCueListImp::getMetaData()));
    TextTrackImp::setStaticPrivate(new NativeClass(global, TextTrackImp::getMetaData()));
    TextTrackListImp::setStaticPrivate(new NativeClass(global, TextTrackListImp::getMetaData()));
    TimeRangesImp::setStaticPrivate(new NativeClass(global, TimeRangesImp::getMetaData()));
    TrackEventImp::setStaticPrivate(new NativeClass(global, TrackEventImp::getMetaData()));
    TrackEventInitImp::setStaticPrivate(new NativeClass(global, TrackEventInitImp::getMetaData()));
    TransferableImp::setStaticPrivate(new NativeClass(global, TransferableImp::getMetaData()));
    ValidityStateImp::setStaticPrivate(new NativeClass(global, ValidityStateImp::getMetaData()));
    VideoTrackImp::setStaticPrivate(new NativeClass(global, VideoTrackImp::getMetaData()));
    VideoTrackListImp::setStaticPrivate(new NativeClass(global, VideoTrackListImp::getMetaData()));
    WindowProxy::setStaticPrivate(new NativeClass(global, WindowProxy::getMetaData()));
    RangeImp::setStaticPrivate(new NativeClass(global, RangeImp::getMetaData()));
//    MediaListImp::setStaticPrivate(new NativeClass(global, MediaListImp::getMetaData()));
//    StyleSheetImp::setStaticPrivate(new NativeClass(global, StyleSheetImp::getMetaData()));
    SVGMatrixImp::setStaticPrivate(new NativeClass(global, SVGMatrixImp::getMetaData()));
    NodeFilterImp::setStaticPrivate(new NativeClass(global, NodeFilterImp::getMetaData()));
    NodeIteratorImp::setStaticPrivate(new NativeClass(global, NodeIteratorImp::getMetaData()));
    TreeWalkerImp::setStaticPrivate(new NativeClass(global, TreeWalkerImp::getMetaData()));
    ArrayBufferImp::setStaticPrivate(new NativeClass(global, ArrayBufferImp::getMetaData()));
    ArrayBufferViewImp::setStaticPrivate(new NativeClass(global, ArrayBufferViewImp::getMetaData()));
    DataViewImp::setStaticPrivate(new NativeClass(global, DataViewImp::getMetaData()));
    Float32ArrayImp::setStaticPrivate(new NativeClass(global, Float32ArrayImp::getMetaData()));
    Float64ArrayImp::setStaticPrivate(new NativeClass(global, Float64ArrayImp::getMetaData()));
    Int16ArrayImp::setStaticPrivate(new NativeClass(global, Int16ArrayImp::getMetaData()));
    Int32ArrayImp::setStaticPrivate(new NativeClass(global, Int32ArrayImp::getMetaData()));
    Int8ArrayImp::setStaticPrivate(new NativeClass(global, Int8ArrayImp::getMetaData()));
    Uint16ArrayImp::setStaticPrivate(new NativeClass(global, Uint16ArrayImp::getMetaData()));
    Uint32ArrayImp::setStaticPrivate(new NativeClass(global, Uint32ArrayImp::getMetaData()));
    Uint8ArrayImp::setStaticPrivate(new NativeClass(global, Uint8ArrayImp::getMetaData()));
    Uint8ClampedArrayImp::setStaticPrivate(new NativeClass(global, Uint8ClampedArrayImp::getMetaData()));
    DOMRectReadOnlyImp::setStaticPrivate(new NativeClass(global, DOMRectReadOnlyImp::getMetaData()));
    DOMRectImp::setStaticPrivate(new NativeClass(global, DOMRectImp::getMetaData()));
    DOMRectListImp::setStaticPrivate(new NativeClass(global, DOMRectListImp::getMetaData()));
    XBLContentElementImp::setStaticPrivate(new NativeClass(global, XBLContentElementImp::getMetaData()));
    XBLImplementationImp::setStaticPrivate(new NativeClass(global, XBLImplementationImp::getMetaData()));
    XBLImplementationListImp::setStaticPrivate(new NativeClass(global, XBLImplementationListImp::getMetaData()));
    FormDataImp::setStaticPrivate(new NativeClass(global, FormDataImp::getMetaData()));
    XMLHttpRequestEventTargetImp::setStaticPrivate(new NativeClass(global, XMLHttpRequestEventTargetImp::getMetaData()));
    XMLHttpRequestImp::setStaticPrivate(new NativeClass(global, XMLHttpRequestImp::getMetaData()));
    XMLHttpRequestOptionsImp::setStaticPrivate(new NativeClass(global, XMLHttpRequestOptionsImp::getMetaData()));
    XMLHttpRequestUploadImp::setStaticPrivate(new NativeClass(global, XMLHttpRequestUploadImp::getMetaData()));
}

}  // namespace

v8::Persistent<v8::ObjectTemplate> ECMAScriptContext::Impl::getGlobalTemplate() {
    static bool initilized = false;
    static v8::Persistent<v8::ObjectTemplate> globalTemplate;
    if (initilized)
        return globalTemplate;
#ifdef HAVE_V8_ISOLATE
    globalTemplate = v8::Persistent<v8::ObjectTemplate>::New(v8::Isolate::GetCurrent(), v8::ObjectTemplate::New());
#else
    globalTemplate = v8::Persistent<v8::ObjectTemplate>::New(v8::ObjectTemplate::New());
#endif
    registerClasses(globalTemplate);
    globalTemplate->SetInternalFieldCount(1);
    initilized = true;
    return globalTemplate;
}

ECMAScriptContext::Impl::Impl()
{
    const char* extensionNames[] = {
        "v8/gc",
    };

    v8::V8::AddMessageListener(reportError);

    v8::ExtensionConfiguration extensions(1, extensionNames);
    context = v8::Context::New(&extensions, getGlobalTemplate());
    v8::Context::Scope scope(context);
    v8::HandleScope handleScope;
    v8::Handle<v8::Object> globalProxy = context->Global();
    v8::Handle<v8::Object> global = globalProxy->GetPrototype().As<v8::Object>();
    assert(global->InternalFieldCount() == 1);
    Reflect::Interface globalMeta(html::Window::getMetaData());
    std::string name = Reflect::getIdentifier(globalMeta.getName());
    if (0 < name.length()) {
        auto window = v8::Local<v8::Function>::Cast(globalProxy->Get(v8::String::New(name.c_str(), name.length())));
        v8::Local<v8::Value> prototype = window->Get(v8::String::New("prototype"));
        global->SetPrototype(prototype);
    }
}

ECMAScriptContext::Impl::~Impl()
{
    if (v8::Context::InContext() && v8::Context::GetCurrent() == context)
        context->Exit();
#ifdef HAVE_V8_ISOLATE
    context.Dispose(v8::Isolate::GetCurrent());
#else
    context.Dispose();
#endif
    context.Clear();
}

void ECMAScriptContext::Impl::enter(ObjectImp* windowProxy)
{
    context->Enter();

    v8::HandleScope handleScope;

    v8::Handle<v8::Object> globalProxy = context->Global();
    v8::Handle<v8::Object> global = globalProxy->GetPrototype().As<v8::Object>();
    assert(global->InternalFieldCount() == 1);
    global->SetInternalField(0, v8::External::New(windowProxy));
}

void ECMAScriptContext::Impl::exit(ObjectImp* windowProxy)
{
    assert(v8::Context::GetCurrent() == context);
    context->Exit();
}

void ECMAScriptContext::Impl::shutDown()
{
#ifdef HAVE_V8_ISOLATE
    getGlobalTemplate().Dispose(v8::Isolate::GetCurrent());
#else
    getGlobalTemplate().Dispose();
#endif
    getGlobalTemplate().Clear();
}

ECMAScriptContext::ECMAScriptContext()
  : pimpl(new Impl())
{
}

ECMAScriptContext::~ECMAScriptContext()
{
}

void ECMAScriptContext::enter(ObjectImp* window)
{
    pimpl->enter(window);
    current = window;
}

void ECMAScriptContext::exit(ObjectImp* window)
{
    pimpl->exit(window);
}

Object ECMAScriptContext::compileFunction(const std::u16string& body)
{
    assert(getCurrentContext() == this);
    return pimpl->compileFunction(body);
}

Object ECMAScriptContext::xblCreateImplementation(Object object, Object prototype, Object boundElement, Object shadowTree)
{
    assert(getCurrentContext() == this);
    return pimpl->xblCreateImplementation(object, prototype, boundElement, shadowTree);
}

void ECMAScriptContext::shutDown()
{
    Impl::shutDown();
}

ObjectImp* ECMAScriptContext::current;


text:
using System;
using System.Collections.Generic;
using d60.Cirqus.Logging;

namespace d60.Cirqus.Config
{
    /// <summary>
    /// Represents additional options for how Cirqus does its thing
    /// </summary>
    public class Options
    {
        /// <summary>
        /// Default number of retries for command processing
        /// </summary>
        public const int DefaultMaxRetries = 10;

        readonly HashSet<Type> _domainExceptionTypes = new HashSet<Type>();

        /// <summary>
        /// Constructs the default options
        /// </summary>
        public Options()
        {
            PurgeExistingViews = false;
            MaxRetries = DefaultMaxRetries;
        }

        /// <summary>
        /// Configures whether to purge all existing views during initialization.
        /// </summary>
        public bool PurgeExistingViews { get; set; }

        /// <summary>
        /// Configures the number of retries to perform when processing commands.
        /// </summary>
        public int MaxRetries { get; set; }

        /// <summary>
        /// Gets the registered domain exception types
        /// </summary>
        public ICollection<Type> DomainExceptionTypes { get { return _domainExceptionTypes; } }

        /// <summary>
        /// Gets/sets the global logger factory. THIS SETTING AFFECTS HOW CIRQUS LOGS, IMMEDIATELY AND GLOBALLY. The setting is here for convenience
        /// </summary>
        public CirqusLoggerFactory GlobalLoggerFactory
        {
            get { return CirqusLoggerFactory.Current; }
            set { CirqusLoggerFactory.Current = value; }
        }

        /// <summary>
        /// Registers the given exception type as a "domain exception", meaning that it will be passed
        /// directly to the caller of <seealso cref="CommandProcessor.ProcessCommand"/>
        /// </summary>
        public void AddDomainExceptionType<TException>() where TException : Exception
        {
            _domainExceptionTypes.Add(typeof (TException));
        }
    }
}


text:
*Scaffold out a TestCafe reporter*

[![Build Status](https://api.travis-ci.org/DevExpress/generator-testcafe-reporter.svg)](https://travis-ci.org/DevExpress/generator-testcafe-reporter)

TestCafe can build test run reports in your own format and style. All you need is a custom reporter plugin.
This Yeoman generator scaffolds out such a plugin, so that you will need to write only a few lines of code.

For more information, read [Custom Reporter Plugin](https://devexpress.github.io/testcafe/documentation/extending-testcafe/reporter-plugin/).


text:
package pia.cloud;

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

public class CountMap<T> {
	private Map<T, Integer> map;

    /**
     * Creates a new map.
     */
    public CountMap() {
        super();
        map = new HashMap<>();
    }

	/**
	 * Creates a new map.
	 */
	public CountMap(int size) {
		super();
		map = new HashMap<>(size);
	}

	/**
	 * Increments a count for a given key.
	 * @param key the key.
	 * @param increment the increment.
	 * @return a new count for a given key.
	 */
	public int inc(T key, int increment) {
		Integer count = map.get(key);

		if (count == null) {
			map.put(key, increment);
			return increment;
		} else {
			map.put(key, count + increment);
			return count + increment;
		}
	}

    /**
     * Decrements a count for a given key.
     * @param key the key.
     * @param decrement the decrement.
     * @return a new count for a given key.
     */
    public int dec(T key, int decrement) {
        Integer count = map.get(key);

        if (count == null) {
            return 0;
        } else {
            map.put(key, count - decrement);
            return count + decrement;
        }
    }

	/**
	 * Gets count for the given key.
	 * @param key the key.
	 * @return the count for the given key.
	 */
	public int get(T key) {
		Integer count = map.get(key);

		if (count == null) {
			return 0;
		} else {
			return count;
		}
	}

	/**
	 * Sets a count for a given key.
	 * @param key the key.
	 * @param value the new value.
	 * @return the new value.
	 */
	public int set(T key, int value) {
        map.put(key, value);

		return value;
	}

	/**
	 * Clears the map.
	 */
	public void clear() {
		map.clear();
	}

    public int size() { return map.size(); }

	/**
	 * Gets the key set.
	 * @return the key set.
	 */
	public Set<T> getKeySet() {
		return map.keySet();
	}

    public Set<Map.Entry<T, Integer>> getEntrySet() { return map.entrySet(); }

	@Override
	public String toString() {
		return map.toString();
	}
}


text:
require "eventmachine"
require "ruby-mpd"

EventMachine.run do
  mpd = MPD.new ENV["HOST"] ||= "localhost", (ENV["PORT"] ||= "6600").to_i, callbacks: true

  mpd.on :playlistlength do |length|
    if length < 2
      playlist = MPD::Playlist.new mpd, ENV["PLAYLIST"] ||= "autoplay"
      playlist.load
    end
  end

  mpd.connect
end