text:
module Nanoc
  module Core
    class CompilationItemRepView < ::Nanoc::Core::BasicItemRepView
      # How long to wait before the requested file appears.
      #
      # This is a bit of a hack -- ideally, Nanoc would know that the file is
      # being generated, and wait the appropriate amount of time.
      FILE_APPEAR_TIMEOUT = 10.0

      # @abstract
      def item_view_class
        Nanoc::Core::CompilationItemView
      end

      # Returns the item rep's raw path. It includes the path to the output
      # directory and the full filename.
      #
      # @param [Symbol] snapshot The snapshot for which the path should be
      #   returned.
      #
      # @return [String] The item rep's raw path.
      def raw_path(snapshot: :last)
        @context.dependency_tracker.bounce(_unwrap.item, compiled_content: true)

        res = @item_rep.raw_path(snapshot: snapshot)

        unless @item_rep.compiled?
          Fiber.yield(Nanoc::Core::Errors::UnmetDependency.new(@item_rep, snapshot))
        end

        # Wait for file to exist
        if res
          start = Time.now
          sleep 0.05 until File.file?(res) || Time.now - start > FILE_APPEAR_TIMEOUT
          raise Nanoc::Core::Errors::InternalInconsistency, "File raw_path did not appear in time (#{FILE_APPEAR_TIMEOUT}s): #{res}" unless File.file?(res)
        end

        res
      end

      # Returns the compiled content.
      #
      # @param [String] snapshot The name of the snapshot from which to
      #   fetch the compiled content. By default, the returned compiled content
      #   will be the content compiled right before the first layout call (if
      #   any).
      #
      # @return [String] The content at the given snapshot.
      def compiled_content(snapshot: nil)
        @context.dependency_tracker.bounce(_unwrap.item, compiled_content: true)
        @context.compiled_content_store.compiled_content(rep: _unwrap, snapshot: snapshot)
      end
    end
  end
end


text:
This module is a collection of features missing in Magento.

## Installation

If you are using composer composer, just add this to you `composer.json` file.
```json
    "require": {
        "magento-hackathon/magento-composer-installer": "*",
        "webbhuset/features": "*"
    },
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/magento-hackathon/magento-composer-installer"
        },
        {
            "type":"vcs",
            "url":"https://github.com/webbhuset/features.git"
        }
    ],
```

You can also copy the files manually to your Magento Project.

## Configuration

Some general settings can be found in __System > Configuration > Webbhuset > Features__

## List of features

### Column added to the Category Products Grid

Added product type filter (simle, configurable etc.) column to category products grid in __Catalog > Manage Categories__.

### Random order on Products in Category

This feature updates the category product position to a random order. For the effect to be visible on the site, you need to set categeory sort by to position (Best Value).

There are two options for how to perform the shuffle:

* Shuffle the position of all products in a store every night.
* Shuffle product position on a specific category, just press "Shuffle Product Order" under __Catalog > Manage Categories > Category Products__

__Important!__ You need to update the _category products_ index after changing product position.

### Add category url to product url ###

When a product url is loaded without category, the category url is added based on the category with the highest level.

### Sitemap Splitter ###

This feature split the sitemap.xml by user defineable value which defaults to 50000 (Google allows a single sitemap file to reference up to 50,000 URLs). Setting is found in System > Configuration > Catalog > google Sitemap > Generation Settings > "Split sitemap".

### Sitemap Exclusion ###

Ability to exclude products with the attribute code _exclude_from_sitemap_ from the sitemap. Attribute is not created and needs to be manually created through admin or an upgrade script.

### Secure cookie for all request ###

Set secure cookie for all requests (frontend/adminhtml) when using https for base url.

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Linq;
using TechTalk.SpecFlow;
using Xunit;

namespace SpecFlow.AdvanceSteps.Integration.Tests
{
    [Binding]
    public class AllStepsThroughScenarioContextSteps
    {
        private readonly ScenarioContext scenarioContext;

        public AllStepsThroughScenarioContextSteps(ScenarioContext scenarioContext)
        {
            this.scenarioContext = scenarioContext;
        }

        [BeforeScenario("testof-sceanrio-context")]
        public void OnBeforeScenario()
        {
            Assert.Equal(4, this.scenarioContext.GetAllSteps().Count());
        }

        [Given(@"I have a simple given statement")]
        public void GivenIHaveASimpleGivenStatement()
        {
        }

        [Given(@"I have a another simple given statement")]
        public void GivenIHaveAAnotherSimpleGivenStatement()
        {
        }

        [When(@"I have a simple when statement")]
        public void WhenIHaveASimpleWhenStatement()
        {
        }

        [Then(@"I have a simple then statement")]
        public void ThenIHaveASimpleThenStatement()
        {
        }
    }
}


text:
import { URI } from "../../../lib/index.js";
import { SessionDescriptionHandler, SIPExtension, UserAgent, UserAgentOptions } from "../../../lib/api/index.js";
import { makeMockSessionDescriptionHandlerFactory } from "./session-description-handler-mock.js";
import { TransportFake } from "./transport-fake.js";

export interface UserFake {
  user: string;
  domain: string;
  displayName: string;
  transport: TransportFake;
  transportReceiveSpy: jasmine.Spy;
  transportSendSpy: jasmine.Spy;
  uri: URI;
  userAgent: UserAgent;
  userAgentOptions: UserAgentOptions;
  isShutdown: () => boolean;
}

export async function makeUserFake(
  user: string | undefined,
  domain: string,
  displayName: string,
  options: UserAgentOptions = {}
): Promise<UserFake> {
  const mockSessionDescriptionHandlers: Array<jasmine.SpyObj<SessionDescriptionHandler>> = [];
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const userHack: any = user; // FIXME: this is because grammar/parser produces undefined on no user
  const uri = new URI("sip", userHack, domain);
  const userAgentOptions: UserAgentOptions = {
    ...{
      uri,
      displayName,
      noAnswerTimeout: 90, // seconds
      sipExtension100rel: SIPExtension.Supported,
      sipExtensionReplaces: SIPExtension.Supported,
      sessionDescriptionHandlerFactory: makeMockSessionDescriptionHandlerFactory(
        displayName,
        0,
        mockSessionDescriptionHandlers
      ),
      transportConstructor: TransportFake
    },
    ...options
  };

  const userAgent = new UserAgent(userAgentOptions);
  await userAgent.start();

  if (!(userAgent.transport instanceof TransportFake)) {
    throw new Error("Transport not TransportFake");
  }
  userAgent.transport.id = displayName;

  const isShutdown = (): boolean => {
    // TODO: Check user agent state finalized

    // Confirm any and all session description handlers have been closed
    const sdhClosed = mockSessionDescriptionHandlers.every((mock) => {
      if (mock.close.calls.count() === 0) {
        // console.error(`${displayName} SDH Not Closed`);
        return false;
      }
      if (mock.close.calls.count() > 1) {
        // console.error(`${displayName} SDH Closed Multiple Times`);
        return false;
      }
      return true;
    });

    const shutdown = sdhClosed;

    // console.warn(`${displayName} is shutdown ${shutdown}`);
    return shutdown;
  };

  return {
    user: user ? user : "",
    domain,
    displayName,
    transport: userAgent.transport,
    transportReceiveSpy: spyOn(userAgent.transport, "receive").and.callThrough(),
    transportSendSpy: spyOn(userAgent.transport, "send").and.callThrough(),
    uri,
    userAgent,
    userAgentOptions,
    isShutdown
  };
}

export function connectUserFake(user1: UserFake, user2: UserFake): void {
  user1.transport.addPeer(user2.transport);
  user2.transport.addPeer(user1.transport);
}


text:
body {
	background: #ededed;
}

.grid {
	margin: 0 auto;
	position: relative;
	width: 700px;
	margin-top: 5px;
}

.add {
	background: url('images/add.png');
}

.delete {
	background: url('images/delete.png');
}

.save {
	background: url('images/save.gif');
}


text:
/*
 * REST API Documentation for the MOTI School Bus Application
 *
 * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
 *
 * OpenAPI spec version: v1
 *
 *
 */

using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;

namespace SchoolBusAPI.Models
{
    /// <summary>
    /// The history of updates made to a School Bus. Exact format of the history TBD.
    /// </summary>
        [MetaDataExtension (Description = "The history of updates made to a School Bus. Exact format of the history TBD.")]

    public partial class SchoolBusHistory : IEquatable<SchoolBusHistory>
    {
        /// <summary>
        /// Default constructor, required by entity framework
        /// </summary>
        public SchoolBusHistory()
        {
            this.Id = 0;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SchoolBusHistory" /> class.
        /// </summary>
        /// <param name="Id">Primary Key (required).</param>
        /// <param name="SchoolBus">SchoolBus.</param>
        public SchoolBusHistory(int Id, SchoolBus SchoolBus = null)
        {

            this.Id = Id;
            this.SchoolBus = SchoolBus;

        }

        /// <summary>
        /// Primary Key
        /// </summary>
        /// <value>Primary Key</value>
        [MetaDataExtension (Description = "Primary Key")]
        public int Id { get; set; }

        /// <summary>
        /// Gets or Sets SchoolBus
        /// </summary>
        public SchoolBus SchoolBus { get; set; }

        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("class SchoolBusHistory {\n");
            sb.Append("  Id: ").Append(Id).Append("\n");
            sb.Append("  SchoolBus: ").Append(SchoolBus).Append("\n");
            sb.Append("}\n");
            return sb.ToString();
        }

        /// <summary>
        /// Returns the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }

        /// <summary>
        /// Returns true if objects are equal
        /// </summary>
        /// <param name="obj">Object to be compared</param>
        /// <returns>Boolean</returns>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) { return false; }
            if (ReferenceEquals(this, obj)) { return true; }
            if (obj.GetType() != GetType()) { return false; }
            return Equals((SchoolBusHistory)obj);
        }

        /// <summary>
        /// Returns true if SchoolBusHistory instances are equal
        /// </summary>
        /// <param name="other">Instance of SchoolBusHistory to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(SchoolBusHistory other)
        {

            if (ReferenceEquals(null, other)) { return false; }
            if (ReferenceEquals(this, other)) { return true; }

            return
                (
                    this.Id == other.Id ||
                    this.Id.Equals(other.Id)
                ) &&
                (
                    this.SchoolBus == other.SchoolBus ||
                    this.SchoolBus != null &&
                    this.SchoolBus.Equals(other.SchoolBus)
                );
        }

        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            // credit: http://stackoverflow.com/a/263416/677735
            unchecked // Overflow is fine, just wrap
            {
                int hash = 41;
                // Suitable nullity checks
                hash = hash * 59 + this.Id.GetHashCode();

                if (this.SchoolBus != null)
                {
                    hash = hash * 59 + this.SchoolBus.GetHashCode();
                }
                return hash;
            }
        }

        #region Operators

        public static bool operator ==(SchoolBusHistory left, SchoolBusHistory right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(SchoolBusHistory left, SchoolBusHistory right)
        {
            return !Equals(left, right);
        }

        #endregion Operators
    }
}


text:
<%inherit file="base.htm" />

<%block name="content">

 Setup Accounts for New Month

Summary

 New Accounts will be created for ${ month} ${ year}

Create Accounts for ${ month} ${ year}

</%block>


text:
Paket is a dependency manager for .NET projects. Paket enables precise and predictable control over your dependencies. With Paket, you can reference:

* [NuGet](https://www.nuget.org/) packages
* Files from [Git repositories](git-dependencies.html)
* Files from any [HTTP resource](http-dependencies.html).

Get started by learning [how to use Paket](learn-how-to-use-paket.html) and take a look at the [FAQ](faq.html) to learn more about it.

If you are using legacy NuGet (`packages.config`-based) projects for package management in your solution, you can learn about the upgrade process in the [convert from NuGet tutorial](convert-from-nuget-tutorial.html)

For information about using Paket with .NET SDK, .NET Core and the `dotnet` CLI see the["Paket and the .NET SDK / .NET Core CLI tools" guide](paket-and-dotnet-cli.html).

[![Paket Overview](img/paket-overview.png)](img/paket-overview.png)

## Contributing and copyright

The project is hosted on [GitHub][gh] where you can [report issues][issues],
fork the project and submit pull requests.

Please see the [Quick contributing guide in the README][readme] for contribution
guidelines.

The library is available under MIT license, which allows modification and
redistribution for both commercial and non-commercial purposes. For more
information see the [License file][license].

  [content]: https://github.com/fsprojects/Paket/tree/master/docs/content
  [gh]: https://github.com/fsprojects/Paket
  [issues]: https://github.com/fsprojects/Paket/issues
  [readme]: https://github.com/fsprojects/Paket/blob/master/README.md
  [license]: license.html


text:
namespace ash {

PinnedFilesBubble::PinnedFilesBubble(HoldingSpaceViewDelegate* delegate)
    : HoldingSpaceTrayChildBubble(delegate) {
  SetID(kHoldingSpacePinnedFilesBubbleId);
}

PinnedFilesBubble::~PinnedFilesBubble() = default;

const char* PinnedFilesBubble::GetClassName() const {
  return "PinnedFilesBubble";
}

std::vector<std::unique_ptr<HoldingSpaceItemViewsSection>>
PinnedFilesBubble::CreateSections() {
  std::vector<std::unique_ptr<HoldingSpaceItemViewsSection>> sections;
  sections.push_back(std::make_unique<PinnedFilesSection>(delegate()));
  return sections;
}

}  // namespace ash


text:
from django.conf.urls.defaults import *

from views import CallbackUrlView, RedirectToTwitterView

urlpatterns = patterns('',
    url(r'^login/?$', RedirectToTwitterView.as_view(),
        name="twitter_begin_auth"),

    url(r'^callback/?$', CallbackUrlView.as_view(),
        name='twitter_callback_url'),
)


text:
(function() {

    // ** BEGIN JASMINE 2.0 COMPATIBILITY SHIM ZONE ** //

    // Add back in the old name of addCustomEqualityTester for compability (remove if jasmine-jquery
    // changes to know about addCustomEqualityTester)
    jasmine.getEnv().addEqualityTester = jasmine.getEnv().addCustomEqualityTester;

    jasmine.originalCreateSpy = jasmine.createSpy;
    jasmine.createSpy = function (name, originalFn) {
        var spy = jasmine.originalCreateSpy.apply(this, arguments);
        spy.andCallFake = function () {
            spy.and.callFake.apply(this, arguments);
            return spy;
        };
        spy.andReturn = function () {
            spy.and.returnValue.apply(this, arguments);
            return spy;
        };
        spy.andCallThrough = function () {
            spy.and.callThrough.apply(this, arguments);
            return spy;
        };
        spy.reset = function () {
            spy.calls.reset();
        };
        spy.lastCall = function () {
            return _.last(spy.calls.all());
        };
        spy.nthCall = function (n) {
            return spy.calls.all()[n];
        };
        return spy;
    };

    window.addCompatibilityShimmedMatchers = function(matchersToAdd) {
        for (var name in matchersToAdd) {
            var matcher = matchersToAdd[name];

            var wrappedMatcher = (function (matcher) {
                return function (util, customEqualityTesters) {
                    return {
                        compare: function (actual, expected) {
                            var fakeThis = {
                                actual: actual,
                                expected: expected
                            };

                            var result;
                            try {
                                result = {pass: matcher.apply(fakeThis, Array.prototype.slice.call(arguments, 1))};
                            } catch (e) {
                                result = {pass: false, message: e};
                            }

                            if (!result.pass && !result.message && fakeThis.message) {
                                result.message = fakeThis.message()[0]; // wat
                            }

                            return result;
                        }
                    };
                };
            }(matcher));

            var matchers = {};
            matchers[name] = wrappedMatcher;
            window.addMatchers(matchers);
        }
    };

    // ** END JASMINE 2.0 COMPATIBILITY SHIM ZONE ** //

    function clearRenderedDOM() {
        $('#jasmine_content').empty();
    }

    function checkTranslation(args) {
        var translationKey = args[0];
        var translatedText = t.apply(this, args);
        var missingParams = translatedText.match(/missing (\{\{\w+\}\}) value/);

        if (!I18n.lookup(translationKey)) {
            throw("Test error - Missing translation key '" + translationKey + "'");
        }
        if (missingParams) {
            throw("Test error - Missing parameter for translation key '" + translationKey + "':  " + missingParams[1]);
        }

        return translatedText;
    }

    var dealWithChromeBackgrounding = _.once(function() {
        // Code that only needs to be run once before all the tests run
        _.debounce = function(func, timeout) { return func; };

        $(window).focus(function(){
            jasmine.getEnv().updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL;
        });

        $(window).blur(function() {
            // if you get 'unresponsive script' warnings in Firefox, you can override the dom.max_script_time variable
            jasmine.getEnv().updateInterval = 12000;
        });
    });

    if (window.location.search.indexOf('phantom=') === -1) {
        jasmine.HighlightingReporter = function() {
            this.started = false;
            this.finished = false;
            this.suites_ = [];
            this.results_ = {};
            this.reportRunnerResults = function() {
                $('body').append('');

                _.each($('.stackTrace'), function (el) {
                    var $el = $(el);
                    var spannedHtml = $el.html().split("\n").map(function (text) {
                        if (text.match(/application|__spec__|assets/)) {
                            return "" + text + "";
                        } else {
                            return text;
                        }
                    }).join("\n");
                    $el.html(spannedHtml);
                });
            };
        };

        jasmine.getEnv().addReporter(new jasmine.HighlightingReporter());
    }

    var backboneModelEqualityTester = function(a, b) {
        if(a instanceof Backbone.Model && b instanceof Backbone.Model) {
            if (a.constructor !== b.constructor) {
                return false;
            }

            if (!_.isUndefined(a.id) && !_.isUndefined(b.id)) {
                return (a.id === b.id);
            }

            if (!_.isUndefined(a.cid) && !_.isUndefined(b.cid)) {
                return (a.cid === b.cid);
            }
        }
    };

    beforeEach(function(done) {
        chorus.currentSpec = jasmine.getEnv().currentSpec.getFullName();
        window.afterSpecFunctions = [];
        dealWithChromeBackgrounding();
        stubDelay();
        stubClEditor();

        jasmine.getEnv().addEqualityTester(backboneModelEqualityTester);

        if (!window.backboneFixtures) {
            // load fixtures asyncronously
            BackboneFixtures.jasmineSetup(chorus.models, chorus.collections, chorus.models.Base, chorus.collections.Base, done);
        } else {
            done();
        }
    });

    beforeEach(function () {
        window.server = this.server = sinon.fakeServer.create();
        this.useFakeTimers = chorus.useFakeTimers;
        chorus.router.unbind();
        delete chorus.page;
        chorus.models.Config.instance().clear();
        window.qtipElements = {};
        window.stubToasts();

        clearRenderedDOM();

        window.addCompatibilityShimmedMatchers({
            toExist: function() {
                return this.actual.size() > 0;
            },

            toBeA: function(klass) {
                if (klass.prototype && klass.prototype.constructorName) {
                    this.message = function () {
                        return [
                            "Expected a '" + this.actual.constructorName + "' to be an instance of '" + klass.prototype.constructorName +"'.",
                            "Expected a '" + this.actual.constructorName + "' to be an instance of something other than '" + klass.prototype.constructorName +"'!"
                        ];
                    };
                }
                if (_.isFunction(klass)) {
                    return this.actual instanceof klass;
                } else {
                    return (typeof this.actual === klass);
                }
            },

            toBeEnabled: function() {
                return this.actual.is(':not(:disabled)');
            },

            toMatchTranslation: function(translationKey) {
                var translatedText = checkTranslation(arguments);

                this.message = function() {
                    return [
                        "Expected text '" + this.actual + "' to match the translation for '" + translationKey + "' (" + translatedText + ")",
                        "Expected text '" + this.actual + "' not to match the translation for '" + translationKey + "' (" + translatedText + ")"
                    ];
                };

                return this.actual === translatedText;
            },

            toContainTranslation: function(translationKey) {
                var actual = _.isString(this.actual) ? this.actual : this.actual.text();
                var translatedText = checkTranslation(arguments);

                this.message = function() {
                    return [
                        "Expected text '" + actual + "' to contain the translation for '" + translationKey + "' (" + translatedText + ")",
                        "Expected text '" + actual + "' not to contain the translation for '" + translationKey + "' (" + translatedText + ")"
                    ];
                };

                return actual && actual.indexOf(translatedText) !== -1;
            },

            toHaveBeenCalledOnSelector: function(selector) {
                return _.any(this.actual.calls.all(), function(call) {
                    return call.object.selector === selector;
                });
            },

            toHaveBeenCalledOn: function(object) {
                return _.any(this.actual.calls.all(), function(call) {
                    return call.object === object;
                });
            },

            toHaveBeenCalledWithSorta: function(object, exceptions) { // only works with 1-argument calls
                function cleanser(object) {
                    object = _.clone(object);
                    _.each(exceptions, function(exception) {
                        if (object.attributes) object.attributes[exception] = undefined;
                        else object[exception] = undefined;
                    });
                    return object;
                }

                var argumentsUsed = "";
                object = cleanser(object);
                if (_.any(this.actual.calls.all(), function(call) {
                    var arg0 = cleanser(call.args[0]);
                    argumentsUsed += "\n" + jasmine.pp(arg0);
                    return arg0.attributes ? _.isEqual(arg0.attributes, object.attributes) : _.isEqual(arg0, object);
                })) {
                    return true;
                }
                this.message = function() {
                    var foo = " to have been called with\n" + jasmine.pp(object) + "\n(ignoring fields " + jasmine.pp(exceptions) + ") as its first argument but was called with " + argumentsUsed + "\n as first arguments";
                    return [ "Expected" + foo , "Expected not" + foo ];
                };
            },

            toContainText: function(text) {
                var actualText = _.isString(this.actual) ? this.actual : this.actual.text();
                actualText = actualText.replace(/\s+/g, " ");
                this.message = function() {
                    return [
                        'Expected "' + actualText + '" to contain "' + text + '"',
                        'Expected "' + actualText + '" not to contain "' + text + '"'
                    ];
                };
                return actualText && actualText.indexOf(text) !== -1;
            },

            toHaveSpinner: function() {
                this.message = function() {
                    return [
                        'Expected "' + this.actual.selector + '" to have a spinner',
                        'Expected "' + this.actual.selector + '" not to have a spinner'
                    ];
                };
                return this.actual.find("div[aria-role=progressbar]").length;
            },

            toHaveModal: function(modalClass) {
                if (!modalClass) { throw "expected undefined modal class to have been launched."; }
                this.message = function() {
                    return [
                        "Expected modal '" + modalClass.prototype.constructorName + "' to have been launched",
                        "Expected modal '" + modalClass.prototype.constructorName + "' not to have been launched"
                    ];
                };
                return _.any(this.actual.modals(), function(modal) {
                    return modal instanceof modalClass;
                });
            },

            toHaveBeenTriggeredOn: function(target, args) {
                var call, eventName = this.actual;

                if (args) {
                    this.message = function() {
                        if (call) {
                            return [
                                "Expected event " + eventName + " to have been triggered on " + target + " with" + args + " but was triggered with " + call.args + " (did you forget to call this matcher with an array of arguments?)",
                                "Expected event " + eventName + " not to have been triggered on " + target + " with" + args + " but was triggered with " + call.args
                            ];
                        } else {
                            return [
                                "Expected event " + eventName + " to have been triggered on " + target + " with " + args + " but it was never triggered",
                                "Expected event " + eventName + " not to have been triggered on " + target + " with " + args + " but it was"
                            ];
                        }
                    };
                } else {
                    this.message = function() {
                        return [
                            "Expected event " + eventName + " to have been triggered on " + target,
                            "Expected event " + eventName + " not to have been triggered on " + target
                        ];
                    };
                }

                if (_.isString(target) || target instanceof jQuery) {
                    return jasmine.JQuery.events.wasTriggered(target, eventName);
                } else if (target._chorusEventSpies && target._chorusEventSpies[eventName]) {
                    call = _.last(target._chorusEventSpies[eventName].calls.all());
                    if (!call) return false;
                    if (args)  return (_.isEqual(call.args, args));
                    return true;
                } else {
                    throw "The event '" + eventName + "' has not been spied on, for the object " + target;
                }
            },

            toMatchUrl: function(target, options) {
                this.message = function() {
                    return [
                        "Expected url " + this.actual + " to be equivalent to url " + target,
                        "Expected url " + this.actual + " not to be equivalent to url " + target
                    ];
                };

                var paramsToIgnore = (options && options.paramsToIgnore) || [];
                var targetURI = new URI(decodeURI(target)).removeSearch(paramsToIgnore);
                var actualURI = new URI(decodeURI(this.actual)).removeSearch(paramsToIgnore);
                return (actualURI).equals(targetURI);
            },

            toContainQueryParams: function(queryParams) {
                var actualQueryParams = new URI(this.actual).query(true);
                var targetQueryParams = new URI("").addQuery(chorus.Mixins.Fetching.underscoreKeys(queryParams)).query(true);

                return _.all(targetQueryParams, function(targetValue, targetKey) {
                    if (targetValue instanceof Array) {
                        return _.difference(targetValue, actualQueryParams[targetKey]).length === 0;
                    } else {
                        return actualQueryParams[targetKey] === targetValue;
                    }
                });
            },

            toHaveUrlPath: function(targetPath) {
                var actualURI = new URI(this.actual);
                return actualURI.path() === targetPath;
            },

            toHaveHref: function(expectedHref) {
                var actualHref = this.actual.attr("href");
                this.message = function() {
                    return [
                        "Expected href " + actualHref + " to be an `a` and equivalent to href " + expectedHref,
                        "Expected href " + actualHref + " to be an `a` and not to be equivalent to href " + expectedHref
                    ];
                };
                return this.actual.is("a") && decodeURI(actualHref) === decodeURI(expectedHref);
            },

            toHaveVisibleQtip: function() {
                return this.actual.find('.qtip').attr('aria-hidden') === 'false';
            },

            toBeBetween: function(lowerBound, upperBound) {
                return (this.actual >= lowerBound) && (this.actual <= upperBound);
            },

            toHaveBeenFetched: function() {
                return !!window.server.lastFetchFor(this.actual);
            },

            toHaveAllBeenFetched: function() {
                return !!window.server.lastFetchAllFor(this.actual);
            },

            toHaveBeenCreated: function() {
                return !!window.server.lastCreateFor(this.actual);
            },

            toHaveBeenUpdated: function() {
                return !!window.server.lastUpdateFor(this.actual);
            },

            toHaveAttrs: function(args) {
                return _.all(args, function(val, key) {
                    return this.actual.attributes[key] === val;
                }, this);
            },

            toHaveSubscription: function(eventName, callback) {
                this.message = function() {
                    return [
                        "Expected to have subscription to event " + eventName + " with callback " + callback,
                        "Expected not to have subscription to event " + eventName + " with callback " + callback
                    ];
                };
                return _.any(chorus.PageEvents._events[eventName], function(subscription) {return subscription.callback === callback;});
            }
        });

        var fakeSpinner = {
            spin: jasmine.createSpy('MockSpinner.spin').andCallFake(function(parentEl) {
                this.el = $('
')[0];
                parentEl && parentEl.appendChild(this.el);
                return this;
            }),

            stop: jasmine.createSpy('MockSpinner.stop').andCallFake(function() {
                if (this.el) {
                    $(this.el).detach();
                }
            })
        };

        window.Spinner = jasmine.createSpy('MockSpinner').andCallFake(function() {
            return fakeSpinner;
        });

        $.fx.off = true;
        spyOn(window.history, "back");
        spyOn(chorus, 'isDevMode').andReturn(false);

        chorus.PageEvents.off();
        chorus.session.sandboxPermissionsCreated = {};
        setLoggedInUser();
    });

    var specWhitelist = {
        id: true,
        env: true,
        suite: true,
        description: true,
        queue: true,
        afterCallbacks: true,
        spies_: true,
        results_: true,
        matchersClass: true
    };

    afterEach(function() {
        chorus.router.trigger("leaving");
        _.each(window.afterSpecFunctions, function (fn) { fn(); });

        delete chorus.models.Config._instance;

        $.cookie("userId", null);
        if (this instanceof jasmine.Spec) {
            _.each(this, function(_value, key) {
                if (this.hasOwnProperty(key) && !(key in specWhitelist)) {
                    if (this[key] && this[key].teardown) {
                        this[key].teardown();
                    }
                    delete this[key];
                }
            }, this);
        }
        chorus._navigated();
        window.server = undefined;
    });

    //global helpers
    window.context = window.describe;
    window.xcontext = window.xdescribe;
    window.specify = window.it;
    window.xspecify = window.xit;

    window.xitBehavesLike = {};
    _.each(window.itBehavesLike, function(value, key) { window.xitBehavesLike[key] = $.noop; });

    window.loadConfig = function() {
        chorus.models.Config.instance().set(backboneFixtures.config().attributes);
    };

    window.unsetLoggedInUser = function() {
        chorus.session.unset("id");
        delete chorus.session._user;
    };

    var jquerySpyOnEvent = window.spyOnEvent;
    var backboneSpyOnEvent = function(object, name) {
        var eventSpy = jasmine.createSpy(name + "Spy");
        object.bind(name, eventSpy);
        object._chorusEventSpies || (object._chorusEventSpies = {});
        object._chorusEventSpies[name] = eventSpy;
        return eventSpy;
    };

    window.spyOnEvent = function(object) {
        if (object.bind === Backbone.Events.bind) {
            return backboneSpyOnEvent.apply(this, arguments);
        } else {
            return jquerySpyOnEvent.apply(this, arguments);
        }
    };

    window.resetBackboneEventSpies = function(object) {
        if (object._chorusEventSpies) {
            _.each(object._chorusEventSpies, function(spy) {
                spy.reset();
            });
        }
    };

    window.setLoggedInUser = function(options, chorusObject) {
        var target = (chorusObject || chorus);
        if(options instanceof chorus.models.User) {
            options = options.attributes;
        }
        target.session = backboneFixtures.session({user: options});
    };

    window.stubToasts = function () {
        spyOn(Messenger(), 'post');
    };

    window.stubView = function(html, options) {
        options || (options = {});
        var stubClass = Backbone.View.extend({
            className: options.className,

            initialize: function() {
                _.bindAll(this, "render");
            },

            render: function() {
                this.$el.html(html);
                return this;
            },

            teardown: $.noop
        });

        return new stubClass();
    };

    window.stubModals = function() {
        spyOn($, "facebox");
        $.facebox.settings = {};
        var launchModalSpy = spyOn(chorus.Modal.prototype, "initialize").andCallThrough();

        return {
            lastModal: function() {
                return _.last(this.modals());
            },

            modals: function() {
                return _.map(launchModalSpy.calls.all(), function(call) {
                    return call.object;
                });
            },

            reset: function() {
                launchModalSpy.reset();
            }
        };
    };

    window.stubDelay = function() {
        spyOn(_, 'delay').andCallFake(function(func) {
            func();
        });
    };

    window.unstubDelay = function () {
        _.delay.andCallThrough();
    };

    window.qtipElements = {};
    window.stubQtip = function(selector) {
        selector || (selector = "*");
        qtipElements[selector] = $('

');
        $('#jasmine_content').append(qtipElements[selector]);

        if (!jasmine.isSpy($.fn.qtip)) {
            var qtip = $.fn.qtip;

            spyOn($.fn, 'qtip').andCallFake(function() {
                var jqueryObject = this;
                var options = arguments[0] || {};
                if (typeof options !== 'object') return;

                _.any(qtipElements, function(fakeQtipEl, selector) {
                    if (!jqueryObject.is(selector)) return false;
                    options.show || (options.show = {});
                    options.position || (options.position = {});
                    options.show.delay = 0;
                    options.position.container = fakeQtipEl;

                    qtip.call(jqueryObject, options);
                    return true;
                });
            });
        }

        qtipElements[selector].$ = qtipElements[selector].find;
        return qtipElements[selector];
    };

    window.stubSelectMenu = function() {
        var stubContainer = $('

');
        $('#jasmine_content').append(stubContainer);

        var selectmenu = $.fn.selectmenu;

        spyOn($.fn, 'selectmenu').andCallFake(function() {
            var jqueryObject = this;
            var options = arguments[0] || {};
            options.appendTo = stubContainer;
            selectmenu.call(jqueryObject, options);
            return true;
        });

        return stubContainer;
    };

    window.stubClEditor = function() {
        spyOn($.fn, "cleditor").andReturn([0]);
    };

    window.unstubClEditor = function () {
        $.fn.cleditor.andCallThrough();
    };

    window.enterTag = function(view, tagName) {
        var keyup = $.Event('keyup');
        keyup.keyCode = $.ui.keyCode.ENTER;
        var enter = $.Event('enterKeyPress');
        var input = view.$("input");
        input.val(tagName);
        input.focus();
        input.trigger(enter);
        input.trigger(keyup);
    };

    if ($.browser.msie && !window['con' + 'sole']) {
        (function(F, i, r, e, b, u, g, L, I, T, E) {
            if (F.getElementById(b))return;
            E = F[i + 'NS'] && F.documentElement.namespaceURI;
            E = E ? F[i + 'NS'](E, 'script') : F[i]('script');
            E[r]('id', b);
            E[r]('src', I + g + T);
            E[r](b, u);
            (F[e]('head')[0] || F[e]('body')[0]).appendChild(E);
            E = new Image();
            E[r]('src', I + L);
        })(document, 'createElement', 'setAttribute', 'getElementsByTagName', 'FirebugLite', '4', 'firebug-lite.js', 'releases/lite/latest/skin/xp/sprite.png', '/firebug-lite/build/', '#startOpened');
    }

    // Don't change urls in specs
    Backbone.History.prototype.navigate = function(fragment, triggerRoute) {
        if (triggerRoute) this.loadUrl(fragment);
    };

    //initialization
    (function safeStart() {

        var origLogin = chorus.requireLogin;
        var origHistory = chorus.startHistory;
        chorus.requireLogin = $.noop;
        chorus.startHistory = function () {
            Backbone.history.options = {root: '/'};
        };

        chorus.initialize();

        chorus.requireLogin = origLogin;
        chorus.startHistory = origHistory;

    })();
})();


text:
"use strict";

import $ from 'jquery';

// Core Foundation Utilities, utilized in a number of places.

  /**
   * Returns a boolean for RTL support
   */
function rtl() {
  return $('html').attr('dir') === 'rtl';
}

/**
 * returns a random base-36 uid with namespacing
 * @function
 * @param {Number} length - number of random base-36 digits desired. Increase for more random strings.
 * @param {String} namespace - name of plugin to be incorporated in uid, optional.
 * @default {String} '' - if no plugin name is provided, nothing is appended to the uid.
 * @returns {String} - unique id
 */
function GetYoDigits(length = 6, namespace){
  let str = '';
  const chars = '0123456789abcdefghijklmnopqrstuvwxyz';
  const charsLength = chars.length;
  for (let i = 0; i < length; i++) {
    str += chars[Math.floor(Math.random() * charsLength)];
  }
  return namespace ? `${str}-${namespace}` : str;
}

/**
 * Escape a string so it can be used as a regexp pattern
 * @function
 * @see https://stackoverflow.com/a/9310752/4317384
 *
 * @param {String} str - string to escape.
 * @returns {String} - escaped string
 */
function RegExpEscape(str){
  return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

function transitionend($elem){
  var transitions = {
    'transition': 'transitionend',
    'WebkitTransition': 'webkitTransitionEnd',
    'MozTransition': 'transitionend',
    'OTransition': 'otransitionend'
  };
  var elem = document.createElement('div'),
      end;

  for (let transition in transitions){
    if (typeof elem.style[transition] !== 'undefined'){
      end = transitions[transition];
    }
  }
  if (end) {
    return end;
  } else {
    setTimeout(function(){
      $elem.triggerHandler('transitionend', [$elem]);
    }, 1);
    return 'transitionend';
  }
}

/**
 * Return an event type to listen for window load.
 *
 * If `$elem` is passed, an event will be triggered on `$elem`. If window is already loaded, the event will still be triggered.
 * If `handler` is passed, attach it to the event on `$elem`.
 * Calling `onLoad` without handler allows you to get the event type that will be triggered before attaching the handler by yourself.
 * @function
 *
 * @param {Object} [] $elem - jQuery element on which the event will be triggered if passed.
 * @param {Function} [] handler - function to attach to the event.
 * @returns {String} - event type that should or will be triggered.
 */
function onLoad($elem, handler) {
  const didLoad = document.readyState === 'complete';
  const eventType = (didLoad ? '_didLoad' : 'load') + '.zf.util.onLoad';
  const cb = () => $elem.triggerHandler(eventType);

  if ($elem) {
    if (handler) $elem.one(eventType, handler);

    if (didLoad)
      setTimeout(cb);
    else
      $(window).one('load', cb);
  }

  return eventType;
}

/**
 * Retuns an handler for the `mouseleave` that ignore disappeared mouses.
 *
 * If the mouse "disappeared" from the document (like when going on a browser UI element, See https://git.io/zf-11410),
 * the event is ignored.
 * - If the `ignoreLeaveWindow` is `true`, the event is ignored when the user actually left the window
 *   (like by switching to an other window with [Alt]+[Tab]).
 * - If the `ignoreReappear` is `true`, the event will be ignored when the mouse will reappear later on the document
 *   outside of the element it left.
 *
 * @function
 *
 * @param {Function} [] handler - handler for the filtered `mouseleave` event to watch.
 * @param {Object} [] options - object of options:
 * - {Boolean} [false] ignoreLeaveWindow - also ignore when the user switched windows.
 * - {Boolean} [false] ignoreReappear - also ignore when the mouse reappeared outside of the element it left.
 * @returns {Function} - filtered handler to use to listen on the `mouseleave` event.
 */
function ignoreMousedisappear(handler, { ignoreLeaveWindow = false, ignoreReappear = false } = {}) {
  return function leaveEventHandler(eLeave, ...rest) {
    const callback = handler.bind(this, eLeave, ...rest);

    // The mouse left: call the given callback if the mouse entered elsewhere
    if (eLeave.relatedTarget !== null) {
      return callback();
    }

    // Otherwise, check if the mouse actually left the window.
    // In firefox if the user switched between windows, the window sill have the focus by the time
    // the event is triggered. We have to debounce the event to test this case.
    setTimeout(function leaveEventDebouncer() {
      if (!ignoreLeaveWindow && document.hasFocus && !document.hasFocus()) {
        return callback();
      }

      // Otherwise, wait for the mouse to reeapear outside of the element,
      if (!ignoreReappear) {
        $(document).one('mouseenter', function reenterEventHandler(eReenter) {
          if (!$(eLeave.currentTarget).has(eReenter.target).length) {
            // Fill where the mouse finally entered.
            eLeave.relatedTarget = eReenter.target;
            callback();
          }
        });
      }

    }, 0);
  };
}

export { rtl, GetYoDigits, RegExpEscape, transitionend, onLoad, ignoreMousedisappear };


text:
package org.marketcetera.quickfix;

import org.marketcetera.util.log.I18NLoggerProxy;
import org.marketcetera.util.log.I18NMessage0P;
import org.marketcetera.util.log.I18NMessage1P;
import org.marketcetera.util.log.I18NMessage2P;
import org.marketcetera.util.log.I18NMessageProvider;
import org.marketcetera.util.misc.ClassVersion;

/* $License$ */

/**
 * The internationalization constants used by this package.
 *
 * @author klim@marketcetera.com
 * @since 0.6.0
 * @version $Id: Messages.java 16154 2012-07-14 16:34:05Z colin $
 */
@ClassVersion("$Id: Messages.java 16154 2012-07-14 16:34:05Z colin $") //$NON-NLS-1$
public interface Messages
{
    /**
     * The message provider.
     */

    static final I18NMessageProvider PROVIDER =
        new I18NMessageProvider("quickfix"); //$NON-NLS-1$

    /**
     * The logger.
     */

    static final I18NLoggerProxy LOGGER =
        new I18NLoggerProxy(PROVIDER);

    /*
     * The messages.
     */

    static final I18NMessage1P GROUP_NUMBER_COULD_NOT_TRANSLATE =
        new I18NMessage1P(LOGGER,"group_number_could_not_translate"); //$NON-NLS-1$

    static final I18NMessage0P FIX_OUTGOING_NO_MSGTYPE =
        new I18NMessage0P(LOGGER,"fix_outgoing_no_msgtype"); //$NON-NLS-1$
    static final I18NMessage0P FIX_MD_MERGE_INVALID_INCOMING_SNAPSHOT =
        new I18NMessage0P(LOGGER,"fix_md_merge_invalid_incoming_snapshot"); //$NON-NLS-1$
    static final I18NMessage0P FIX_MD_MERGE_INVALID_INCOMING_INCREMENTAL =
        new I18NMessage0P(LOGGER,"fix_md_merge_invalid_incoming_incremental"); //$NON-NLS-1$
    static final I18NMessage1P FIX_VERSION_UNSUPPORTED =
        new I18NMessage1P(LOGGER,"fix_version_unsupported"); //$NON-NLS-1$
    static final I18NMessage1P FIX_FNF_NOMSG =
        new I18NMessage1P(LOGGER,"fix_fnf_nomsg"); //$NON-NLS-1$
    static final I18NMessage2P FIX_FNF_MSG =
        new I18NMessage2P(LOGGER,"fix_fnf_msg"); //$NON-NLS-1$

    static final I18NMessage0P ERROR_WRITING_EVENT_TO_LOG =
        new I18NMessage0P(LOGGER,"error_writing_event_to_log"); //$NON-NLS-1$
    static final I18NMessage1P ERROR_COULD_NOT_CLEAR_LOG =
        new I18NMessage1P(LOGGER,"error_could_not_clear_log"); //$NON-NLS-1$
    static final I18NMessage0P ERROR_COULD_NOT_CREATE_FIX_DATA_DICTIONARY =
        new I18NMessage0P(LOGGER,"error_could_not_create_fix_data_dictionary"); //$NON-NLS-1$
    static final I18NMessage1P CANNOT_CREATE_FIX_FIELD = new I18NMessage1P(LOGGER,
                                                                           "cannot_create_fix_field"); //$NON-NLS-1$
}


text:
&nbsp&nbsp&nbsp&nbspCar Details

        DashBoard&nbsp

        View Car&nbsp

       Details

            Car Model No :          <input type="text" readonly="true" value="{{cars.id}}">

            Car Name :              <input type="text" readonly="true" value="{{cars.name}}">

            Type :                     <input type="text" readonly="true" value="{{cars.type}}">

            Color :                     <input type="color" disabled="true" value="{{cars.color}}">

            Project Manager :        <input type="text" readonly="true" value="{{cars.Mname}}">

            Project Name :           <input type="text" readonly="true" value="{{cars.Pname}}">

            No of Seats :            <input type="text" readonly="true" value="{{cars.seats}}">

            Fuel Type :               <input type="text" readonly="true" value="{{cars.ftype}}">

<button ng-click="update(cars.id)"> Update</button>
                <button>  Cancel</button>


text:
/**
 * The dialog module enables the display of message boxes, custom modal dialogs and other overlays or slide-out UI abstractions. Dialogs are constructed by the composition system which interacts with a user defined dialog context. The dialog module enforced the activator lifecycle.
 * @module dialog
 * @requires system
 * @requires app
 * @requires composition
 * @requires activator
 * @requires viewEngine
 * @requires jquery
 * @requires knockout
 */
define(['durandal/system', 'durandal/app', 'durandal/composition', 'durandal/activator', 'durandal/viewEngine', 'jquery', 'knockout'], function (system, app, composition, activator, viewEngine, $, ko) {
    var contexts = {},
        dialogCount = 0,
        dialog;

    /**
     * Models a message box's message, title and options.
     * @class MessageBox
     */
    var MessageBox = function(message, title, options) {
        this.message = message;
        this.title = title || MessageBox.defaultTitle;
        this.options = options || MessageBox.defaultOptions;
    };

    /**
     * Selects an option and closes the message box, returning the selected option through the dialog system's promise.
     * @method selectOption
     * @param {string} dialogResult The result to select.
     */
    MessageBox.prototype.selectOption = function (dialogResult) {
        dialog.close(this, dialogResult);
    };

    /**
     * Provides the view to the composition system.
     * @method getView
     * @return {DOMElement} The view of the message box.
     */
    MessageBox.prototype.getView = function(){
        return viewEngine.processMarkup(MessageBox.defaultViewMarkup);
    };

    /**
     * Configures a custom view to use when displaying message boxes.
     * @method setViewUrl
     * @param {string} viewUrl The view url relative to the base url which the view locator will use to find the message box's view.
     * @static
     */
    MessageBox.setViewUrl = function(viewUrl){
        delete MessageBox.prototype.getView;
        MessageBox.prototype.viewUrl = viewUrl;
    };

    /**
     * The title to be used for the message box if one is not provided.
     * @property {string} defaultTitle
     * @default Application
     * @static
     */
    MessageBox.defaultTitle = app.title || 'Application';

    /**
     * The options to display in the message box of none are specified.
     * @property {string[]} defaultOptions
     * @default ['Ok']
     * @static
     */
    MessageBox.defaultOptions = ['Ok'];

    /**
     * The markup for the message box's view.
     * @property {string} defaultViewMarkup
     * @static
     */
/*
    MessageBox.defaultViewMarkup = [
        '
',
            '
',
                '

',
            '
',
            '
',
                '

',
            '
',
            '
',
                '<button class="btn" data-bind="click: function () { $parent.selectOption($data); }, text: $data, css: { \'btn-primary\': $index() == 0, autofocus: $index() == 0 }"></button>',
            '
',
        '
'
    ].join('\n');
*/

    MessageBox.defaultViewMarkup = [
    '
',
        '
',
            '
',
                '
',
                    '',
                    '

',
                '
',
                '
',
                    '

',
                '
',
                '
',
                    '<button class="btn" data-bind="click: function () { $parent.selectOption($data); }, text: $data, css: { \'btn-primary\': $index() == 0, autofocus: $index() == 0 }"></button>',
                '
',
            '
',
        '
',
    '
'
    ].join('\n');

    function ensureDialogInstance(objOrModuleId) {
        return system.defer(function(dfd) {
            if (system.isString(objOrModuleId)) {
                system.acquire(objOrModuleId).then(function (module) {
                    dfd.resolve(system.resolveObject(module));
                }).fail(function(err){
                    system.error('Failed to load dialog module (' + objOrModuleId + '). Details: ' + err.message);
                });
            } else {
                dfd.resolve(objOrModuleId);
            }
        }).promise();
    }

    /**
     * @class DialogModule
     * @static
     */
    dialog = {
        /**
         * The constructor function used to create message boxes.
         * @property {MessageBox} MessageBox
         */
        MessageBox:MessageBox,
        /**
         * The css zIndex that the last dialog was displayed at.
         * @property {number} currentZIndex
         */
        currentZIndex: 1050,
        /**
         * Gets the next css zIndex at which a dialog should be displayed.
         * @method getNextZIndex
         * @return {number} The next usable zIndex.
         */
        getNextZIndex: function () {
            return ++this.currentZIndex;
        },
        /**
         * Determines whether or not there are any dialogs open.
         * @method isOpen
         * @return {boolean} True if a dialog is open. false otherwise.
         */
        isOpen: function() {
            return dialogCount > 0;
        },
        /**
         * Gets the dialog context by name or returns the default context if no name is specified.
         * @method getContext
         * @param {string} [name] The name of the context to retrieve.
         * @return {DialogContext} True context.
         */
        getContext: function(name) {
            return contexts[name || 'default'];
        },
        /**
         * Adds (or replaces) a dialog context.
         * @method addContext
         * @param {string} name The name of the context to add.
         * @param {DialogContext} dialogContext The context to add.
         */
        addContext: function(name, dialogContext) {
            dialogContext.name = name;
            contexts[name] = dialogContext;

            var helperName = 'show' + name.substr(0, 1).toUpperCase() + name.substr(1);
            this[helperName] = function (obj, activationData) {
                return this.show(obj, activationData, name);
            };
        },
        createCompositionSettings: function(obj, dialogContext) {
            var settings = {
                model:obj,
                activate:false,
                transition: false
            };

            if (dialogContext.attached) {
                settings.attached = dialogContext.attached;
            }

            if (dialogContext.compositionComplete) {
                settings.compositionComplete = dialogContext.compositionComplete;
            }

            return settings;
        },
        /**
         * Gets the dialog model that is associated with the specified object.
         * @method getDialog
         * @param {object} obj The object for whom to retrieve the dialog.
         * @return {Dialog} The dialog model.
         */
        getDialog:function(obj){
            if(obj){
                return obj.__dialog__;
            }

            return undefined;
        },
        /**
         * Closes the dialog associated with the specified object.
         * @method close
         * @param {object} obj The object whose dialog should be closed.
         * @param {object} results* The results to return back to the dialog caller after closing.
         */
        close:function(obj){
            var theDialog = this.getDialog(obj);
            if(theDialog){
                var rest = Array.prototype.slice.call(arguments, 1);
                theDialog.close.apply(theDialog, rest);
            }
        },
        /**
         * Shows a dialog.
         * @method show
         * @param {object|string} obj The object (or moduleId) to display as a dialog.
         * @param {object} [activationData] The data that should be passed to the object upon activation.
         * @param {string} [context] The name of the dialog context to use. Uses the default context if none is specified.
         * @return {Promise} A promise that resolves when the dialog is closed and returns any data passed at the time of closing.
         */
        show: function(obj, activationData, context) {
            var that = this;
            var dialogContext = contexts[context || 'default'];

            return system.defer(function(dfd) {
                ensureDialogInstance(obj).then(function(instance) {
                    var dialogActivator = activator.create();

                    dialogActivator.activateItem(instance, activationData).then(function (success) {
                        if (success) {
                            var theDialog = instance.__dialog__ = {
                                owner: instance,
                                context: dialogContext,
                                activator: dialogActivator,
                                close: function () {
                                    var args = arguments;
                                    dialogActivator.deactivateItem(instance, true).then(function (closeSuccess) {
                                        if (closeSuccess) {
                                            dialogCount--;
                                            dialogContext.removeHost(theDialog);
                                            delete instance.__dialog__;

                                            if (args.length === 0) {
                                                dfd.resolve();
                                            } else if (args.length === 1) {
                                                dfd.resolve(args[0]);
                                            } else {
                                                dfd.resolve.apply(dfd, args);
                                            }
                                        }
                                    });
                                }
                            };

                            theDialog.settings = that.createCompositionSettings(instance, dialogContext);
                            dialogContext.addHost(theDialog);

                            dialogCount++;
                            composition.compose(theDialog.host, theDialog.settings);
                        } else {
                            dfd.resolve(false);
                        }
                    });
                });
            }).promise();
        },
        /**
         * Shows a message box.
         * @method showMessage
         * @param {string} message The message to display in the dialog.
         * @param {string} [title] The title message.
         * @param {string[]} [options] The options to provide to the user.
         * @return {Promise} A promise that resolves when the message box is closed and returns the selected option.
         */
        showMessage:function(message, title, options){
            if(system.isString(this.MessageBox)){
                return dialog.show(this.MessageBox, [
                    message,
                    title || MessageBox.defaultTitle,
                    options || MessageBox.defaultOptions
                ]);
            }

            return dialog.show(new this.MessageBox(message, title, options));
        },
        /**
         * Installs this module into Durandal; called by the framework. Adds `app.showDialog` and `app.showMessage` convenience methods.
         * @method install
         * @param {object} [config] Add a `messageBox` property to supply a custom message box constructor. Add a `messageBoxView` property to supply custom view markup for the built-in message box.
         */
        install:function(config){
            app.showDialog = function(obj, activationData, context) {
                return dialog.show(obj, activationData, context);
            };

            app.showMessage = function(message, title, options) {
                return dialog.showMessage(message, title, options);
            };

            if(config.messageBox){
                dialog.MessageBox = config.messageBox;
            }

            if(config.messageBoxView){
                dialog.MessageBox.prototype.getView = function(){
                    return config.messageBoxView;
                };
            }
        }
    };

    /**
     * @class DialogContext
     */
    dialog.addContext('default', {
        blockoutOpacity: .2,
        removeDelay: 200,
        /**
         * In this function, you are expected to add a DOM element to the tree which will serve as the "host" for the modal's composed view. You must add a property called host to the modalWindow object which references the dom element. It is this host which is passed to the composition module.
         * @method addHost
         * @param {Dialog} theDialog The dialog model.
         */
        addHost: function(theDialog) {
            var body = $('body');
            var blockout = $('

')
                .css({ 'z-index': dialog.getNextZIndex(), 'opacity': this.blockoutOpacity })
                .appendTo(body);

            var host = $('

')
                .css({ 'z-index': dialog.getNextZIndex() })
                .appendTo(body);

            theDialog.host = host.get(0);
            theDialog.blockout = blockout.get(0);

            if (!dialog.isOpen()) {
                theDialog.oldBodyMarginRight = body.css("margin-right");
                theDialog.oldInlineMarginRight = body.get(0).style.marginRight;

                var html = $("html");
                var oldBodyOuterWidth = body.outerWidth(true);
                var oldScrollTop = html.scrollTop();
                $("html").css("overflow-y", "hidden");
                var newBodyOuterWidth = $("body").outerWidth(true);
                body.css("margin-right", (newBodyOuterWidth - oldBodyOuterWidth + parseInt(theDialog.oldBodyMarginRight, 10)) + "px");
                html.scrollTop(oldScrollTop); // necessary for Firefox
            }
        },
        /**
         * This function is expected to remove any DOM machinery associated with the specified dialog and do any other necessary cleanup.
         * @method removeHost
         * @param {Dialog} theDialog The dialog model.
         */
        removeHost: function(theDialog) {
            $(theDialog.host).css('opacity', 0);
            $(theDialog.blockout).css('opacity', 0);

            setTimeout(function() {
                ko.removeNode(theDialog.host);
                ko.removeNode(theDialog.blockout);
            }, this.removeDelay);

            if (!dialog.isOpen()) {
                var html = $("html");
                var oldScrollTop = html.scrollTop(); // necessary for Firefox.
                html.css("overflow-y", "").scrollTop(oldScrollTop);

                if(theDialog.oldInlineMarginRight) {
                    $("body").css("margin-right", theDialog.oldBodyMarginRight);
                } else {
                    $("body").css("margin-right", '');
                }
            }
        },
        attached: function (view) {
            //To prevent flickering in IE8, we set visibility to hidden first, and later restore it
            $(view).css("visibility", "hidden");
        },
        /**
         * This function is called after the modal is fully composed into the DOM, allowing your implementation to do any final modifications, such as positioning or animation. You can obtain the original dialog object by using `getDialog` on context.model.
         * @method compositionComplete
         * @param {DOMElement} child The dialog view.
         * @param {DOMElement} parent The parent view.
         * @param {object} context The composition context.
         */
        compositionComplete: function (child, parent, context) {
            var theDialog = dialog.getDialog(context.model);
            var $child = $(child);
            var loadables = $child.find("img").filter(function () {
                //Remove images with known width and height
                var $this = $(this);
                return !(this.style.width && this.style.height) && !($this.attr("width") && $this.attr("height"));
            });

            $child.data("predefinedWidth", $child.get(0).style.width);

            var setDialogPosition = function () {
                //Setting a short timeout is need in IE8, otherwise we could do this straight away
                setTimeout(function () {
                    //We will clear and then set width for dialogs without width set
                    if (!$child.data("predefinedWidth")) {
                        $child.css({ width: '' }); //Reset width
                    }
                    var width = $child.outerWidth(false);
                    var height = $child.outerHeight(false);
                    var windowHeight = $(window).height();
                    var constrainedHeight = Math.min(height, windowHeight);

                    $child.css({
                        'margin-top': (-constrainedHeight / 2).toString() + 'px',
                        'margin-left': (-width / 2).toString() + 'px'
                    });

                    if (!$child.data("predefinedWidth")) {
                        //Ensure the correct width after margin-left has been set
                        $child.outerWidth(width);
                    }

                    if (height > windowHeight) {
                        $child.css("overflow-y", "auto");
                    } else {
                        $child.css("overflow-y", "");
                    }

                    $(theDialog.host).css('opacity', 1);
                    $child.css("visibility", "visible");

                    $child.find('.autofocus').first().focus();
                }, 1);
            };

            setDialogPosition();
            loadables.load(setDialogPosition);

            if ($child.hasClass('autoclose')) {
                $(theDialog.blockout).click(function () {
                    theDialog.close();
                });
            }
        }
    });

    return dialog;
});


text:
module BWAPI
  class Client
    module Admin
      module Clients
        # Search module for admin/search endpoints
        module Search

          # Get a list of queries
          #
          # @param opts [Hash] options hash of parameters
          # @option opts [Integer] text Text expression
          # @return [Hashie::Mash] List of queries
          def search_query_text opts
            get "admin/search/querytext"
          end
          alias :query_text :search_query_text

          # Get a list of query names
          #
          # @param opts [Hash] options hash of parameters
          # @option opts [Integer] text Text expression
          # @return [Hashie::Mash] List of query names
          def search_query_name opts
            get "admin/search/queryname"
          end
          alias :query_name :search_query_name

          # Get a list of rules
          #
          # @param opts [Hash] options hash of parameters
          # @option opts [Integer] text Text expression
          # @return [Hashie::Mash] List of rules
          def search_rule_text opts
            get "admin/search/ruletext"
          end
          alias :rule_text :search_rule_text

        end
      end
    end
  end
end


text:
angular.module('yds').directive('ydsEmbed', ['$compile', 'Data', function($compile, Data) {
	return {
		restrict: 'A',
		link: function (scope, element, attrs) {
			var projectId = scope.projectId;
			var elementClass = attrs.class;
			var embedCode ="";
			var visualisationType = "";
			var defaultVisTypes = ["pie", "line", "bar", "map"];

			//check if the element has id, accepted: "pie-container, line-container, bar-container, map-container"
			if (!angular.isUndefined(elementClass) && elementClass!="") {
				var visTypeFound = false;

				for (var i=0; i<defaultVisTypes.length; i++) {				//check if the main element is a valid yds container
					var visTypeIndex = elementClass.indexOf(defaultVisTypes[i]);

					//if the one of the defaultVisTypes exist in the element id, get the visualisation type
					if (visTypeIndex>-1) {
						visualisationType = defaultVisTypes[i];
						visTypeFound = true;
						break;
					}
				}

				if (!visTypeFound) {
					console.error('The embed extension cannot be applied on the selected element');
					return false;
				}
			} else
				return false;

			//check if the user has enabled the embedding of the selected element
			var embeddable = scope.embeddable;
			if (!angular.isUndefined(embeddable) && embeddable=="true"){
				if (!angular.isUndefined(projectId) /*&& !isNaN(projectId)*/){
					var popoverPos = scope.popoverPos;		//indicates the position the popover
					var embedBtnX = scope.embedBtnX;		//indicates the x position the embed button
					var embedBtnY = scope.embedBtnY;		//indicates the y position the embed button
					var defaultPos = ["top", "bottom", "left", "right"];

					//if popover position is undefined assign the default value
					if (angular.isUndefined(popoverPos) || _.indexOf(defaultPos, popoverPos)==-1)
						popoverPos = "right";

					//if embedBtnX property is undefined assign the default value
					if (angular.isUndefined(embedBtnX) || isNaN(embedBtnX))
						embedBtnX = 12;

					//if embedBtnY property is undefined assign the default value
					if (angular.isUndefined(embedBtnY) || isNaN(embedBtnY))
						embedBtnY = 12;

					scope.popoverOpen = false;    //flag that indicates if the embed tooltip is shown
					scope.popover = {
						content: '',
						templateUrl: 'templates/embed-popover.html',
						title: 'Embed URL'
					};

					var embedBtnTemplate = '<button type="button"' +
							'class="btn btn-default btn-xs embed-btn"' +
							'ng-click = "requestEmbed(this)"' +
							'popover-trigger = "none"' +
							'popover-is-open="popoverOpen"' +
							'popover-placement="'+ popoverPos + '"' +
							'uib-popover-template="popover.templateUrl">' +
							'' +
							'</button>';

					//compile the embed button and append it to the element's container
					var compiledTemplate = $compile(embedBtnTemplate)(scope);
					compiledTemplate.css('position', 'absolute');
					compiledTemplate.css('top', embedBtnY + 'px');
					compiledTemplate.css('left', embedBtnX + 'px');
					compiledTemplate.css('z-index', 9999999);
					compiledTemplate.css('font-size', 11 + 'px');
					compiledTemplate.css('cursor', 'pointer');

					element.parent().append(compiledTemplate);
				} else {
					console.error('The embed extension is not configured properly');
					return false;
				}
			} else
				return false;

			scope.requestEmbed = function (element) {
				if (embedCode=="") {          //if the request code doesn't exist
					var facets = [{
						facet_type : "",
						facet_values: []
					}];

					Data.requestEmbedCode(projectId, facets, visualisationType)
					.then(function (response) {
						embedCode = response.generated_hash;
						scope.popover.content = '' +
								'
Your browser does not support iframes.
' +
								'';
						element.popoverOpen = true;
					}, function (error) {
						console.log('request embed code error:', error);
					});
				} else
					element.popoverOpen = !element.popoverOpen;
			};
		}
	}
}]);


text:
<resources>
    <string name="app_name">ProjectScalableImageView</string>
</resources>


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

namespace Microsoft.WindowsAzure.Test.Network.Behaviors
{
    using System;
    using System.Threading;
    using Fiddler;

    /// <summary>
    /// DelayBehaviors control whether the sessions should be delayed before being delivered to user code.
    /// </summary>
    public static class DelayBehaviors
    {
        /// <summary>
        /// DelayAllRequests returns a behavior that delays all requests the specified number of milliseconds.
        /// </summary>
        /// <param name="delayInMs">The time in milliseconds to delay the request.</param>
        /// <param name="options">The options controlling the behavior.</param>
        /// <returns>The relevant behavior.</returns>
        public static ProxyBehavior DelayAllRequests(int delayInMs, BehaviorOptions options = null)
        {
            return new DelayRequestBehavior(delayInMs, null, options);
        }

        /// <summary>
        /// DelayAllRequestsIf returns a behavior that delays requests the specified number of milliseconds.
        /// </summary>
        /// <param name="delayInMs">The time in milliseconds to delay the request.</param>
        /// <param name="selector">The predicate controlling when to delay the request.</param>
        /// <param name="options">The options controlling the behavior.</param>
        /// <returns>The relevant behavior.</returns>
        public static ProxyBehavior DelayAllRequestsIf(int delayInMs, Func<Session, bool> selector, BehaviorOptions options = null)
        {
            return new DelayRequestBehavior(delayInMs, selector, options);
        }

        /// <summary>
        /// DelayAllRequestsUntil returns a behavior that delays all requests the specified number of milliseconds.
        /// </summary>
        /// <param name="delayInMs">The time in milliseconds to delay the request.</param>
        /// <param name="expiry">The DateTime at which to stop delaying requests.</param>
        /// <returns>The relevant behavior.</returns>
        public static ProxyBehavior DelayAllRequestsUntil(int delayInMs, DateTime expiry)
        {
            return new DelayRequestBehavior(delayInMs, expiry);
        }

        /// <summary>
        /// DelayAllRequestsUntilIf returns a behavior that delays all requests the specified number of milliseconds.
        /// </summary>
        /// <param name="delayInMs">The time in milliseconds to delay the request.</param>
        /// <param name="expiry">The DateTime at which to stop delaying requests.</param>
        /// <param name="selector">The predicate controlling when to delay the request.</param>
        /// <returns>The relevant behavior.</returns>
        public static ProxyBehavior DelayAllRequestsUntilIf(int delayInMs, DateTime expiry, Func<Session, bool> selector)
        {
            return new DelayRequestBehavior(delayInMs, expiry, selector);
        }

        /// <summary>
        /// DelayNRequests returns a behavior that delays requests the specified number of milliseconds.
        /// </summary>
        /// <param name="delayInMs">The time in milliseconds to delay the request.</param>
        /// <param name="n">The maximum number of sessions which should be delayed.</param>
        /// <returns>The relevant behavior.</returns>
        public static ProxyBehavior DelayNRequests(int delayInMs, int n)
        {
            return new DelayRequestBehavior(delayInMs, n);
        }

        /// <summary>
        /// DelayNRequestsIf returns a behavior that delays requests the specified number of milliseconds.
        /// </summary>
        /// <param name="delayInMs">The time in milliseconds to delay the request.</param>
        /// <param name="n">The maximum number of sessions which should be delayed.</param>
        /// <param name="selector">The predicate controlling when to delay the request.</param>
        /// <returns>The relevant behavior.</returns>
        public static ProxyBehavior DelayNRequestsIf(int delayInMs, int n, Func<Session, bool> selector)
        {
            return new DelayRequestBehavior(delayInMs, n, selector);
        }

        /// <summary>
        /// DelayAllResponses returns a behavior that delays all responses the specified number of milliseconds.
        /// </summary>
        /// <param name="delayInMs">The time in milliseconds to delay the response.</param>
        /// <param name="options">The options controlling the behavior.</param>
        /// <returns>The relevant behavior.</returns>
        public static ProxyBehavior DelayAllResponses(int delayInMs, BehaviorOptions options = null)
        {
            return new DelayResponseBehavior(delayInMs, null, options);
        }

        /// <summary>
        /// DelayAllResponsesIf returns a behavior that delays responses the specified number of milliseconds.
        /// </summary>
        /// <param name="delayInMs">The time in milliseconds to delay the response.</param>
        /// <param name="selector">The predicate controlling when to delay the response.</param>
        /// <param name="options">The options controlling the behavior.</param>
        /// <returns>The relevant behavior.</returns>
        public static ProxyBehavior DelayAllResponsesIf(int delayInMs, Func<Session, bool> selector, BehaviorOptions options = null)
        {
            return new DelayResponseBehavior(delayInMs, selector, options);
        }

        /// <summary>
        /// DelayAllResponsesUntil returns a behavior that delays responses the specified number of milliseconds.
        /// </summary>
        /// <param name="delayInMs">The time in milliseconds to delay the response.</param>
        /// <param name="expiry">The DateTime at which to stop delaying responses.</param>
        /// <returns>The relevant behavior.</returns>
        public static ProxyBehavior DelayAllResponsesUntil(int delayInMs, DateTime expiry)
        {
            return new DelayResponseBehavior(delayInMs, expiry);
        }

        /// <summary>
        /// DelayAllResponsesUntilIf returns a behavior that delays responses the specified number of milliseconds.
        /// </summary>
        /// <param name="delayInMs">The time in milliseconds to delay the response.</param>
        /// <param name="expiry">The DateTime at which to stop delaying responses.</param>
        /// <param name="selector">The predicate controlling when to delay the response.</param>
        /// <returns>The relevant behavior.</returns>
        public static ProxyBehavior DelayAllResponsesUntilIf(int delayInMs, DateTime expiry, Func<Session, bool> selector)
        {
            return new DelayResponseBehavior(delayInMs, expiry, selector);
        }

        /// <summary>
        /// DelayNResponses returns a behavior that delays responses the specified number of milliseconds.
        /// </summary>
        /// <param name="delayInMs">The time in milliseconds to delay the response.</param>
        /// <param name="n">The maximum number of sessions which should be delayed.</param>
        /// <returns>The relevant behavior.</returns>
        public static ProxyBehavior DelayNResponses(int delayInMs, int n)
        {
            return new DelayResponseBehavior(delayInMs, n);
        }

        /// <summary>
        /// DelayNResponsesIf returns a behavior that delays responses the specified number of milliseconds.
        /// </summary>
        /// <param name="delayInMs">The time in milliseconds to delay the response.</param>
        /// <param name="n">The maximum number of sessions which should be delayed.</param>
        /// <param name="selector">The predicate controlling when to delay the response.</param>
        /// <returns>The relevant behavior.</returns>
        public static ProxyBehavior DelayNResponsesIf(int delayInMs, int n, Func<Session, bool> selector)
        {
            return new DelayResponseBehavior(delayInMs, n, selector);
        }

        /// <summary>
        /// Helper class for request (outgoing) delays.
        /// </summary>
        private class DelayRequestBehavior : ProxyBehavior
        {
            /// <summary>
            /// Initializes a new instance of the DelayRequestBehavior class.
            /// </summary>
            /// <param name="delayInMs">The time in milliseconds to delay the request.</param>
            /// <param name="selector">The predicate controlling when to delay the request.</param>
            /// <param name="options">The options controlling the behavior.</param>
            public DelayRequestBehavior(int delayInMs, Func<Session, bool> selector = null, BehaviorOptions options = null)
                : base(session => session.oRequest.pipeClient.TransmitDelay = delayInMs, selector, options, TriggerType.BeforeRequest)
            {
            }

            /// <summary>
            /// Initializes a new instance of the DelayRequestBehavior class.
            /// </summary>
            /// <param name="delayInMs">The time in milliseconds to delay the request.</param>
            /// <param name="n">The maximum number of sessions which should be delayed.</param>
            /// <param name="selector">The predicate controlling when to delay the request.</param>
            public DelayRequestBehavior(int delayInMs, int n, Func<Session, bool> selector = null)
                : this(delayInMs, selector, new BehaviorOptions(maximumRemainingSessions: n))
            {
            }

            /// <summary>
            /// Initializes a new instance of the DelayRequestBehavior class.
            /// </summary>
            /// <param name="delayInMs">The time in milliseconds to delay the request.</param>
            /// <param name="expiry">The DateTime at which to no longer delay requests.</param>
            /// <param name="selector">The predicate controlling when to delay the request.</param>
            public DelayRequestBehavior(int delayInMs, DateTime expiry, Func<Session, bool> selector = null)
                : this(delayInMs, selector, new BehaviorOptions(expiry))
            {
            }
        }

        /// <summary>
        /// Helper class for response (incoming) delays.
        /// </summary>
        private class DelayResponseBehavior : ProxyBehavior
        {
            /// <summary>
            /// Initializes a new instance of the DelayResponseBehavior class.
            /// </summary>
            /// <param name="delayInMs">The time in milliseconds to delay the response.</param>
            /// <param name="selector">The predicate controlling when to delay the response.</param>
            /// <param name="options">The options controlling the behavior.</param>
            public DelayResponseBehavior(int delayInMs, Func<Session, bool> selector = null, BehaviorOptions options = null)
                : base(session => session.oResponse.pipeServer.TransmitDelay = delayInMs, selector, options, TriggerType.BeforeResponse)
            {
            }

            /// <summary>
            /// Initializes a new instance of the DelayResponseBehavior class.
            /// </summary>
            /// <param name="delayInMs">The time in milliseconds to delay the response.</param>
            /// <param name="n">The maximum number of sessions which should be delayed.</param>
            /// <param name="selector">The predicate controlling when to delay the response.</param>
            public DelayResponseBehavior(int delayInMs, int n, Func<Session, bool> selector = null)
                : this(delayInMs, selector, new BehaviorOptions(maximumRemainingSessions: n))
            {
            }

            /// <summary>
            /// Initializes a new instance of the DelayResponseBehavior class.
            /// </summary>
            /// <param name="delayInMs">The time in milliseconds to delay the response.</param>
            /// <param name="expiry">The DateTime at which to no longer delay responses.</param>
            /// <param name="selector">The predicate controlling when to delay the response.</param>
            public DelayResponseBehavior(int delayInMs, DateTime expiry, Func<Session, bool> selector = null)
                : this(delayInMs, selector, new BehaviorOptions(expiry))
            {
            }
        }
    }
}


text:
Circles of Space - Audiovisual Installation

This project was a collaboration between Dutch designer Anouk Wipprecht and myself, presented at CODAME Art+Tech in San Francisco. The concept was to create an interactive visualization of personal space using a projector and sensors worn on the body.

# Play with the interactive web demo.
Built for Chrome only!

Everything that you see in the visuals was created using CSS and JavaScript. I also created some ambient sound loops that correspond to the visual intensities.


text:
function CreatePerson(name, gender) { //構造物件的函式(工廠方式)
    //系統內部執行
    //var this = new Object();

    //加工
    this.name = name;
    this.gender = gender;
    this.showName = function() {
        console.log("my name:" + this.name);
    };
    this.showGender = function() {
        console.log("my gender:" + this.gender);
    };

    //系統內部執行
    //return this;
}
var p1 = new CreatePerson("Mark", "male");
var p2 = new CreatePerson("Susan", "female");


text:
package org.jibberjabber.dialogue;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import org.jibberjabber.dialogue.model.Question;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

public class QuestionsActivity extends Activity {

    private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;

    private TextToSpeech mTtobj;

    private ImageView mImageView;

    private View mViewStart;
    private View mViewRepeat;
    private View mViewNext;

    private AudioManager mAudioManager;

    private HashMap<String, String> mParams;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_questions);
        bindViews();

        mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);

        mParams = new HashMap<String, String>();
        mParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "utterance_id");

        mTtobj = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    mTtobj.setLanguage(Locale.UK);

                    mTtobj.setOnUtteranceProgressListener(new UtteranceProgressListener() {

                        @Override
                        public void onStart(String utteranceId) {
                        }

                        @Override
                        public void onError(String utteranceId) {
                        }

                        @Override
                        public void onDone(String utteranceId) {
                            runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    onSpeechCompleted();
                                }
                            });
                        }
                    });
                }
            }
        });

    }

    @Override
    public void onDestroy() {
        if (mTtobj != null) {
            mTtobj.stop();
            mTtobj.shutdown();
        }
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)

            // If Voice recognition is successful then it returns RESULT_OK
            if (resultCode == RESULT_OK) {

                ArrayList<String> textMatchList = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if (!textMatchList.isEmpty()) {
                    // If first Match contains the 'search' word
                    // Then start web search.
                    onRecognized(textMatchList);
                }
                // Result code for various error.
            } else {
                speakText(JibberJabberApplication.mQuestions.getCurrent());
            }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void bindViews() {

        mImageView = (ImageView) findViewById(R.id.image);

        mViewStart = findViewById(R.id.btn_start);
        mViewStart.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                speakText(JibberJabberApplication.mQuestions.getCurrent());
            }
        });

        mViewRepeat = findViewById(R.id.btn_repeat);
        mViewRepeat.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                speakText(JibberJabberApplication.mQuestions.getCurrent());
            }
        });

        mViewNext = findViewById(R.id.btn_next);
        mViewNext.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (JibberJabberApplication.mQuestions.next()) {
                    speakText(JibberJabberApplication.mQuestions.getCurrent());
                } else {
                    onFinish();
                }
            }

        });

        mViewStart.setVisibility(View.VISIBLE);
        mViewRepeat.setVisibility(View.GONE);
        mViewNext.setVisibility(View.GONE);

    }

    public void promptAnswer() {
        mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);

        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        // Specify the calling package to identify your application
        intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage()
                                                                          .getName());

        // Display an hint to the user about what he should say.
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak your answer");
        // intent.putExtra(RecognizerIntent.E, "Speak your answer");

        // Given an hint to the recognizer about what the user is going to say
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);

        // // If number of Matches is not selected then return show toast
        // message
        // if (msTextMatches.getSelectedItemPosition() ==
        // AdapterView.INVALID_POSITION) {
        // Toast.makeText(this, "Please select No. of Matches from spinner",
        // Toast.LENGTH_SHORT)
        // .show();
        // return;
        // }

        int noOfMatches = 7;

        // Specify how many results you want to receive. The results will be
        // sorted where the first result is the one with higher confidence.

        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches);

        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);

        mViewStart.setVisibility(View.GONE);
        mViewRepeat.setVisibility(View.GONE);
        mViewNext.setVisibility(View.GONE);
    }

    private void onRecognized(final ArrayList<String> textMatchList) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);

                        String answer = JibberJabberApplication.mQuestions.getCurrent().mAnswer;
                        boolean success = isAnswerRight(textMatchList, answer);
                        if (success) {
                            MediaPlayer mediaPlayer = MediaPlayer.create(QuestionsActivity.this, R.raw.right);
                            mediaPlayer.start();
                            mImageView.setImageResource(R.drawable.tick_green);
                        } else {
                            mImageView.setImageResource(R.drawable.cross_red);
                            MediaPlayer mediaPlayer = MediaPlayer.create(QuestionsActivity.this, R.raw.wrong2);
                            mediaPlayer.start();
                        }

                        mViewStart.setVisibility(View.GONE);
                        mViewRepeat.setVisibility(View.VISIBLE);
                        mViewNext.setVisibility(View.VISIBLE);
                    }
                });
            }
        }).start();

    }

    private boolean isAnswerRight(ArrayList<String> textMatchList, String answer) {
        Log.i("stp", "===========");
        Log.i("stp", ">>> " + answer.toLowerCase()
                                    .trim());

        for (String recognized : textMatchList) {
            if (matches(answer, recognized)) {
                return true;
            }
        }
        return false;
    }

    private boolean matches(String answer, String recognized) {

        if (answer == null) {
            return false;
        }
        if (recognized == null) {
            return false;
        }

        Log.i("stp", "<<< " + recognized.toLowerCase()
                                        .trim());

        return recognized.trim()
                         .equalsIgnoreCase(answer.trim());
    }

    public void speakText(Question question) {
        mImageView.setImageResource(R.drawable.question);
        speakText(question.mQuestion);
    }

    public void speakText(String toSpeak) {
        mTtobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, mParams);
    }

    private void onFinish() {
        showToastMessage("See you soon!");
    }

    void showToastMessage(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT)
             .show();
    }

    private void onSpeechCompleted() {
        promptAnswer();
    }

}