text:
import base64
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from django.core.validators import RegexValidator
import oauth2_provider
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from yak.rest_core.serializers import YAKModelSerializer
from yak.rest_core.utils import get_package_version
from yak.settings import yak_settings

User = get_user_model()
oauth_toolkit_version = get_package_version(oauth2_provider)

class AuthSerializerMixin(object):
    def create(self, validated_data):
        if validated_data.get("username", None):
            validated_data["username"] = validated_data["username"].lower()
        if validated_data.get("email", None):
            validated_data["email"] = validated_data["email"].lower()
        if validated_data.get("password", None):
            validated_data["password"] = make_password(validated_data["password"])

        return super(AuthSerializerMixin, self).create(validated_data)

    def update(self, instance, validated_data):
        if validated_data.get("username", None):
            validated_data["username"] = validated_data["username"].lower()
        if validated_data.get("email", None):
            validated_data["email"] = validated_data["email"].lower()
        if validated_data.get("password", None):
            validated_data["password"] = make_password(validated_data["password"])

        return super(AuthSerializerMixin, self).update(instance, validated_data)

    def validate_username(self, value):
        username = self.context['request'].user.username if self.context['request'].user.is_authenticated else None
        if value and value != username and User.objects.filter(username__iexact=value).exists():
            raise serializers.ValidationError("That username is taken")
        return value

    def validate_email(self, value):
        email = self.context['request'].user.email if self.context['request'].user.is_authenticated else None
        if value and value != email and User.objects.filter(email__iexact=value).exists():
            raise serializers.ValidationError("An account already exists with that email")
        return value

    def validate_password(self, value):
        value = base64.decodebytes(bytes(value, 'utf8')).decode()
        if len(value) < 6:
            raise serializers.ValidationError("Password must be at least 6 characters")
        return value

class LoginSerializer(serializers.ModelSerializer):
    client_id = serializers.SerializerMethodField()
    client_secret = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('client_id', 'client_secret')

    def get_application(self, obj):
        # If we're using version 0.8.0 or higher
        if oauth_toolkit_version[0] >= 0 and oauth_toolkit_version[1] >= 8:
            return obj.oauth2_provider_application.first()
        else:
            return obj.oauth2_provider_application.first()

    def get_client_id(self, obj):
        return self.get_application(obj).client_id

    def get_client_secret(self, obj):
        return self.get_application(obj).client_secret

class SignUpSerializer(AuthSerializerMixin, LoginSerializer):
    password = serializers.CharField(max_length=128, write_only=True, error_messages={'required': 'Password required'})
    username = serializers.CharField(
        error_messages={'required': 'Username required'},
        max_length=30,
        validators=[RegexValidator(), UniqueValidator(queryset=User.objects.all(), message="Username taken")])
    email = serializers.EmailField(
        allow_blank=True,
        allow_null=True,
        max_length=75,
        required=False,
        validators=[UniqueValidator(queryset=User.objects.all(), message="Email address taken")])

    class Meta(LoginSerializer.Meta):
        fields = ('fullname', 'username', 'email', 'password', 'client_id', 'client_secret')

class UserSerializer(AuthSerializerMixin, YAKModelSerializer):

    def __new__(cls, *args, **kwargs):
        """
        Can't just inherit in the class definition due to lots of import issues
        """
        return yak_settings.USER_SERIALIZER(*args, **kwargs)

class PasswordConfirmSerializer(AuthSerializerMixin, serializers.Serializer):
    password = serializers.CharField(required=True, error_messages={'required': 'New password required'})
    confirm_password = serializers.CharField(required=True,
                                             error_messages={'required': 'New password must be confirmed'})

    def validate(self, attrs):
        # first password is decoded in the `validate_password` method
        attrs['confirm_password'] = base64.decodebytes(bytes(attrs['confirm_password'], 'utf8')).decode()
        if attrs['password'] != attrs['confirm_password']:
            raise serializers.ValidationError("Passwords did not match")
        return attrs

class PasswordChangeSerializer(PasswordConfirmSerializer):
    old_password = serializers.CharField(required=True, error_messages={'required': 'Old password required'})

class PasswordResetSerializer(serializers.Serializer):
    email = serializers.EmailField()

class PasswordSetSerializer(PasswordConfirmSerializer):
    uid = serializers.CharField()
    token = serializers.CharField()


text:
package com.google.samples.apps.topeka.model.quiz;

public class FillTwoBlanksQuizTest extends AbsQuizTestCase<FillTwoBlanksQuiz> {

    @Override
    public FillTwoBlanksQuiz getQuiz() {
        return new FillTwoBlanksQuiz(QUESTION, STRING_ARRAY, false);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * @file
 * Hooks and API provided by the Slick module.
 */

/**
 * @defgroup slick_api Slick API
 * @{
 * Information about the Slick usages.
 *
 * Modules may implement any of the available hooks to interact with Slick.
 *
 * Slick may be configured using the web interface via sub-modules.
 * However below is a few sample coded ones. The simple API is to achieve
 * consistent markups working for various skins, and layouts for both coded
 * and sub-modules implementations.
 *
 * The expected parameters are:
 *   - items: A required array of slick contents: text, image or media.
 *   - options: An optional array of key:value pairs of custom JS options.
 *   - optionset: An optional optionset object to avoid multiple invocations.
 *   - settings: An array of key:value pairs of HTML/layout related settings
 *     which may contain optionset ID if no optionset above is provided.
 *
 * @see \Drupal\slick\Plugin\Field\FieldFormatter\SlickImageFormatter
 * @see \Drupal\slick_views\Plugin\views\style\SlickViews
 *
 * @section sec_quick Quick sample #1
 *
 * Returns the renderable array of a slick instance.
 * @code
 * function my_module_render_slick() {
 *   // Invoke the plugin class, or use a DI service container accordingly.
 *   $slick = \Drupal::service('slick.manager');
 *
 *   // Access the formatter service for image-related methods:
 *   $formatter = \Drupal::service('slick.formatter');
 *
 *   $build = [];
 *
 *   // Caption contains: alt, data, link, overlay, title.
 *   // Each item has keys: slide, caption, settings.
 *   $items[] = [
 *     // Use $formatter->getImage($element) to have lazyLoad where $element
 *     // contains:
 *     // item: Drupal\image\Plugin\Field\FieldType\ImageItem.
 *     'slide'   => '',
 *     'caption' => ['title' => t('Description #1')],
 *   ];
 *
 *   $items[] = [
 *     'slide'   => '',
 *     'caption' => ['title' => t('Description #2')],
 *   ];
 *
 *   $items[] = [
 *     'slide'   => '',
 *     'caption' => ['title' => t('Description #3')],
 *   ];
 *
 *   // Pass the $items to the array.
 *   $build['items'] = $items;
 *
 *   // If no optionset name is provided via $build['settings'], slick will
 *   // fallback to 'default'.
 *   // Optionally override 'default' optionset with custom JS options.
 *   $build['options'] = [
 *     'autoplay' => TRUE,
 *     'dots'     => TRUE,
 *     'arrows'   => FALSE,
 *   ];
 *
 *   // Build the slick.
 *   $element = $slick->build($build);
 *
 *   // Prepare $variables to pass into a .twig.html file.
 *   $variables['slick'] = $element;
 *
 *   // Render the slick at a .twig.html file.
 *   // {{ slick }}
 *   // Or simply return the $element if a renderable array is expected.
 *   return $element;
 * }
 * @endcode
 * @see \Drupal\slick\SlickManager::build()
 * @see template_preprocess_slick_wrapper()
 * @see template_preprocess_slick()
 *
 * @section sec_detail Detailed sample #2
 *
 * This can go to some hook_preprocess() of a target html.twig, or any relevant
 * PHP file.
 *
 * The goal is to create a vertical newsticker, or tweets, with pure text only.
 * First, create an unformatted Views block, says 'Ticker' containing ~ 10
 * titles, or any data for the contents -- using EFQ, or static array will do.
 *
 * Returns the renderable array of a slick instance.
 * @code
 * function my_module_render_slick_detail() {
 *   // Invoke the plugin class, or use a DI service container accordingly.
 *   $slick = \Drupal::service('slick.manager');
 *
 *   // Access the formatter service for image related methods:
 *   $formatter = \Drupal::service('slick.formatter');
 *
 *   $build = [];
 *
 *   // 1.
 *   // Optional $settings, can be removed.
 *   // Provides HTML settings with optionset name and ID, none of JS related.
 *   // To add JS key:value pairs, use #options below instead.
 *   // @see \Drupal\slick\SlickDefault for most supported settings.
 *   $build['settings'] = [
 *     // Optional optionset name, otherwise fallback to default.
 *     // 'optionset' => 'blog',
 *     // Optional skin name fetched from hook_slick_skins_info(), else none.
 *     // 'skin' => 'fullwidth',
 *     // Define the main ID. The rest are managed by the module.
 *     // If you provide ID, be sure unique per instance as it is cached.
 *     // Leave empty to be provided by the module.
 *     'id' => 'slick-ticker',
 *
 *     // Define cache max-age, default to -1 (Cache::PERMANENT) to permanently
 *     // cache the results. Hence a 1 hour is passed. Be sure it is an integer!
 *     'cache' => 3600,
 *   ];
 *
 *   // 3.
 *   // Obligatory #items, as otherwise empty slick.
 *   // Prepare #items, note the 'slide' key is to hold the actual slide
 *   // which can be pure and simple text, or any image/media file.
 *   // Meaning $rows can be text only, or image/audio/video, or a combination
 *   // of both.
 *   // To add caption/overlay, use 'caption' key with the supported sub-keys:
 *   // alt, data, link, overlay, title for complex content.
 *   // Sanitize each sub-key content accordingly.
 *   // @see template_preprocess_slick_slide() for more info.
 *   $items = [];
 *   foreach ($rows as $key => $row) {
 *     // Each item has keys: slide, caption, settings.
 *     $items[] = [
 *       'slide' => $row,
 *
 *       // Optional caption contains: alt, data, link, overlay, title.
 *       // If the above slide is an image, to add text caption, use:
 *       'caption' => ['title' => 'some-caption data'],
 *
 *       // Optional slide settings to manipulate layout, can be removed.
 *       // Individual slide supports some useful settings like layout, classes,
 *       // etc.
 *       // Meaning each slide can have different layout, or classes.
 *       // @see src/Plugin/Field/README.txt
 *       'settings' => [
 *
 *         // Optionally add a custom layout, can be a static uniform value, or
 *         // dynamic one based on the relevant field value.
 *         // @see src/Plugin/Field/README.txt for the supported layout keys.
 *         'layout' => 'bottom',
 *
 *         // Optionally add a custom class, can be a static uniform class, or
 *         // dynamic one based on the relevant field value.
 *         'class' => 'slide--custom-class--' . $key,
 *       ],
 *     ];
 *   }
 *
 *   // Pass the $items to the array.
 *   $build['items'] = $items;
 *
 *   // 4.
 *   // Optional specific JS options, to re-use one optionset, can be removed.
 *   // Play with speed and options to achieve desired result.
 *   // @see config/install/slick.optionset.default.yml
 *   $build['options'] = [
 *     'arrows'    => FALSE,
 *     'autoplay'  => TRUE,
 *     'vertical'  => TRUE,
 *     'draggable' => FALSE,
 *   ];
 *
 *   // 5.
 *   // Build the slick with the arguments as described above.
 *   $element = $slick->build($build);
 *
 *   // Prepare $variables to pass into a .twig.html file.
 *  $variables['slick'] = $element;
 *
 *   // Render the slick at a .twig.html file.
 *   // {{ slick }}
 *   // Or simply return the $element if a renderable array is expected.
 *   return $element;
 * }
 * @endcode
 * @see \Drupal\slick\SlickManager::build()
 * @see template_preprocess_slick_wrapper()
 *
 * @section sec_asnavfor AsNavFor sample #3
 *
 * The only requirement for asNavFor is optionset and optionset_thumbnail IDs:
 * @code
 * $build['settings']['optionset'] = 'optionset_name';
 * $build['settings']['optionset_thumbnail'] = 'optionset_thumbnail_name';
 * @endcode
 *
 * The rest are optional, and will fallback to default:
 *   - $build['settings']['optionset_thumbnail'] = 'optionset_thumbnail_name';
 *     Defined at the main settings.
 *
 *   - $build['settings']['id'] = 'slick-asnavfor';
 *     Only main display ID is needed. The thumbnail ID will be
 *     automatically created: 'slick-asnavfor-thumbnail', including the content
 *     attributes accordingly. If none provided, will fallback to incremented
 *     ID.
 *
 * See the HTML structure below to get a clear idea.
 *
 * 1. Main slider:
 * @code
 *

 *

 *

 *

 *

 * @endcode
 * 2. Thumbnail slider:
 * @code
 *

 *

 *

 *

 *

 * @endcode
 * The asnavfor targets are the 'slick-initialized' attributes, and managed by
 * the module automatically when using SlickManager::build().
 *
 * Returns the renderable array of slick instances.
 * @code
 * function my_module_render_slick_asnavfor() {
 *   // Invoke the plugin class, or use a DI service container accordingly.
 *   $slick = \Drupal::service('slick.manager');
 *
 *   // Access the formatter service for image related methods:
 *   $formatter = \Drupal::service('slick.formatter');
 *
 *   $build = [];
 *
 *   // 1. Main slider ---------------------------------------------------------
 *   // Add the main display items.
 *   $build['items'] = [];
 *
 *   $images = [1, 2, 3, 4, 6, 7];
 *   foreach ($images as $key) {
 *     // Each item has keys: slide, caption, settings.
 *     $build['items'][] = [
 *
 *       // Use $formatter->getImage($element) to have lazyLoad where $element
 *       // contains:
 *       // item: Drupal\image\Plugin\Field\FieldType\ImageItem.
 *       'slide'   => '',
 *
 *       // Main caption contains: alt, data, link, overlay, title keys which
 *       // serve the purpose to have consistent markups and skins without
 *       // bothering much nor remembering what HTML tags and where to place to
 *       // provide for each purpose cosnsitently. CSS will do layout regardless
 *       // HTML composition.
 *       // If having more complex caption data, use 'data' key instead.
 *       // If the common layout doesn't satisfy the need, just override twig.
 *       'caption' => ['title' => 'Description #' . $key],
 *     ];
 *   }
 *
 *   // Optionally override the optionset.
 *   $build['options'] = [
 *     'arrows'        => FALSE,
 *     'centerMode'    => TRUE,
 *     'centerPadding' => '',
 *   ];
 *
 *   // Satisfy the asnavfor main settings.
 *   // @see \Drupal\slick\SlickDefault for most supported settings.
 *   $build['settings'] = [
 *     // The only required is 'optionset_thumbnail'.
 *     // Define both main and thumbnail optionset names at the main display.
 *     'optionset' => 'optionset_main_name',
 *     'optionset_thumbnail' => 'optionset_thumbnail_name',
 *
 *     // The rest is optional, just FYI.
 *     'id' => 'slick-asnavfor',
 *     'skin' => 'skin-main-name',
 *     'skin_thumbnail' => 'skin-thumbnail-name',
 *   ];
 *
 *   // 2. Thumbnail slider ----------------------------------------------------
 *   // The thumbnail array is grouped by 'thumb'.
 *   $build['thumb'] = ['items' => []];
 *   foreach ($images as $key) {
 *     // Each item has keys: slide, caption, settings.
 *     $build['thumb']['items'][] = [
 *       // Use $formatter->getThumbnail($settings) where $settings contain:
 *       // uri, image_style, height, width, alt, title.
 *       'slide'   => '',
 *
 *       // Thumbnail caption accepts direct markup or custom renderable array
 *       // without any special key to be simple as much as complex.
 *       // Think Youtube playlist with scrolling nav: thumbnail, text, etc.
 *       'caption' => ['#markup' => 'Description #' . $key],
 *     ];
 *   }
 *
 *   // Optionally override 'optionset_thumbnail_name' with custom JS options.
 *   $build['thumb']['options'] = [
 *     'arrows'        => TRUE,
 *     'centerMode'    => TRUE,
 *     'centerPadding' => '10px',
 *
 *     // Be sure to have multiple slides for the thumbnail, otherwise nonsense.
 *     'slidesToShow'  => 5,
 *   ];
 *
 *   // Build the slick once.
 *   $element = $slick->build($build);
 *
 *   // Prepare variables to pass into a .twig.html file.
 *   $variables['slick'] = $element;
 *
 *   // Render the slick at a .twig.html file.
 *   // {{ slick }}
 *   // Or simply return the $element if a renderable array is expected.
 *   return $element;
 * }
 * @endcode
 * @see \Drupal\slick\SlickManager::build()
 * @see template_preprocess_slick_wrapper()
 *
 * @section sec_skin Registering Slick skins
 *
 * To register a skin, implement hook_slick_skins_info() in a module file, and
 * defines skins at the registered class which implements SlickSkinInterface.
 *
 * The class must implement \Drupal\slick\SlickSkinInterface, and it has 3
 * supported methods: ::skins(), ::dots(), ::arrows() to have skin options for
 * main/thumbnail/overlay/nested displays, dots, and arrows skins respectively.
 * The declared skins will be available for custom coded, or UI selections.
 *
 * @see \Drupal\slick\SlickSkinInterface
 * @see \Drupal\slick_example\SlickExampleSkin
 * @see \Drupal\slick_extras\SlickExtrasSkin
 *
 * Add the needed methods accordingly.
 * This can be used to register skins for the Slick. Skins will be
 * available when configuring the Optionset, Field formatter, or Views style,
 * or custom coded slicks.
 *
 * Slick skins get a unique CSS class to use for styling, e.g.:
 * If your skin name is "my_module_slick_carousel_rounded", the CSS class is:
 * slick--skin--my-module-slick-carousel-rounded
 *
 * A skin can specify CSS and JS files to include when Slick is displayed,
 * except for a thumbnail skin which accepts CSS only.
 *
 * Each skin supports 5 keys:
 * - name: The human readable name of the skin.
 * - description: The description about the skin, for help and manage pages.
 * - css: An array of CSS files to attach.
 * - js: An array of JS files to attach, e.g.: image zoomer, reflection, etc.
 * - group: A string grouping the current skin: main, thumbnail.
 * - provider: A module name registering the skins.
 *
 * @section sec_skins Defines the Slick main and thumbnail skins
 *
 * @code
 * public function skins() {
 *   $theme_path = base_path() . drupal_get_path('theme', 'my_theme');
 *
 *   return [
 *     'skin_name' => [
 *       // Human readable skin name.
 *       'name' => 'Skin name',
 *
 *       // Description of the skin.
 *       'description' => t('Skin description.'),
 *
 *       // Group skins to reduce confusion on form selection: main, thumbnail.
 *       'group' => 'main',
 *
 *       // Optional module name to prefix the library name.
 *       'provider' => 'my_module',
 *
 *       // Custom assets to be included within a skin, e.g.: Zoom, Reflection,
 *       // Slicebox, etc.
 *       'css' => [
 *         'theme' => [
 *           // Full path to a CSS file to include with the skin.
 *           $theme_path . '/css/my-theme--slider.css' => [],
 *           $theme_path . '/css/my-theme--carousel.css' => [],
 *         ],
 *       ],
 *       'js' => [
 *         // Full path to a JS file to include with the skin.
 *         $theme_path . '/js/my-theme--slider.js' => [],
 *         $theme_path . '/js/my-theme--carousel.js' => [],
 *         // To act on afterSlick event, or any other slick events,
 *         // put a lighter weight before slick.load.min.js (0).
 *         $theme_path . '/js/slick.skin.menu.min.js' => ['weight' => -2],
 *       ],
 *
 *       // Alternatively, add extra library dependencies for re-usable
 *       // libraries. These must be registered as module libraries first.
 *       // Use above CSS and JS directly if reluctant to register libraries.
 *       'dependencies' => [
 *         'my_module/d3',
 *         'my_module/slicebox',
 *         'my_module/zoom',
 *       ],
 *
 *       // Add custom options to be merged into [data-slick] attribute.
 *       // Below is a sample of Slicebox options merged into Slick options.
 *       // These options later can be accessed in the custom JS acccordingly.
 *       'options' => [
 *         'orientation'     => 'r',
 *         'cuboidsCount'    => 7,
 *         'maxCuboidsCount' => 7,
 *         'cuboidsRandom'   => TRUE,
 *         'disperseFactor'  => 30,
 *         'itemAnimation'   => TRUE,
 *         'perspective'     => 1300,
 *         'reflection'      => TRUE,
 *         'effect'          => ['slicebox', 'zoom'],
 *       ],
 *     ],
 *   ];
 * }
 * @endcode
 *
 * @section sec_dots Defines Slick dot skins
 *
 * The provided dot skins will be available at sub-module UI form.
 * A skin dot named 'hop' will have a class 'slick-dots--hop' for the UL.
 *
 * The array is similar to the self::skins(), excluding group, JS.
 * @code
 * public function dots() {
 *   // Create an array of dot skins.
 *   return [];
 * }
 * @endcode
 *
 * @section sec_arrows Defines Slick arrow skins
 *
 * The provided arrow skins will be available at sub-module UI form.
 * A skin arrow 'slit' will have a class 'slick__arrow--slit' for the NAV.
 *
 * The array is similar to the self::skins(), excluding group, JS.
 *
 * @return array
 *   The array of the arrow skins.
 * @code
 * public function arrows() {
 *   // Create an array of arrow skins.
 *   return [];
 * }
 * @endcode
 * @}
 */

/**
 * @addtogroup hooks
 * @{
 */

/**
 * Registers a class that should hold skin definitions.
 *
 * @deprecated, will be removed anytime when a core solution is available.
 * @see #2233261
 * Postponed till D9.
 *
 * @see slick_hook_info()
 * @see slick_example.module
 * @see slick_extras.module
 * @see \Drupal\slick\SlickSkinInterface
 * @see sec_skin
 *
 * @ingroup slick_api
 */
function hook_slick_skins_info() {
  return '\Drupal\my_module\MyModuleSlickSkin';
}

/**
 * Modifies overridable options to re-use one optionset.
 *
 * @see \Drupal\slick\Form\SlickAdmin::getOverridableOptions()
 *
 * @ingroup slick_api
 */
function hook_slick_overridable_options_info_alter(&$options) {
  // Adds RTL option to Slick field formatters, or Slick Views UI.
  $options['rtl'] = t('RTL');
}

/**
 * @} End of "addtogroup hooks".
 */


text:
<!DOCTYPE html>

		<meta charset="UTF-8"/>
		<title>Module utility.config</title>
		<link rel="stylesheet" type="text/css" href="../styles/ddox.css"/>
		<link rel="stylesheet" href="../prettify/prettify.css" type="text/css"/>

								components

								animation

								assetanimation

								assets

								camera

								icomponent

								lights

								material

								mesh

								userinterface

								core

								dgame

								gameobject

								gameobjectcollection

								prefabs

								properties

								reflection

								scene

								graphics

								adapters

								adapter

								linux

								mac

								win32

								shaders

								glsl

								ambientlight

								animatedgeometry

								directionallight

								geometry

								pointlight

								userinterface

								glsl

								shaders

								adapters

								graphics

								shaders

								utility

								awesomium

								concurrency

								config

								filepath

								input

								output

								string

								time

								components

								core

								graphics

								utility

The search functionality needs JavaScript enabled

						<input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/>

Module utility.config

 Defines the static class Config, which handles all configuration options.

Functions

					<col class="caption"/>

						Name
						Description

								constructAmbientLight

						 TODO

								constructConv

						 TODO

								constructDirectionalLight

						 TODO

								constructPointLight

						 TODO

								constructQuaternion

						 TODO

								constructVector2

						 TODO

								constructVector3

						 TODO

								loadYamlDocuments

						 Process all yaml files in a directory.

								loadYamlFile

						 Load a yaml file with the engine-specific mappings.

								loadYamlObjects

						 Processes all yaml files in a directory, and converts each document into an object of type T.

Classes

					<col class="caption"/>

						Name
						Description

								Config

						 Static class which handles the configuration options and YAML interactions.

Authors

Copyright

License


text:
BundleEvent
-----------

.. doxygengroup:: gr_bundleevent
   :content-only:


text:
echo off

set esbToolkitPath="C:\Program Files (x86)\Microsoft BizTalk ESB Toolkit\Bin"
set logFile=".\Log"

if not exist %logFile% mkdir %logFile%

echo ***
echo *** >> %logFile%

echo Import Ajax itinerary
echo Import Ajax itinerary >> %logFile%

esbimportutil /f:Ajax.xml /c:deployed >> %logFile%

echo Import done
echo Import done >> %logFile%

echo ***
echo *** >> %logFile%

pause


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Globalization;
using System.Linq;
using Microsoft.Rest.Generator.ClientModel;
using Microsoft.Rest.Generator.Utilities;
using System.Text.RegularExpressions;
namespace Microsoft.Rest.Generator.NodeJS.TemplateModels
{
    using System.Collections.Generic;

    public static class ClientModelExtensions
    {
        public static string GetHttpMethod(this HttpMethod method)
        {
            if (method == HttpMethod.Patch)
            {
                return "new HttpMethod(\"Patch\")";
            }
            else
            {
                return string.Format(CultureInfo.InvariantCulture, "HttpMethod.{0}", method);
            }
        }

        /// <summary>
        /// Format the value of a sequence given the modeled element format.  Note that only sequences of strings are supported
        /// </summary>
        /// <param name="parameter">The parameter to format</param>
        /// <returns>A reference to the formatted parameter value</returns>
        public static string GetFormattedReferenceValue(this Parameter parameter)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException("parameter");
            }

            SequenceType sequence = parameter.Type as SequenceType;
            if (sequence == null)
            {
                return parameter.Type.ToString(parameter.Name);
            }

            PrimaryType primaryType = sequence.ElementType as PrimaryType;
            EnumType enumType = sequence.ElementType as EnumType;
            if (enumType != null && enumType.ModelAsString)
            {
                primaryType = PrimaryType.String;
            }

            if (primaryType != PrimaryType.String)
            {
                throw new InvalidOperationException(
                    string.Format(CultureInfo.InvariantCulture,
                    "Cannot generate a formatted sequence from a " +
                                  "non-string array parameter {0}", parameter));
            }

            return string.Format(CultureInfo.InvariantCulture,
                "{0}.join('{1}')", parameter.Name, parameter.CollectionFormat.GetSeparator());
        }

        /// <summary>
        /// Return the separator associated with a given collectionFormat
        /// </summary>
        /// <param name="format">The collection format</param>
        /// <returns>The separator</returns>
        private static string GetSeparator(this CollectionFormat format)
        {
            switch (format)
            {
                case CollectionFormat.Csv:
                    return ",";
                case CollectionFormat.Pipes:
                    return "|";
                case CollectionFormat.Ssv:
                    return " ";
                case CollectionFormat.Tsv:
                    return "\t";
                default:
                    throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture,
                        "Collection format {0} is not supported.", format));
            }
        }

        private static string NormalizeValueReference(this string valueReference)
        {
            Regex pattern = new Regex("['.\\[\\]]");
            return pattern.Replace(valueReference, "");
        }

        private static string GetBasePropertyFromUnflattenedProperty(this string property)
        {
            string result = null;
            if (property.Contains("]["))
            {
                result = property.Substring(0, property.IndexOf("][", StringComparison.OrdinalIgnoreCase) + 1);
            }

            return result;
        }

        /// <summary>
        /// Simple conversion of the type to string
        /// </summary>
        /// <param name="type">The type to convert</param>
        /// <param name="reference">a reference to an instance of the type</param>
        /// <returns></returns>
        public static string ToString(this IType type, string reference)
        {
            var known = type as PrimaryType;
            var enumType = type as EnumType;
            if (enumType != null || known == PrimaryType.String)
            {
                return reference;
            }

            if (known == PrimaryType.Date)
            {
                return string.Format(CultureInfo.InvariantCulture,
                    "msRest.serializeObject({0}).replace(/[Tt].*[Zz]/, '')", reference);
            }

            if (known == PrimaryType.DateTimeRfc1123)
            {
                return string.Format(CultureInfo.InvariantCulture, "{0}.toUTCString()", reference);
            }

            if (known == PrimaryType.DateTime ||
                known == PrimaryType.ByteArray)
            {
                return string.Format(CultureInfo.InvariantCulture,
                    "msRest.serializeObject({0})", reference);
            }

            if (known == PrimaryType.TimeSpan)
            {
                return string.Format(CultureInfo.InvariantCulture,
                    "{0}.toISOString()", reference);
            }

            return string.Format(CultureInfo.InvariantCulture, "{0}.toString()", reference);
        }

        /// <summary>
        /// Returns a Javascript Array containing the values in a string enum type
        /// </summary>
        /// <param name="type">EnumType to model as Javascript Array</param>
        /// <returns>The Javascript Array as a string</returns>
        public static string GetEnumValuesArray(this EnumType type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            return string.Format(CultureInfo.InvariantCulture,
                "[ {0} ]", string.Join(", ",
                type.Values.Select(p => string.Format(CultureInfo.InvariantCulture, "'{0}'", p.Name))));
        }

        public static string EscapeSingleQuotes(this string valueReference)
        {
            if (valueReference == null)
            {
                throw new ArgumentNullException("valueReference");
            }

            return valueReference.Replace("'", "\\'");
        }

        private static IndentedStringBuilder ConstructValidationCheck(IndentedStringBuilder builder, string errorMessage, string valueReference, string typeName)
        {
            var escapedValueReference = valueReference.EscapeSingleQuotes();
            var lowercaseTypeName = typeName.ToLower(CultureInfo.InvariantCulture);

            return builder.Indent()
                            .AppendLine(errorMessage, escapedValueReference, lowercaseTypeName)
                          .Outdent()
                          .AppendLine("}");
        }

        private static string ValidatePrimaryType(this PrimaryType primary, IScopeProvider scope, string valueReference, bool isRequired)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var requiredTypeErrorMessage = "throw new Error('{0} cannot be null or undefined and it must be of type {1}.');";
            var typeErrorMessage = "throw new Error('{0} must be of type {1}.');";
            var lowercaseTypeName = primary.Name.ToLower(CultureInfo.InvariantCulture);
            if (primary == PrimaryType.Boolean ||
                primary == PrimaryType.Double ||
                primary == PrimaryType.Decimal ||
                primary == PrimaryType.Int ||
                primary == PrimaryType.Long ||
                primary == PrimaryType.Object)
            {
                if (isRequired)
                {
                    builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0} !== '{1}') {{", valueReference, lowercaseTypeName);
                    return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString();
                }

                builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0} !== '{1}') {{", valueReference, lowercaseTypeName);
                return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString();
            }
            else if (primary == PrimaryType.String)
            {
                if (isRequired)
                {
                    //empty string can be a valid value hence we cannot implement the simple check if (!{0})
                    builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName);
                    return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString();
                }

                builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName);
                return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString();
            }
            else if (primary == PrimaryType.ByteArray)
            {
                if (isRequired)
                {
                    builder.AppendLine("if (!Buffer.isBuffer({0})) {{", valueReference, lowercaseTypeName);
                    return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString();
                }

                builder.AppendLine("if ({0} && !Buffer.isBuffer({0})) {{", valueReference, lowercaseTypeName);
                return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString();
            }
            else if (primary == PrimaryType.DateTime || primary == PrimaryType.Date || primary == PrimaryType.DateTimeRfc1123)
            {
                if (isRequired)
                {
                    builder.AppendLine("if(!{0} || !({0} instanceof Date || ", valueReference)
                                                  .Indent()
                                                  .Indent()
                                                  .AppendLine("(typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{", valueReference);
                    return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString();
                }

                builder = builder.AppendLine("if ({0} && !({0} instanceof Date || ", valueReference)
                                              .Indent()
                                              .Indent()
                                              .AppendLine("(typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{", valueReference);
                return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString();
            }
            else if (primary == PrimaryType.TimeSpan)
            {
                if (isRequired)
                {
                    builder.AppendLine("if(!{0} || !moment.isDuration({0})) {{", valueReference);
                    return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString();
                }

                builder.AppendLine("if({0} && !moment.isDuration({0})) {{", valueReference);
                return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString();
            }
            else
            {
                throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture,
                    "'{0}' not implemented", valueReference));
            }
        }

        /// <summary>
        /// Returns the TypeScript type string for the specified primary type
        /// </summary>
        /// <param name="primary">primary type to query</param>
        /// <returns>The TypeScript type correspoinding to this model primary type</returns>
        private static string PrimaryTSType(this PrimaryType primary)
        {
            if (primary == PrimaryType.Boolean)
                return "boolean";
            else if (primary == PrimaryType.Double || primary == PrimaryType.Decimal || primary == PrimaryType.Int || primary == PrimaryType.Long)
                return "number";
            else if (primary == PrimaryType.String)
                return "string";
            else if (primary == PrimaryType.Date || primary == PrimaryType.DateTime || primary == PrimaryType.DateTimeRfc1123)
                return "Date";
            else if (primary == PrimaryType.Object)
                return "any";   // TODO: test this
            else if (primary == PrimaryType.ByteArray)
                return "Buffer";
            else if (primary == PrimaryType.Stream)
                return "stream.Readable";
            else if (primary == PrimaryType.TimeSpan)
                return "moment.Duration"; //TODO: test this, add include for it
            else {
                throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture,
                    "Type '{0}' not implemented", primary));
            }
        }

        private static string ValidateEnumType(this EnumType enumType, IScopeProvider scope, string valueReference, bool isRequired)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var allowedValues = scope.GetVariableName("allowedValues");

            builder.AppendLine("if ({0}) {{", valueReference)
                        .Indent()
                            .AppendLine("var {0} = {1};", allowedValues, enumType.GetEnumValuesArray())
                            .AppendLine("if (!{0}.some( function(item) {{ return item === {1}; }})) {{", allowedValues, valueReference)
                            .Indent()
                                .AppendLine("throw new Error({0} + ' is not a valid value. The valid values are: ' + {1});", valueReference, allowedValues)
                            .Outdent()
                            .AppendLine("}")
                        .Outdent()
                        .AppendLine("}");
            if (isRequired)
            {
                builder.Append(" else {")
                    .Indent()
                        .AppendLine("throw new Error('{0} cannot be null or undefined.');", valueReference)
                    .Outdent()
                    .AppendLine("}");
            }

            return builder.ToString();
        }

        private static string ValidateCompositeType(IScopeProvider scope, string valueReference, bool isRequired)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var escapedValueReference = valueReference.EscapeSingleQuotes();
            //Only validate whether the composite type is present, if it is required. Detailed validation happens in serialization.
            if (isRequired)
            {
                builder.AppendLine("if ({0} === null || {0} === undefined) {{", valueReference)
                         .Indent()
                         .AppendLine("throw new Error('{0} cannot be null or undefined.');", escapedValueReference)
                       .Outdent()
                       .AppendLine("}");
            }
            return builder.ToString();
        }

        private static string ValidateSequenceType(this SequenceType sequence, IScopeProvider scope, string valueReference, bool isRequired, string modelReference = "client._models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var escapedValueReference = valueReference.EscapeSingleQuotes();

            var indexVar = scope.GetVariableName("i");
            var innerValidation = sequence.ElementType.ValidateType(scope, valueReference + "[" + indexVar + "]", false, modelReference);
            if (!string.IsNullOrEmpty(innerValidation))
            {
                if (isRequired)
                {
                    return builder.AppendLine("if (!util.isArray({0})) {{", valueReference)
                        .Indent()
                          .AppendLine("throw new Error('{0} cannot be null or undefined and it must be of type {1}.');",
                          escapedValueReference, sequence.Name.ToLower(CultureInfo.InvariantCulture))
                        .Outdent()
                      .AppendLine("}")
                      .AppendLine("for (var {1} = 0; {1} < {0}.length; {1}++) {{", valueReference, indexVar)
                            .Indent()
                              .AppendLine(innerValidation)
                            .Outdent()
                          .AppendLine("}").ToString();
                }

                return builder.AppendLine("if (util.isArray({0})) {{", valueReference)
                        .Indent()
                          .AppendLine("for (var {1} = 0; {1} < {0}.length; {1}++) {{", valueReference, indexVar)
                            .Indent()
                              .AppendLine(innerValidation)
                            .Outdent()
                          .AppendLine("}")
                        .Outdent()
                      .AppendLine("}").ToString();
            }

            return null;
        }

        private static string ValidateDictionaryType(this DictionaryType dictionary, IScopeProvider scope, string valueReference, bool isRequired, string modelReference = "client._models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var escapedValueReference = valueReference.EscapeSingleQuotes();
            var valueVar = scope.GetVariableName("valueElement");
            var innerValidation = dictionary.ValueType.ValidateType(scope, valueReference + "[" + valueVar + "]", false, modelReference);
            if (!string.IsNullOrEmpty(innerValidation))
            {
                if (isRequired)
                {
                    return builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0} !== 'object') {{", valueReference)
                        .Indent()
                          .AppendLine("throw new Error('{0} cannot be null or undefined and it must be of type {1}.');",
                            escapedValueReference, dictionary.Name.ToLower(CultureInfo.InvariantCulture))
                        .Outdent()
                      .AppendLine("}")
                      .AppendLine("for(var {0} in {1}) {{", valueVar, valueReference)
                        .Indent()
                          .AppendLine(innerValidation)
                        .Outdent()
                      .AppendLine("}").ToString();
                }

                return builder.AppendLine("if ({0} && typeof {0} === 'object') {{", valueReference)
                        .Indent()
                          .AppendLine("for(var {0} in {1}) {{", valueVar, valueReference)
                            .Indent()
                              .AppendLine(innerValidation)
                            .Outdent()
                          .AppendLine("}")
                        .Outdent()
                      .AppendLine("}").ToString();
            }

            return null;
        }

        /// <summary>
        /// Generate code to perform validation on a parameter or property
        /// </summary>
        /// <param name="type">The type to validate</param>
        /// <param name="scope">A scope provider for generating variable names as necessary</param>
        /// <param name="valueReference">A reference to the value being validated</param>
        /// <param name="isRequired">True if the parameter is required.</param>
        /// <param name="modelReference">A reference to the models array</param>
        /// <returns>The code to validate the reference of the given type</returns>
        public static string ValidateType(this IType type, IScopeProvider scope, string valueReference, bool isRequired, string modelReference = "client._models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            CompositeType composite = type as CompositeType;
            SequenceType sequence = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;
            PrimaryType primary = type as PrimaryType;
            EnumType enumType = type as EnumType;
            if (primary != null)
            {
                return primary.ValidatePrimaryType(scope, valueReference, isRequired);
            }
            else if (enumType != null && enumType.Values.Any())
            {
                return enumType.ValidateEnumType(scope, valueReference, isRequired);
            }
            else if (composite != null && composite.Properties.Any())
            {
                return ValidateCompositeType(scope, valueReference, isRequired);
            }
            else if (sequence != null)
            {
                return sequence.ValidateSequenceType(scope, valueReference, isRequired, modelReference);
            }
            else if (dictionary != null)
            {
                return dictionary.ValidateDictionaryType(scope, valueReference, isRequired, modelReference);
            }

            return null;
        }

        /// <summary>
        /// Return the TypeScript type (as a string) for specified type.
        /// </summary>
        public static string TSType(this IType type, bool inModelsModule) {
            CompositeType composite = type as CompositeType;
            SequenceType sequence = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;
            PrimaryType primary = type as PrimaryType;
            EnumType enumType = type as EnumType;

            string tsType;
            if (primary != null)
            {
                tsType = primary.PrimaryTSType();
            }
            else if (enumType != null)
            {
                tsType = "string";
            }
            else if (composite != null)
            {
                if (inModelsModule)
                    tsType = composite.Name;
                else tsType = "models." + composite.Name;
            }
            else if (sequence != null)
            {
                tsType = sequence.ElementType.TSType(inModelsModule) + "[]";
            }
            else if (dictionary != null)
            {
                // TODO: Confirm with Mark exactly what cases for additionalProperties AutoRest intends to handle (what about
                // additonalProperties combined with explicit properties?) and add support for those if needed to at least match
                // C# target level of functionality
                tsType = "{ [propertyName: string]: " + dictionary.ValueType.TSType(inModelsModule) + " }";
            }
            else throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "Type '{0}' not implemented", type));

            return tsType;
        }

        private static string SerializePrimaryType(this PrimaryType primary, IScopeProvider scope, string objectReference, string valueReference, bool isRequired)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var requiredTypeErrorMessage = "throw new Error('{0} cannot be null or undefined and it must be of type {1}.');";
            var typeErrorMessage = "throw new Error('{0} must be of type {1}.');";
            var lowercaseTypeName = primary.Name.ToLower(CultureInfo.InvariantCulture);

            if (primary == PrimaryType.Boolean ||
                primary == PrimaryType.Double ||
                primary == PrimaryType.Decimal ||
                primary == PrimaryType.Int ||
                primary == PrimaryType.Long ||
                primary == PrimaryType.Object)
            {
                if (isRequired)
                {
                    builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0} !== '{1}') {{",
                        objectReference, lowercaseTypeName);
                    builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name);
                    builder = ConstructBasePropertyCheck(builder, valueReference);
                    return builder.AppendLine("{0} = {1};", valueReference, objectReference).ToString();
                }
                builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", objectReference)
                         .Indent()
                         .AppendLine("if (typeof {0} !== '{1}') {{", objectReference, lowercaseTypeName);
                builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name);
                builder = ConstructBasePropertyCheck(builder, valueReference);
                return builder.AppendLine("{0} = {1};", valueReference, objectReference)
                            .Outdent()
                            .AppendLine("}").ToString();
            }
            else if (primary == PrimaryType.String)
            {
                if (isRequired)
                {
                    //empty string can be a valid value hence we cannot implement the simple check if (!{0})
                    builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0}.valueOf() !== '{1}') {{",
                        objectReference, lowercaseTypeName);
                    builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name);
                    builder = ConstructBasePropertyCheck(builder, valueReference);
                    return builder.AppendLine("{0} = {1};", valueReference, objectReference).ToString();
                }
                builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", objectReference)
                         .Indent()
                         .AppendLine("if (typeof {0}.valueOf() !== '{1}') {{", objectReference, lowercaseTypeName);
                builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name);
                builder = ConstructBasePropertyCheck(builder, valueReference);
                return builder.AppendLine("{0} = {1};", valueReference, objectReference)
                            .Outdent()
                            .AppendLine("}").ToString();
            }
            else if (primary == PrimaryType.ByteArray)
            {
                if (isRequired)
                {
                    builder.AppendLine("if (!Buffer.isBuffer({0})) {{", objectReference);
                    builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name);
                    builder = ConstructBasePropertyCheck(builder, valueReference);
                    return builder.AppendLine("{0} = {1}.toString('base64');", valueReference, objectReference).ToString();
                }
                builder.AppendLine("if ({0}) {{", objectReference)
                         .Indent()
                         .AppendLine("if (!Buffer.isBuffer({0})) {{", objectReference);
                builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name);
                builder = ConstructBasePropertyCheck(builder, valueReference);
                return builder.AppendLine("{0} = {1}.toString('base64');", valueReference, objectReference)
                            .Outdent()
                            .AppendLine("}").ToString();
            }
            else if (primary == PrimaryType.Date)
            {
                if (isRequired)
                {
                    builder.AppendLine("if(!{0} || !({0} instanceof Date || (typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{",
                        objectReference);
                    builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name);
                    builder = ConstructBasePropertyCheck(builder, valueReference);
                    return builder.AppendLine("{0} = ({1} instanceof Date) ? {1}.toISOString().substring(0,10) : {1};",
                        valueReference, objectReference).ToString();
                }

                builder.AppendLine("if ({0}) {{", objectReference)
                         .Indent()
                         .AppendLine("if (!({0} instanceof Date || typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0})))) {{",
                         objectReference);
                builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name);
                builder = ConstructBasePropertyCheck(builder, valueReference);
                return builder.AppendLine("{0} = ({1} instanceof Date) ? {1}.toISOString().substring(0,10) : {1};", valueReference, objectReference)
                                .Outdent()
                                .AppendLine("}").ToString();
            }
            else if (primary == PrimaryType.DateTime)
            {
                if (isRequired)
                {
                    builder.AppendLine("if(!{0} || !({0} instanceof Date || (typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{",
                        objectReference);
                    builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name);
                    builder = ConstructBasePropertyCheck(builder, valueReference);
                    return builder.AppendLine("{0} = ({1} instanceof Date) ? {1}.toISOString() : {1};",
                        valueReference, objectReference).ToString();
                }

                builder.AppendLine("if ({0}) {{", objectReference)
                         .Indent()
                         .AppendLine("if (!({0} instanceof Date || typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0})))) {{",
                         objectReference);
                builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name);
                builder = ConstructBasePropertyCheck(builder, valueReference);
                return builder.AppendLine("{0} = ({1} instanceof Date) ? {1}.toISOString() : {1};", valueReference, objectReference)
                                .Outdent()
                                .AppendLine("}").ToString();
            }
            else if (primary == PrimaryType.DateTimeRfc1123)
            {
                if (isRequired)
                {
                    builder.AppendLine("if(!{0} || !({0} instanceof Date || (typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{",
                        objectReference);
                    builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name);
                    builder = ConstructBasePropertyCheck(builder, valueReference);
                    return builder.AppendLine("{0} = ({1} instanceof Date) ? {1}.toUTCString() : {1};",
                        valueReference, objectReference).ToString();
                }

                builder.AppendLine("if ({0}) {{", objectReference)
                         .Indent()
                         .AppendLine("if (!({0} instanceof Date || typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0})))) {{",
                         objectReference);
                builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name);
                builder = ConstructBasePropertyCheck(builder, valueReference);
                return builder.AppendLine("{0} = ({1} instanceof Date) ? {1}.toUTCString() : {1};", valueReference, objectReference)
                                .Outdent()
                                .AppendLine("}").ToString();
            }
            else if (primary == PrimaryType.TimeSpan)
            {
                if (isRequired)
                {
                    builder.AppendLine("if(!{0} || !moment.isDuration({0})) {{", objectReference);
                    builder = ConstructValidationCheck(builder, requiredTypeErrorMessage, objectReference, primary.Name);
                    builder = ConstructBasePropertyCheck(builder, valueReference);
                    return builder.AppendLine("{0} = {1}.toISOString();", valueReference, objectReference).ToString();
                }

                builder.AppendLine("if ({0}) {{", objectReference)
                         .Indent()
                         .AppendLine("if (!moment.isDuration({0})) {{",
                         objectReference);
                builder = ConstructValidationCheck(builder, typeErrorMessage, objectReference, primary.Name);
                builder = ConstructBasePropertyCheck(builder, valueReference);
                return builder.AppendLine("{0} = {1}.toISOString();", valueReference, objectReference)
                                .Outdent()
                                .AppendLine("}").ToString();
            }
            else
            {
                throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture,
                    "'{0}' not implemented", valueReference));
            }
        }

        private static IndentedStringBuilder ConstructBasePropertyCheck(IndentedStringBuilder builder, string valueReference)
        {
            string baseProperty = valueReference.GetBasePropertyFromUnflattenedProperty();
            if (baseProperty != null)
            {
                builder.AppendLine("if ({0} === null || {0} === undefined) {{", baseProperty)
                         .Indent()
                         .AppendLine("{0} = {{}};", baseProperty)
                       .Outdent()
                       .AppendLine("}");
            }

            return builder;
        }

        private static string SerializeEnumType(this EnumType enumType, IScopeProvider scope, string objectReference, string valueReference, bool isRequired)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var allowedValues = scope.GetVariableName("allowedValues");
            string tempReference = objectReference;
            builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", objectReference)
                        .Indent()
                        .AppendLine("var {0} = {1};", allowedValues, enumType.GetEnumValuesArray());
                        if (objectReference.IndexOfAny(new char[] { '.', '[', ']'}) >= 0)
                        {
                            tempReference = tempReference.NormalizeValueReference();
                            builder.AppendLine("var {0} = {1};", tempReference, objectReference);
                        }
                        builder.AppendLine("if (!{0}.some( function(item) {{ return item === {1}; }})) {{", allowedValues, tempReference)
                                    .Indent()
                                    .AppendLine("throw new Error({0} + ' is not a valid value. The valid values are: ' + {1});", objectReference, allowedValues)
                                .Outdent()
                                .AppendLine("}");
                        builder = ConstructBasePropertyCheck(builder, valueReference);
                        builder.AppendLine("{0} = {1};", valueReference, objectReference)
                              .Outdent()
                              .AppendLine("}");
            if (isRequired)
            {
                builder.Append(" else {")
                    .Indent()
                        .AppendLine("throw new Error('{0} cannot be null or undefined.');", objectReference)
                    .Outdent()
                    .AppendLine("}");
            }

            return builder.ToString();
        }

        private static string SerializeCompositeType(this CompositeType composite, IScopeProvider scope, string objectReference,
            string valueReference, bool isRequired, string modelReference = "client._models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var escapedObjectReference = objectReference.EscapeSingleQuotes();

            builder.AppendLine("if ({0}) {{", objectReference).Indent();

            if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator))
            {
                builder.AppendLine("if({0}['{1}'] !== null && {0}['{1}'] !== undefined && {2}.discriminators[{0}['{1}']]) {{",
                                    objectReference,
                                    composite.PolymorphicDiscriminator, modelReference)
                    .Indent();
                builder = ConstructBasePropertyCheck(builder, valueReference);
                builder.AppendLine("{0} = {1}.serialize();", valueReference, objectReference)
                    .Outdent()
                    .AppendLine("}} else {{", valueReference)
                    .Indent()
                        .AppendLine("throw new Error('No discriminator field \"{0}\" was found in parameter \"{1}\".');",
                                    composite.PolymorphicDiscriminator,
                                    escapedObjectReference)
                    .Outdent()
                    .AppendLine("}");
            }
            else
            {
                builder = ConstructBasePropertyCheck(builder, valueReference);
                builder.AppendLine("{0} = {1}.serialize();", valueReference, objectReference);
            }
            builder.Outdent().AppendLine("}");

            if (isRequired)
            {
                builder.Append(" else {")
                    .Indent()
                        .AppendLine("throw new Error('{0} cannot be null or undefined.');", escapedObjectReference)
                    .Outdent()
                    .AppendLine("}");
            }
            return builder.ToString();
        }

        private static string SerializeSequenceType(this SequenceType sequence, IScopeProvider scope, string objectReference,
            string valueReference, bool isRequired, string modelReference = "client._models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var escapedObjectReference = objectReference.EscapeSingleQuotes();

            var indexVar = scope.GetVariableName("i");
            var innerSerialization = sequence.ElementType.SerializeType(scope, objectReference + "[" + indexVar + "]", valueReference + "[" + indexVar + "]", false, modelReference);
            if (!string.IsNullOrEmpty(innerSerialization))
            {
                if (isRequired)
                {
                    return builder.AppendLine("if (!util.isArray({0})) {{", objectReference)
                        .Indent()
                          .AppendLine("throw new Error('{0} cannot be null or undefined and it must be of type {1}.');",
                          escapedObjectReference, sequence.Name.ToLower(CultureInfo.InvariantCulture))
                        .Outdent()
                      .AppendLine("}")
                      .AppendLine("{0} = [];", valueReference)
                      .AppendLine("for (var {1} = 0; {1} < {0}.length; {1}++) {{", objectReference, indexVar)
                            .Indent()
                              .AppendLine(innerSerialization)
                            .Outdent()
                          .AppendLine("}").ToString();
                }

                return builder.AppendLine("if (util.isArray({0})) {{", objectReference)
                        .Indent()
                          .AppendLine("{0} = [];", valueReference)
                          .AppendLine("for (var {1} = 0; {1} < {0}.length; {1}++) {{", objectReference, indexVar)
                            .Indent()
                              .AppendLine(innerSerialization)
                            .Outdent()
                          .AppendLine("}")
                        .Outdent()
                      .AppendLine("}").ToString();
            }

            return null;
        }

        private static string SerializeDictionaryType(this DictionaryType dictionary, IScopeProvider scope, string objectReference, string valueReference,
            bool isRequired, string modelReference = "client._models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var escapedObjectReference = objectReference.EscapeSingleQuotes();
            var valueVar = scope.GetVariableName("valueElement");
            var innerSerialization = dictionary.ValueType.SerializeType(scope, objectReference + "[" + valueVar + "]", valueReference + "[" + valueVar + "]", false, modelReference);
            if (!string.IsNullOrEmpty(innerSerialization))
            {
                if (isRequired)
                {
                    return builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0} !== 'object') {{", objectReference)
                        .Indent()
                          .AppendLine("throw new Error('{0} cannot be null or undefined and it must be of type {1}.');",
                            escapedObjectReference, dictionary.Name.ToLower(CultureInfo.InvariantCulture))
                        .Outdent()
                      .AppendLine("}")
                      .AppendLine("{0} = {{}};", valueReference)
                      .AppendLine("for(var {0} in {1}) {{", valueVar, objectReference)
                        .Indent()
                          .AppendLine(innerSerialization)
                        .Outdent()
                      .AppendLine("}").ToString();
                }

                return builder.AppendLine("if ({0} && typeof {0} === 'object') {{", objectReference)
                        .Indent()
                          .AppendLine("{0} = {{}};", valueReference)
                          .AppendLine("for(var {0} in {1}) {{", valueVar, objectReference)
                            .Indent()
                              .AppendLine(innerSerialization)
                              .AppendLine("else {")
                                .Indent()
                                .AppendLine("{0} = {1};", valueReference + "[" + valueVar + "]", objectReference + "[" + valueVar + "]")
                              .Outdent()
                              .AppendLine("}")
                            .Outdent()
                          .AppendLine("}")
                        .Outdent()
                      .AppendLine("}").ToString();
            }

            return null;
        }

        /// <summary>
        /// Generate code to perform serialization on a parameter or property
        /// </summary>
        /// <param name="type">The type to validate</param>
        /// <param name="scope">A scope provider for generating variable names as necessary</param>
        /// <param name="objectReference">A reference to the object being serialized</param>
        /// <param name="valueReference">A reference to the value that will be assigned the serialized object</param>
        /// <param name="isRequired">True if the parameter or property is required.</param>
        /// <param name="modelReference">A reference to the models</param>
        /// <returns>The code to serialize the given type</returns>
        public static string SerializeType(this IType type, IScopeProvider scope, string objectReference, string valueReference, bool isRequired, string modelReference = "client._models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            CompositeType composite = type as CompositeType;
            SequenceType sequence = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;
            PrimaryType primary = type as PrimaryType;
            EnumType enumType = type as EnumType;
            if (primary != null)
            {
                return primary.SerializePrimaryType(scope, objectReference, valueReference, isRequired);
            }
            else if (enumType != null && enumType.Values.Any())
            {
                return enumType.SerializeEnumType(scope, objectReference, valueReference, isRequired);
            }
            else if (composite != null && composite.Properties.Any())
            {
                return composite.SerializeCompositeType(scope, objectReference, valueReference, isRequired, modelReference);
            }
            else if (sequence != null)
            {
                return sequence.SerializeSequenceType(scope, objectReference, valueReference, isRequired, modelReference);
            }
            else if (dictionary != null)
            {
                return dictionary.SerializeDictionaryType(scope, objectReference, valueReference, isRequired, modelReference);
            }

            return null;
        }

        /// <summary>
        /// Generate code to perform deserialization on a parameter or property
        /// </summary>
        /// <param name="type">The type to deserialize</param>
        /// <param name="scope">A scope provider for generating variable names as necessary</param>
        /// <param name="objectReference">A reference to the object that will be assigned the deserialized value</param>
        /// <param name="valueReference">A reference to the value being deserialized</param>
        /// <param name="modelReference">A reference to the models</param>
        /// <returns>The code to deserialize the given type</returns>
        public static string DeserializeType(this IType type, IScopeProvider scope, string objectReference, string valueReference, string modelReference = "self._models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            EnumType enumType = type as EnumType;
            CompositeType composite = type as CompositeType;
            SequenceType sequence = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;
            PrimaryType primary = type as PrimaryType;
            var builder = new IndentedStringBuilder("  ");
            string baseProperty = valueReference.GetBasePropertyFromUnflattenedProperty();
            if (baseProperty != null)
            {
                builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", baseProperty).Indent();
            }
            if (enumType != null)
            {
                builder = ProcessBasicType(objectReference, valueReference, builder);
            }
            else if (primary != null)
            {
                if (primary == PrimaryType.ByteArray)
                {
                    builder.AppendLine("if ({0}) {{", valueReference)
                             .Indent()
                             .AppendLine("{1} = new Buffer({0}, 'base64');", valueReference, objectReference)
                           .Outdent().AppendLine("}")
                           .AppendLine("else if ({0} !== undefined) {{", valueReference)
                             .Indent()
                             .AppendLine("{1} = {0};", valueReference, objectReference)
                           .Outdent()
                           .AppendLine("}");
                }
                else if (primary == PrimaryType.DateTime || primary == PrimaryType.Date || primary == PrimaryType.DateTimeRfc1123)
                {
                    builder.AppendLine("if ({0}) {{", valueReference)
                             .Indent()
                             .AppendLine("{1} = new Date({0});", valueReference, objectReference)
                           .Outdent()
                           .AppendLine("}")
                           .AppendLine("else if ({0} !== undefined) {{", valueReference)
                             .Indent()
                             .AppendLine("{1} = {0};", valueReference, objectReference)
                           .Outdent()
                           .AppendLine("}");
                }
                else if (primary == PrimaryType.TimeSpan)
                {
                    builder.AppendLine("if ({0}) {{", valueReference)
                             .Indent()
                             .AppendLine("{1} = moment.duration({0});", valueReference, objectReference)
                           .Outdent()
                           .AppendLine("}")
                           .AppendLine("else if ({0} !== undefined) {{", valueReference)
                             .Indent()
                             .AppendLine("{1} = {0};", valueReference, objectReference)
                           .Outdent()
                           .AppendLine("}");
                }
                else
                {
                    builder.AppendLine("if ({0} !== undefined) {{", valueReference)
                             .Indent()
                             .AppendLine("{1} = {0};", valueReference, objectReference)
                           .Outdent()
                           .AppendLine("}");
                }
            }
            else if (composite != null && composite.Properties.Any())
            {
                builder = composite.ProcessCompositeType(objectReference, valueReference, modelReference, builder, "DeserializeType");
            }
            else if (sequence != null)
            {
                builder = sequence.ProcessSequenceType(scope, objectReference, valueReference, modelReference, builder, "DeserializeType");
            }
            else if (dictionary != null)
            {
                builder = dictionary.ProcessDictionaryType(scope, objectReference, valueReference, modelReference, builder, "DeserializeType");
            }

            if (baseProperty != null)
            {
                builder.Outdent().AppendLine("}");
            }

            return builder.ToString();
        }

        public static string InitializeType(this IType type, IScopeProvider scope, string objectReference, string valueReference, string modelReference = "models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            EnumType enumType = type as EnumType;
            CompositeType composite = type as CompositeType;
            SequenceType sequence = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;
            PrimaryType primary = type as PrimaryType;
            var builder = new IndentedStringBuilder("  ");
            if (enumType != null || primary != null)
            {
                builder = ProcessBasicType(objectReference, valueReference, builder);
            }
            else if (composite != null && composite.Properties.Any())
            {
                builder = composite.ProcessCompositeType(objectReference, valueReference, modelReference, builder, "InitializeType");
            }
            else if (sequence != null)
            {
                builder = sequence.ProcessSequenceType(scope, objectReference, valueReference, modelReference, builder, "InitializeType");
            }
            else if (dictionary != null)
            {
                builder = dictionary.ProcessDictionaryType(scope, objectReference, valueReference, modelReference, builder, "InitializeType");
            }

            return builder.ToString();
        }

        public static string InitializeSerializationType(this IType type, IScopeProvider scope, string objectReference, string valueReference, string modelReference = "models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            CompositeType composite = type as CompositeType;
            SequenceType sequence = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;
            var builder = new IndentedStringBuilder("  ");
            if (composite != null && composite.Properties.Any())
            {
                builder = composite.ProcessCompositeType(objectReference, valueReference, modelReference, builder, "InitializeSerializationType");
            }
            else if (sequence != null)
            {
                builder = sequence.ProcessSequenceType(scope, objectReference, valueReference, modelReference, builder, "InitializeSerializationType");
            }
            else if (dictionary != null)
            {
                builder = dictionary.ProcessDictionaryType(scope, objectReference, valueReference, modelReference, builder, "InitializeSerializationType");
            }

            return builder.ToString();
        }

        private static IndentedStringBuilder ProcessBasicType(string objectReference, string valueReference, IndentedStringBuilder builder)
        {
            return builder.AppendLine("if ({0} !== undefined) {{", valueReference)
                            .Indent()
                            .AppendLine("{0} = {1};", objectReference, valueReference)
                          .Outdent()
                          .AppendLine("}");
        }

        private static IndentedStringBuilder ProcessCompositeType(this CompositeType composite, string objectReference,
            string valueReference, string modelReference, IndentedStringBuilder builder, string processType)
        {
            builder.AppendLine("if ({0}) {{", valueReference).Indent();
            string discriminator = "{3} = new {2}.discriminators[{0}['{1}']]({0});";
            string objectCreation = "{3} = new {2}['{1}']({0});";

            if (processType == "DeserializeType")
            {
                discriminator = "{3} = new {2}.discriminators[{0}['{1}']]().deserialize({0});";
                objectCreation = "{3} = new {2}['{1}']().deserialize({0});";
            }

            if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator))
            {
                builder.AppendLine(discriminator, valueReference, composite.PolymorphicDiscriminator, modelReference, objectReference);
            }
            else
            {
                builder.AppendLine(objectCreation, valueReference, composite.Name, modelReference, objectReference);
            }
            builder.Outdent().AppendLine("}");

            return builder;
        }

        private static IndentedStringBuilder ProcessSequenceType(this SequenceType sequence, IScopeProvider scope, string objectReference,
            string valueReference, string modelReference, IndentedStringBuilder builder, string processType)
        {
            var elementVar = scope.GetVariableName("element");
            string innerInitialization = null;
            if (processType == null)
            {
                throw new ArgumentNullException("processType");
            }

            if (processType == "InitializeType")
            {
                innerInitialization = sequence.ElementType.InitializeType(scope, elementVar, elementVar, modelReference);
            }
            else if (processType == "DeserializeType")
            {
                innerInitialization = sequence.ElementType.DeserializeType(scope, elementVar, elementVar, modelReference);
            }
            else if (processType == "InitializeSerializationType")
            {
                innerInitialization = sequence.ElementType.InitializeSerializationType(scope, elementVar, elementVar, modelReference);
            }

            if (!string.IsNullOrEmpty(innerInitialization))
            {
                var arrayName = valueReference.ToPascalCase().NormalizeValueReference();
                builder.AppendLine("if ({0}) {{", valueReference)
                         .Indent()
                         .AppendLine("var temp{0} = [];", arrayName)
                         .AppendLine("{0}.forEach(function({1}) {{", valueReference, elementVar)
                           .Indent()
                             .AppendLine(innerInitialization)
                             .AppendLine("temp{0}.push({1});", arrayName, elementVar)
                           .Outdent()
                           .AppendLine("});")
                           .AppendLine("{0} = temp{1};", objectReference, arrayName)
                         .Outdent()
                         .AppendLine("}");
            }

            return builder;
        }

        private static IndentedStringBuilder ProcessDictionaryType(this DictionaryType dictionary, IScopeProvider scope, string objectReference,
            string valueReference, string modelReference, IndentedStringBuilder builder, string processType)
        {
            var valueVar = scope.GetVariableName("valueElement");
            string innerInitialization = null;
            if (processType == null)
            {
                throw new ArgumentNullException("processType");
            }

            string elementObjectReference = objectReference + "[" + valueVar + "]";
            string elementValueReference = valueReference + "[" + valueVar + "]";

            if (processType == "InitializeType")
            {
                innerInitialization = dictionary.ValueType.InitializeType(scope, elementObjectReference, elementValueReference, modelReference);
            }
            else if (processType == "DeserializeType")
            {
                innerInitialization = dictionary.ValueType.DeserializeType(scope, elementObjectReference, elementValueReference, modelReference);
            }
            else if (processType == "InitializeSerializationType")
            {
                innerInitialization = dictionary.ValueType.InitializeSerializationType(scope, elementObjectReference, elementValueReference, modelReference);
            }

            if (!string.IsNullOrEmpty(innerInitialization))
            {
                builder.AppendLine("if ({0}) {{", valueReference).Indent();
                if (processType == "DeserializeType" || processType == "InitializeType")
                {
                    builder.AppendLine("{0} = {{}};", objectReference);
                }

                builder.AppendLine("for(var {0} in {1}) {{", valueVar, valueReference)
                         .Indent()
                         .AppendLine(innerInitialization)
                       .Outdent()
                       .AppendLine("}")
                     .Outdent()
                     .AppendLine("}");
            }

            return builder;
        }

        /// <summary>
        /// Determine whether URL encoding should be skipped for this parameter
        /// </summary>
        /// <param name="parameter">The parameter to check</param>
        /// <returns>true if url encoding should be skipped for the parameter, otherwise false</returns>
        public static bool SkipUrlEncoding(this Parameter parameter)
        {
            if (parameter == null)
            {
                return false;
            }

            return parameter.Extensions.ContainsKey(CodeGenerator.SkipUrlEncodingExtension) &&
                   (bool)parameter.Extensions[CodeGenerator.SkipUrlEncodingExtension];
        }

        public static bool ContainsTimeSpan(this CompositeType type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            Property prop = type.Properties.FirstOrDefault(p =>
                p.Type == PrimaryType.TimeSpan ||
                (p.Type is SequenceType && (p.Type as SequenceType).ElementType == PrimaryType.TimeSpan) ||
                (p.Type is DictionaryType && (p.Type as DictionaryType).ValueType == PrimaryType.TimeSpan));

            return prop != null;
        }
    }
}


text:
require 'spec_helper'

describe Danica::Operator::Division do
  subject { described_class.new(*variables) }

  let(:variables) { [2, 4] }

  describe '#numerator' do
    it 'returns the numerator' do
      expect(subject.numerator).to eq(Danica::Wrapper::Number.new(2))
    end
  end

  describe '#denominator' do
    it 'returns the denominator' do
      expect(subject.denominator).to eq(Danica::Wrapper::Number.new(4))
    end
  end

  it_behaves_like 'an object that respond to basic_methods'
  it_behaves_like 'an object with basic operation'

  it_behaves_like 'a operator that has two terms', :division,
                  values: [2, 4],
                  calculated: 1.0 / 2.0,
                  to_tex: {
                    string_expected: '\frac{X1}{X2}',
                    numeric_string_expected: '\frac{2}{4}',
                    partial_string_expected: '\frac{2}{X2}'
                  },
                  to_gnu: {
                    string_expected: '(X1)/(X2)',
                    numeric_string_expected: '(2)/(4)',
                    partial_string_expected: '(2)/(X2)'
                  }

  describe 'more complex division' do
    describe 'of two additions' do
      subject do
        described_class.new(
          Danica::Operator::Addition.new(2, :x),
          Danica::Operator::Addition.new(3, :y)
        )
      end

      describe 'to_gnu' do
        let(:expected) do
          '(2 + x)/(3 + y)'
        end

        it 'groups addition' do
          expect(subject.to_gnu).to eq(expected)
        end
      end
    end
  end
end


text:
		{% include "shape_poly_display.svg" with entry=entry.shape %}

		{% include "image_square.svg" with url=entry.image_blob.url %}


text:
Blackjack
=======================

Based on Zf2 Skeleton

Installation
---------------------------

    $ composer.phar install
    $ vagrant up


text:
    <form name="$ctrl.form">
      <process-template ng-if="$ctrl.template" template="$ctrl.template" project="$ctrl.preSelectedProject" on-project-selected="$ctrl.onProjectSelected" available-projects="$ctrl.unfilteredProjects" is-dialog="true"></process-template>
    </form>


text:
namespace content {

SpeechRecognitionDispatcherHost::SpeechRecognitionDispatcherHost(
    int render_process_id,
    net::URLRequestContextGetter* context_getter)
    : BrowserMessageFilter(SpeechRecognitionMsgStart),
      render_process_id_(render_process_id),
      context_getter_(context_getter),
      weak_factory_(this) {
  // Do not add any non-trivial initialization here, instead do it lazily when
  // required (e.g. see the method |SpeechRecognitionManager::GetInstance()|) or
  // add an Init() method.
}

SpeechRecognitionDispatcherHost::~SpeechRecognitionDispatcherHost() {
  SpeechRecognitionManager::GetInstance()->AbortAllSessionsForRenderProcess(
      render_process_id_);
}

base::WeakPtr<SpeechRecognitionDispatcherHost>
SpeechRecognitionDispatcherHost::AsWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

bool SpeechRecognitionDispatcherHost::OnMessageReceived(
    const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(SpeechRecognitionDispatcherHost, message)
    IPC_MESSAGE_HANDLER(SpeechRecognitionHostMsg_StartRequest,
                        OnStartRequest)
    IPC_MESSAGE_HANDLER(SpeechRecognitionHostMsg_AbortRequest,
                        OnAbortRequest)
    IPC_MESSAGE_HANDLER(SpeechRecognitionHostMsg_StopCaptureRequest,
                        OnStopCaptureRequest)
    IPC_MESSAGE_HANDLER(SpeechRecognitionHostMsg_AbortAllRequests,
                        OnAbortAllRequests)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void SpeechRecognitionDispatcherHost::OverrideThreadForMessage(
    const IPC::Message& message,
    BrowserThread::ID* thread) {
  if (message.type() == SpeechRecognitionHostMsg_StartRequest::ID)
    *thread = BrowserThread::UI;
}

void SpeechRecognitionDispatcherHost::OnChannelClosing() {
  weak_factory_.InvalidateWeakPtrs();
}

void SpeechRecognitionDispatcherHost::OnStartRequest(
    const SpeechRecognitionHostMsg_StartRequest_Params& params) {
  SpeechRecognitionHostMsg_StartRequest_Params input_params(params);

  // Check that the origin specified by the renderer process is one
  // that it is allowed to access.
  if (params.origin_url != "null" &&
      !ChildProcessSecurityPolicyImpl::GetInstance()->CanRequestURL(
          render_process_id_, GURL(params.origin_url))) {
    LOG(ERROR) << "SRDH::OnStartRequest, disallowed origin: "
               << params.origin_url;
    return;
  }

  int embedder_render_process_id = 0;
  int embedder_render_view_id = MSG_ROUTING_NONE;
  RenderViewHostImpl* render_view_host =
      RenderViewHostImpl::FromID(render_process_id_, params.render_view_id);
  WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(
      WebContents::FromRenderViewHost(render_view_host));
  BrowserPluginGuest* guest = web_contents->GetBrowserPluginGuest();
  if (guest) {
    // If the speech API request was from a guest, save the context of the
    // embedder since we will use it to decide permission.
    embedder_render_process_id =
        guest->embedder_web_contents()->GetRenderProcessHost()->GetID();
    DCHECK_NE(embedder_render_process_id, 0);
    embedder_render_view_id =
        guest->embedder_web_contents()->GetRenderViewHost()->GetRoutingID();
    DCHECK_NE(embedder_render_view_id, MSG_ROUTING_NONE);
  }

  // TODO(lazyboy): Check if filter_profanities should use |render_process_id|
  // instead of |render_process_id_|.
  bool filter_profanities =
      SpeechRecognitionManagerImpl::GetInstance() &&
      SpeechRecognitionManagerImpl::GetInstance()->delegate() &&
      SpeechRecognitionManagerImpl::GetInstance()->delegate()->
          FilterProfanities(render_process_id_);

  BrowserThread::PostTask(
      BrowserThread::IO,
      FROM_HERE,
      base::Bind(&SpeechRecognitionDispatcherHost::OnStartRequestOnIO,
                 this,
                 embedder_render_process_id,
                 embedder_render_view_id,
                 input_params,
                 filter_profanities));
}

void SpeechRecognitionDispatcherHost::OnStartRequestOnIO(
    int embedder_render_process_id,
    int embedder_render_view_id,
    const SpeechRecognitionHostMsg_StartRequest_Params& params,
    bool filter_profanities) {
  SpeechRecognitionSessionContext context;
  context.context_name = params.origin_url;
  context.render_process_id = render_process_id_;
  context.render_view_id = params.render_view_id;
  context.embedder_render_process_id = embedder_render_process_id;
  context.embedder_render_view_id = embedder_render_view_id;
  if (embedder_render_process_id)
    context.guest_render_view_id = params.render_view_id;
  context.request_id = params.request_id;

  SpeechRecognitionSessionConfig config;
  config.is_legacy_api = false;
  config.language = params.language;
  config.grammars = params.grammars;
  config.max_hypotheses = params.max_hypotheses;
  config.origin_url = params.origin_url;
  config.initial_context = context;
  config.url_request_context_getter = context_getter_.get();
  config.filter_profanities = filter_profanities;
  config.continuous = params.continuous;
  config.interim_results = params.interim_results;
  config.event_listener = AsWeakPtr();

  int session_id = SpeechRecognitionManager::GetInstance()->CreateSession(
      config);
  DCHECK_NE(session_id, SpeechRecognitionManager::kSessionIDInvalid);
  SpeechRecognitionManager::GetInstance()->StartSession(session_id);
}

void SpeechRecognitionDispatcherHost::OnAbortRequest(int render_view_id,
                                                     int request_id) {
  int session_id = SpeechRecognitionManager::GetInstance()->GetSession(
      render_process_id_, render_view_id, request_id);

  // The renderer might provide an invalid |request_id| if the session was not
  // started as expected, e.g., due to unsatisfied security requirements.
  if (session_id != SpeechRecognitionManager::kSessionIDInvalid)
    SpeechRecognitionManager::GetInstance()->AbortSession(session_id);
}

void SpeechRecognitionDispatcherHost::OnAbortAllRequests(int render_view_id) {
  SpeechRecognitionManager::GetInstance()->AbortAllSessionsForRenderView(
      render_process_id_, render_view_id);
}

void SpeechRecognitionDispatcherHost::OnStopCaptureRequest(
    int render_view_id, int request_id) {
  int session_id = SpeechRecognitionManager::GetInstance()->GetSession(
      render_process_id_, render_view_id, request_id);

  // The renderer might provide an invalid |request_id| if the session was not
  // started as expected, e.g., due to unsatisfied security requirements.
  if (session_id != SpeechRecognitionManager::kSessionIDInvalid) {
    SpeechRecognitionManager::GetInstance()->StopAudioCaptureForSession(
        session_id);
  }
}

// -------- SpeechRecognitionEventListener interface implementation -----------

void SpeechRecognitionDispatcherHost::OnRecognitionStart(int session_id) {
  const SpeechRecognitionSessionContext& context =
      SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
  Send(new SpeechRecognitionMsg_Started(context.render_view_id,
                                        context.request_id));
}

void SpeechRecognitionDispatcherHost::OnAudioStart(int session_id) {
  const SpeechRecognitionSessionContext& context =
      SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
  Send(new SpeechRecognitionMsg_AudioStarted(context.render_view_id,
                                             context.request_id));
}

void SpeechRecognitionDispatcherHost::OnSoundStart(int session_id) {
  const SpeechRecognitionSessionContext& context =
      SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
  Send(new SpeechRecognitionMsg_SoundStarted(context.render_view_id,
                                             context.request_id));
}

void SpeechRecognitionDispatcherHost::OnSoundEnd(int session_id) {
  const SpeechRecognitionSessionContext& context =
      SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
  Send(new SpeechRecognitionMsg_SoundEnded(context.render_view_id,
                                           context.request_id));
}

void SpeechRecognitionDispatcherHost::OnAudioEnd(int session_id) {
  const SpeechRecognitionSessionContext& context =
      SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
  Send(new SpeechRecognitionMsg_AudioEnded(context.render_view_id,
                                           context.request_id));
}

void SpeechRecognitionDispatcherHost::OnRecognitionEnd(int session_id) {
  const SpeechRecognitionSessionContext& context =
      SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
  Send(new SpeechRecognitionMsg_Ended(context.render_view_id,
                                      context.request_id));
}

void SpeechRecognitionDispatcherHost::OnRecognitionResults(
    int session_id,
    const SpeechRecognitionResults& results) {
  const SpeechRecognitionSessionContext& context =
      SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
  Send(new SpeechRecognitionMsg_ResultRetrieved(context.render_view_id,
                                                context.request_id,
                                                results));
}

void SpeechRecognitionDispatcherHost::OnRecognitionError(
    int session_id,
    const SpeechRecognitionError& error) {
  const SpeechRecognitionSessionContext& context =
      SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id);
  Send(new SpeechRecognitionMsg_ErrorOccurred(context.render_view_id,
                                              context.request_id,
                                              error));
}

// The events below are currently not used by speech JS APIs implementation.
void SpeechRecognitionDispatcherHost::OnAudioLevelsChange(int session_id,
                                                          float volume,
                                                          float noise_volume) {
}

void SpeechRecognitionDispatcherHost::OnEnvironmentEstimationComplete(
    int session_id) {
}

}  // namespace content


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Dasyscyphus phragmiticolus Henn. & Plöttn.

### Remarks
null