<commit_before>/**
 * @license Angulartics
 * (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics
 * Piwik 2.1.x update contributed by http://github.com/highskillz
 * License: MIT
 */

/* global _paq */

(function(angular) {
    'use strict';

    /**
     * @ngdoc overview
     * @name angulartics.piwik
     * Enables analytics support for Piwik (http://piwik.org/docs/tracking-api/)
     */
    angular.module('angulartics.piwik', ['angulartics'])
        .config(['$analyticsProvider', '$windowProvider',
            function($analyticsProvider, $windowProvider) {

                var $window = $windowProvider.$get();

                $analyticsProvider.settings.pageTracking.trackRelativePath = true;

                // Add piwik specific trackers to angulartics API

                // Requires the CustomDimensions plugin for Piwik.
                $analyticsProvider.api.setCustomDimension = function(dimensionId, value) {

                    if ($window._paq) {
                        $window._paq.push(['setCustomDimension', dimensionId, value]);
                    }
                };

                // Requires the CustomDimensions plugin for Piwik.
                $analyticsProvider.api.deleteCustomDimension = function(dimensionId) {

                    if ($window._paq) {
                        $window._paq.push(['deleteCustomDimension', dimensionId]);
                    }
                };

                // scope: visit or page. Defaults to 'page'
                $analyticsProvider.api.setCustomVariable = function(varIndex, varName, value, scope) {

                    if ($window._paq) {
                        scope = scope || 'page';
                        $window._paq.push(['setCustomVariable', varIndex, varName, value, scope]);
                    }
                };

                // scope: visit or page. Defaults to 'page'
                $analyticsProvider.api.deleteCustomVariable = function(varIndex, scope) {

                    if ($window._paq) {
                        scope = scope || 'page';
                        $window._paq.push(['deleteCustomVariable', varIndex, scope]);
                    }
                };

                // trackSiteSearch(keyword, category, [searchCount])
                $analyticsProvider.api.trackSiteSearch = function(keyword, category, searchCount) {

                    // keyword is required
                    if ($window._paq && keyword) {

                        var params = ['trackSiteSearch', keyword, category || false];

                        // searchCount is optional
                        if (angular.isDefined(searchCount)) {
                            params.push(searchCount);
                        }

                        $window._paq.push(params);
                    }
                };

                // logs a conversion for goal 1. revenue is optional
                // trackGoal(goalID, [revenue]);
                $analyticsProvider.api.trackGoal = function(goalID, revenue) {
                    if ($window._paq) {
                        _paq.push(['trackGoal', goalID, revenue || 0]);
                    }
                };

                // track outlink or download
                // linkType is 'link' or 'download', 'link' by default
                // trackLink(url, [linkType]);
                $analyticsProvider.api.trackLink = function(url, linkType) {
                    var type = linkType || 'link';
                    if ($window._paq) {
                        $window._paq.push(['trackLink', url, type]);
                    }
                };

                // Set default angulartics page and event tracking

                // $analytics.setUsername(username)
                $analyticsProvider.registerSetUsername(function(username) {
                    if ($window._paq) {
                        $window._paq.push(['setUserId', username]);
                    }
                });

                // $analytics.setAlias(alias)
                // $analyticsProvider.registerSetAlias(function(param) {
                //     // TODO: No piwik corresponding function found. Use setCustomVariable instead
                // });

                // $analytics.setUserProperties(properties)
                // $analyticsProvider.registerSetUserProperties(function(param) {
                //     // TODO: No piwik corresponding function found. Use setCustomVariable instead
                // });

                // locationObj is the angular $location object
                $analyticsProvider.registerPageTrack(function(path, locationObj) {

                    if ($window._paq) {
                        $window._paq.push(['setDocumentTitle', $window.document.title]);
                        $window._paq.push(['setCustomUrl', path]);
                        $window._paq.push(['trackPageView']);
                    }
                });

                // trackEvent(category, event, [name], [value])
                $analyticsProvider.registerEventTrack(function(action, properties) {

                    if ($window._paq) {

                        // PAQ requires that eventValue be an integer, see: http://piwik.org/docs/event-tracking/
                        if (properties.value) {
                            var parsed = parseInt(properties.value, 10);
                            properties.value = isNaN(parsed) ? 0 : parsed;
                        }

                        $window._paq.push(['trackEvent', properties.category, action, properties.label, properties.value]);
                    }
                });

              /**
               * Exception Track Event in GA
               * @name exceptionTrack
               * Sugar on top of the eventTrack method for easily handling errors
               *
               * @param {object} error An Error object to track: error.toString() used for event 'action', error.stack used for event 'label'.
               * @param {object} cause The cause of the error given from $exceptionHandler, not used.
               *
               * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/events
               */
              $analyticsProvider.registerExceptionTrack(function (error, cause) {
                  if ($window._paq) {
                      $window._paq.push(['trackEvent', 'Exceptions', error.toString(), error.stack, 0]);
                  }
              });
            }
        ]);
})(angular);
<commit_msg>Update angulartics-piwik.js<commit_after>/**
 * @license Angulartics
 * (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics
 * Piwik 2.1.x update contributed by http://github.com/highskillz
 * License: MIT
 */

/* global _paq */

(function(angular) {
    'use strict';

    /**
     * @ngdoc overview
     * @name angulartics.piwik
     * Enables analytics support for Piwik (http://piwik.org/docs/tracking-api/)
     */
    angular.module('angulartics.piwik', ['angulartics'])
        .config(['$analyticsProvider', '$windowProvider',
            function($analyticsProvider, $windowProvider) {

                var $window = $windowProvider.$get();

                $analyticsProvider.settings.pageTracking.trackRelativePath = true;

                // Add piwik specific trackers to angulartics API

                // Requires the CustomDimensions plugin for Piwik.
                $analyticsProvider.api.setCustomDimension = function(dimensionId, value) {

                    if ($window._paq) {
                        $window._paq.push(['setCustomDimension', dimensionId, value]);
                    }
                };

                // Requires the CustomDimensions plugin for Piwik.
                $analyticsProvider.api.deleteCustomDimension = function(dimensionId) {

                    if ($window._paq) {
                        $window._paq.push(['deleteCustomDimension', dimensionId]);
                    }
                };

                // scope: visit or page. Defaults to 'page'
                $analyticsProvider.api.setCustomVariable = function(varIndex, varName, value, scope) {

                    if ($window._paq) {
                        scope = scope || 'page';
                        $window._paq.push(['setCustomVariable', varIndex, varName, value, scope]);
                    }
                };

                // scope: visit or page. Defaults to 'page'
                $analyticsProvider.api.deleteCustomVariable = function(varIndex, scope) {

                    if ($window._paq) {
                        scope = scope || 'page';
                        $window._paq.push(['deleteCustomVariable', varIndex, scope]);
                    }
                };

                // trackSiteSearch(keyword, category, [searchCount])
                $analyticsProvider.api.trackSiteSearch = function(keyword, category, searchCount) {

                    // keyword is required
                    if ($window._paq && keyword) {

                        var params = ['trackSiteSearch', keyword, category || false];

                        // searchCount is optional
                        if (angular.isDefined(searchCount)) {
                            params.push(searchCount);
                        }

                        $window._paq.push(params);
                    }
                };

                // logs a conversion for goal 1. revenue is optional
                // trackGoal(goalID, [revenue]);
                $analyticsProvider.api.trackGoal = function(goalID, revenue) {
                    if ($window._paq) {
                        _paq.push(['trackGoal', goalID, revenue || 0]);
                    }
                };

                // track outlink or download
                // linkType is 'link' or 'download', 'link' by default
                // trackLink(url, [linkType]);
                $analyticsProvider.api.trackLink = function(url, linkType) {
                    var type = linkType || 'link';
                    if ($window._paq) {
                        $window._paq.push(['trackLink', url, type]);
                    }
                };

                // Set default angulartics page and event tracking

                // $analytics.setUsername(username)
                $analyticsProvider.registerSetUsername(function(username) {
                    if ($window._paq) {
                        $window._paq.push(['setUserId', username]);
                    }
                });

                // $analytics.setAlias(alias)
                // $analyticsProvider.registerSetAlias(function(param) {
                //     // TODO: No piwik corresponding function found. Use setCustomVariable instead
                // });

                // $analytics.setUserProperties(properties)
                // $analyticsProvider.registerSetUserProperties(function(param) {
                //     // TODO: No piwik corresponding function found. Use setCustomVariable instead
                // });

                // locationObj is the angular $location object
                $analyticsProvider.registerPageTrack(function(path, locationObj) {

                    if ($window._paq) {
                        $window._paq.push(['setDocumentTitle', $window.document.title]);
                        $window._paq.push(['setCustomUrl', path]);
                        $window._paq.push(['trackPageView']);
                    }
                });

                // trackEvent(category, event, [name], [value])
                $analyticsProvider.registerEventTrack(function(action, properties) {

                    if ($window._paq) {

                        // PAQ requires that eventValue be an integer, see: http://piwik.org/docs/event-tracking/
                        if (properties.value) {
                            var parsed = parseInt(properties.value, 10);
                            properties.value = isNaN(parsed) ? 0 : parsed;
                        }

                        $window._paq.push(['trackEvent', properties.category, action, properties.label, properties.value]);
                    }
                });

              /**
               * @name exceptionTrack
               * Sugar on top of the eventTrack method for easily handling errors
               *
               * @param {object} error An Error object to track: error.toString() used for event 'action', error.stack used for event 'label'.
               * @param {object} cause The cause of the error given from $exceptionHandler, not used.
               */
              $analyticsProvider.registerExceptionTrack(function (error, cause) {
                  if ($window._paq) {
                      $window._paq.push(['trackEvent', 'Exceptions', error.toString(), error.stack, 0]);
                  }
              });
            }
        ]);
})(angular);
<|endoftext|>


<commit_before>import { lightenColor as lighten, darkenColor as darken } from '../utils';

describe('utils', () => {
  it('should guard non-string value is being passed to color of theme object', () => {
    const result = () => {
      return lighten(1234);
    };

    expect(result).toThrow();
  });

  it('should guard anything that is not working with polished', () => {
    const color = '1234';

    const result = lighten(color);

    expect(result).toEqual(color);
  });

  it('should guard css variables is being passed to polished functions', () => {
    const color = 'var(--my-var, blue)';

    const result = lighten(color);

    expect(result).toEqual(color);
  });

  it('should guard css calc is being passed to polished functions', () => {
    const color = 'rgb(calc(0 + 100), calc(0 + 100), calc(0 + 100))';

    const result = lighten(color);

    expect(result).toEqual(color);
  });

  it('should guard linear-gradient is being passed to polished functions', () => {
    const color = `linear-gradient(to bottom, white, blue)`;

    const result = lighten(color);

    expect(result).toEqual(color);
  });

  it('should guard radial-gradient is being passed to polished functions', () => {
    const color = `radial-gradient(red, green, blue)`;

    const result = lighten(color);

    expect(result).toEqual(color);
  });

  it('should guard repeating-linear-gradient is being passed to polished functions', () => {
    const color = `repeating-linear-gradient(red, yellow 10%, green 20%)`;

    const result = lighten(color);

    expect(result).toEqual(color);
  });

  it('should guard repeating-radial-gradient is being passed to polished functions', () => {
    const color = `repeating-radial-gradient(red, yellow 10%, green 20%)`;

    const result = lighten(color);

    expect(result).toEqual(color);
  });
});
<commit_msg>Add test case for valid arguments<commit_after>import { lightenColor as lighten, darkenColor as darken } from '../utils';

describe('utils', () => {
  it('should apply polished when valid arguments are passed', () => {
    const lightColor = '#F6F9FC';
    const darkColor = '#2f2f2f';
    const darkenedColor = darken(lightColor);
    const lightenedColor = lighten(darkColor);

    expect(darkenedColor).toEqual('rgba(0,0,0,0.95)');
    expect(lightenedColor).toEqual('rgba(255,255,255,0.95)');
  });

  it('should guard non-string value is being passed to color of theme object', () => {
    const result = () => {
      return lighten(1234);
    };

    expect(result).toThrow();
  });

  it('should guard anything that is not working with polished', () => {
    const color = '1234';

    const result = lighten(color);

    expect(result).toEqual(color);
  });

  it('should guard css variables is being passed to polished functions', () => {
    const color = 'var(--my-var, blue)';

    const result = lighten(color);

    expect(result).toEqual(color);
  });

  it('should guard css calc is being passed to polished functions', () => {
    const color = 'rgb(calc(0 + 100), calc(0 + 100), calc(0 + 100))';

    const result = lighten(color);

    expect(result).toEqual(color);
  });

  it('should guard linear-gradient is being passed to polished functions', () => {
    const color = `linear-gradient(to bottom, white, blue)`;

    const result = lighten(color);

    expect(result).toEqual(color);
  });

  it('should guard radial-gradient is being passed to polished functions', () => {
    const color = `radial-gradient(red, green, blue)`;

    const result = lighten(color);

    expect(result).toEqual(color);
  });

  it('should guard repeating-linear-gradient is being passed to polished functions', () => {
    const color = `repeating-linear-gradient(red, yellow 10%, green 20%)`;

    const result = lighten(color);

    expect(result).toEqual(color);
  });

  it('should guard repeating-radial-gradient is being passed to polished functions', () => {
    const color = `repeating-radial-gradient(red, yellow 10%, green 20%)`;

    const result = lighten(color);

    expect(result).toEqual(color);
  });
});
<|endoftext|>


<commit_before>import Provider from 'torii/providers/base';
import {configurable} from 'torii/configuration';
import QueryString from 'torii/lib/query-string';
import requiredProperty from 'torii/lib/required-property';

function currentUrl(){
  return [window.location.protocol,
          "//",
          window.location.host,
          window.location.pathname].join('');
}

/**
 * Implements authorization against an OAuth2 API
 * using the OAuth2 authorization flow in a popup window.
 *
 * Subclasses should extend this class and define the following properties:
 *   - requiredUrlParams: If there are additional required params
 *   - optionalUrlParams: If there are additional optional params
 *   - name: The name used in the configuration `providers` key
 *   - baseUrl: The base url for OAuth2 code-based flow at the 3rd-party
 *
 *   If there are any additional required or optional url params,
 *   include default values for them (if appropriate).
 *
 * @class Oauth2Provider
 */
var Oauth2 = Provider.extend({
  concatenatedProperties: ['requiredUrlParams','optionalUrlParams'],

  /**
   * The parameters that must be included as query params in the 3rd-party provider's url that we build.
   * These properties are in the format that should be in the URL (i.e.,
   * usually underscored), but they are looked up as camelCased properties
   * on the instance of this provider. For example, if the 'client_id' is
   * a required url param, when building the URL we look up the value of
   * the 'clientId' (camel-cased) property and put it in the URL as
   * 'client_id=' + this.get('clientId')
   * Subclasses can add additional required url params.
   *
   * @property {array} requiredUrlParams
   */
  requiredUrlParams: ['response_type', 'client_id', 'redirect_uri'],

  /**
   * Parameters that may be included in the 3rd-party provider's url that we build.
   * Subclasses can add additional optional url params.
   *
   * @property {array} optionalUrlParams
   */
  optionalUrlParams: ['scope'],

  /**
   * The base url for the 3rd-party provider's OAuth2 flow (example: 'https://github.com/login/oauth/authorize')
   *
   * @property {string} baseUrl
   */
  baseUrl:      requiredProperty(),

  /**
   * The apiKey (sometimes called app id) that identifies the registered application at the 3rd-party provider
   *
   * @property {string} apiKey
   */
  apiKey:       configurable('apiKey'),

  scope:        configurable('scope', null),
  clientId:     Ember.computed.alias('apiKey'),

  /**
   * The oauth response type we expect from the third party provider. Hardcoded to 'code' for oauth2-code flows
   * @property {string} responseType
   */
  responseType: 'code',

 /**
  * List of parameters that we expect
  * to see in the query params that the 3rd-party provider appends to
  * our `redirectUri` after the user confirms/denies authorization.
  * If any of these parameters are missing, the OAuth attempt is considered
  * to have failed (usually this is due to the user hitting the 'cancel' button)
  *
  * @property {array} responseParams
  */
  responseParams: requiredProperty(),

  redirectUri: function(){
    return currentUrl();
  }.property(),

  buildQueryString: function(){
    var requiredParams = this.get('requiredUrlParams'),
        optionalParams = this.get('optionalUrlParams');

    var qs = new QueryString(this, requiredParams, optionalParams);
    return qs.toString();
  },

  buildUrl: function(){
    var base = this.get('baseUrl'),
        qs   = this.buildQueryString();

    return [base, qs].join('?');
  },

  /**
   * @method open
   * @return {Promise<object>} If the authorization attempt is a success,
   * the promise will resolve an object containing the following keys:
   *   - authorizationCode: The `code` from the 3rd-party provider
   *   - provider: The name of the provider (i.e., google-oauth2)
   *   - redirectUri: The redirect uri (some server-side exchange flows require this)
   * If there was an error or the user either canceled the authorization or
   * closed the popup window, the promise rejects.
   */
  open: function(){
    var name        = this.get('name'),
        url         = this.buildUrl(),
        redirectUri = this.get('redirectUri'),
        responseParams = this.get('responseParams'),
        responseType = this.get('responseType');

    return this.get('popup').open(url, responseParams).then(function(authData){
      var missingResponseParams = [];

      responseParams.forEach(function(param){
        if (authData[param] === undefined) {
          missingResponseParams.push(param);
        }
      });

      if (missingResponseParams.length){
        throw "The response from the provider is missing " +
              "these required response params: " + responseParams.join(', ');
      }

      return {
        authorizationCode: authData[responseType],
        provider: name,
        redirectUri: redirectUri
      };
    });
  }
});

export default Oauth2;
<commit_msg>make clientId configurable too<commit_after>import Provider from 'torii/providers/base';
import {configurable} from 'torii/configuration';
import QueryString from 'torii/lib/query-string';
import requiredProperty from 'torii/lib/required-property';

function currentUrl(){
  return [window.location.protocol,
          "//",
          window.location.host,
          window.location.pathname].join('');
}

/**
 * Implements authorization against an OAuth2 API
 * using the OAuth2 authorization flow in a popup window.
 *
 * Subclasses should extend this class and define the following properties:
 *   - requiredUrlParams: If there are additional required params
 *   - optionalUrlParams: If there are additional optional params
 *   - name: The name used in the configuration `providers` key
 *   - baseUrl: The base url for OAuth2 code-based flow at the 3rd-party
 *
 *   If there are any additional required or optional url params,
 *   include default values for them (if appropriate).
 *
 * @class Oauth2Provider
 */
var Oauth2 = Provider.extend({
  concatenatedProperties: ['requiredUrlParams','optionalUrlParams'],

  /**
   * The parameters that must be included as query params in the 3rd-party provider's url that we build.
   * These properties are in the format that should be in the URL (i.e.,
   * usually underscored), but they are looked up as camelCased properties
   * on the instance of this provider. For example, if the 'client_id' is
   * a required url param, when building the URL we look up the value of
   * the 'clientId' (camel-cased) property and put it in the URL as
   * 'client_id=' + this.get('clientId')
   * Subclasses can add additional required url params.
   *
   * @property {array} requiredUrlParams
   */
  requiredUrlParams: ['response_type', 'client_id', 'redirect_uri'],

  /**
   * Parameters that may be included in the 3rd-party provider's url that we build.
   * Subclasses can add additional optional url params.
   *
   * @property {array} optionalUrlParams
   */
  optionalUrlParams: ['scope'],

  /**
   * The base url for the 3rd-party provider's OAuth2 flow (example: 'https://github.com/login/oauth/authorize')
   *
   * @property {string} baseUrl
   */
  baseUrl:      requiredProperty(),

  /**
   * The apiKey (sometimes called app id) that identifies the registered application at the 3rd-party provider
   *
   * @property {string} apiKey
   */
  apiKey:       configurable('apiKey'),

  scope:        configurable('scope', null),
  clientId:     configurable('clientId', function () { return this.get('apiKey'); }),

  /**
   * The oauth response type we expect from the third party provider. Hardcoded to 'code' for oauth2-code flows
   * @property {string} responseType
   */
  responseType: 'code',

 /**
  * List of parameters that we expect
  * to see in the query params that the 3rd-party provider appends to
  * our `redirectUri` after the user confirms/denies authorization.
  * If any of these parameters are missing, the OAuth attempt is considered
  * to have failed (usually this is due to the user hitting the 'cancel' button)
  *
  * @property {array} responseParams
  */
  responseParams: requiredProperty(),

  redirectUri: function(){
    return currentUrl();
  }.property(),

  buildQueryString: function(){
    var requiredParams = this.get('requiredUrlParams'),
        optionalParams = this.get('optionalUrlParams');

    var qs = new QueryString(this, requiredParams, optionalParams);
    return qs.toString();
  },

  buildUrl: function(){
    var base = this.get('baseUrl'),
        qs   = this.buildQueryString();

    return [base, qs].join('?');
  },

  /**
   * @method open
   * @return {Promise<object>} If the authorization attempt is a success,
   * the promise will resolve an object containing the following keys:
   *   - authorizationCode: The `code` from the 3rd-party provider
   *   - provider: The name of the provider (i.e., google-oauth2)
   *   - redirectUri: The redirect uri (some server-side exchange flows require this)
   * If there was an error or the user either canceled the authorization or
   * closed the popup window, the promise rejects.
   */
  open: function(){
    var name        = this.get('name'),
        url         = this.buildUrl(),
        redirectUri = this.get('redirectUri'),
        responseParams = this.get('responseParams'),
        responseType = this.get('responseType');

    return this.get('popup').open(url, responseParams).then(function(authData){
      var missingResponseParams = [];

      responseParams.forEach(function(param){
        if (authData[param] === undefined) {
          missingResponseParams.push(param);
        }
      });

      if (missingResponseParams.length){
        throw "The response from the provider is missing " +
              "these required response params: " + responseParams.join(', ');
      }

      return {
        authorizationCode: authData[responseType],
        provider: name,
        redirectUri: redirectUri
      };
    });
  }
});

export default Oauth2;
<|endoftext|>


<commit_before>import EventEmitter from 'events';
import {Event} from 'foxman-api';
import {firstUpperCase, error} from '../util/util';

let app;
class Application {
	constructor() {
		this.eventEmitter = new EventEmitter();
		this.beforeEventMap = {};
		this.current = 0;
		this.states = ['ready', 'create', 'startServer', 'serverBuild'];
	}

	addBeforeEvent (eventName, pluginId, fn){
		if(!app.beforeEventMap[eventName]) app.beforeEventMap[eventName] = {};
		app.beforeEventMap[eventName][pluginId] = fn;
	}

	removeBeforeEvent (eventName, pluginId){
		try{
				delete app.beforeEventMap[eventName][pluginId];
		}catch(err){
			app.beforeEventMap[eventName][pluginId] = null;
		}
	}

	use(Plugins, options) {
		let plugin;
		if(Array.isArray(Plugins) && !options){
			Plugins.forEach((Plugin)=>{
				if(Array.isArray(Plugin)){
					Plugin = Object.assign({},{
						class: Plugin[0],
						options: Plugin[1]
					})
				}
				app.use(Plugin.class, Plugin.options);
			});
			return;
		}

		plugin = new Plugins(options);
		Object.assign(plugin, {
			on: app.on,
			emit: app.emit,
			before: app.before,
			complete: app.complete
		});

		plugin.app = app;
		plugin.id = app.current++;
		plugin.bindLifeCircle = () => {
			app.states.forEach( (item, idx) => {
				const upperEventName = firstUpperCase(item);

				if( (idx!==0) && plugin['before' + upperEventName]){
					plugin.before(item, plugin[`before${upperEventName}`].bind(plugin));
				}
				if(plugin['on' + upperEventName]){
					plugin.on(item, plugin[`on${upperEventName}`].bind(plugin));
				}
			});
		}
		plugin.bindLifeCircle();
	}

	run(...args) {
		setTimeout(()=>{
			app.setState(app.states[0]);
		}, 1000);
	}

	on(msg, fn){
		app.eventEmitter.on(msg, fn);
	}

	before(state, fn){
		if(!(~app.states.indexOf(state))) return;
		// console.log(state);

		const prevState = app.states[app.states.indexOf(state)-1];
		app.eventEmitter.on(prevState, fn);
		app.addBeforeEvent(state, this.id, fn);
	}

	emit(msg ,event){
		app.eventEmitter.emit( msg, event);
	}

	complete(event){
		const nextState = app.states[app.states.indexOf(app.state)+1];

		if(!nextState) {
			error('can`t complete ,because no more state');
			return;
		}
		app.removeBeforeEvent(nextState, this.id);
		app.afterComplete(nextState);
	}

	afterComplete(msg){
		const len = Object.keys(app.beforeEventMap[msg]||{}).length;
		if(len <= 0){
			app.nextState();
		}
	}

	nextState(){
		const nextState = app.states[app.states.indexOf(app.state)+1];
		app.setState(nextState);
	}

	setState(state){
		app.state = state;
		app.emit(state, new Event(state,'app'));
	}
}

export default function () {
	if(!app){
		app = new Application();
	}
	return app;
}
<commit_msg>misc: index.js<commit_after>import EventEmitter from 'events';
import {Event} from 'foxman-api';
import {firstUpperCase, error} from '../util/util';

let app;
class Application {
	constructor() {
		this.eventEmitter = new EventEmitter();
		this.beforeEventMap = {};
		this.current = 0;
		this.states = ['ready', 'create', 'startServer', 'serverBuild'];
	}

	addBeforeEvent (eventName, pluginId, fn){
		if(!app.beforeEventMap[eventName]) app.beforeEventMap[eventName] = {};
		app.beforeEventMap[eventName][pluginId] = fn;
	}

	removeBeforeEvent (eventName, pluginId){
		try{
				delete app.beforeEventMap[eventName][pluginId];
		}catch(err){
			app.beforeEventMap[eventName][pluginId] = null;
		}
	}

	use(Plugins, options) {
		let plugin;
		if(Array.isArray(Plugins) && !options){
			Plugins.forEach((Plugin)=>{
				if(Array.isArray(Plugin)){
					Plugin = Object.assign({},{
						class: Plugin[0],
						options: Plugin[1]
					})
				}
				app.use(Plugin.class, Plugin.options);
			});
			return;
		}

		plugin = new Plugins(options);
		Object.assign(plugin, {
			on: app.on,
			emit: app.emit,
			before: app.before,
			complete: app.complete
		});

		plugin.app = app;
		plugin.id = app.current++;
		plugin.bindLifeCircle = () => {
			app.states.forEach( (item, idx) => {
				const upperEventName = firstUpperCase(item);

				if( (idx!==0) && plugin['before' + upperEventName]){
					plugin.before(item, plugin[`before${upperEventName}`].bind(plugin));
				}
				if(plugin['on' + upperEventName]){
					plugin.on(item, plugin[`on${upperEventName}`].bind(plugin));
				}
			});
		}
		plugin.bindLifeCircle();
	}

	run(...args) {
		setTimeout(()=>{
			app.setState(app.states[0]);
		}, 1000);
	}

	on(msg, fn){
		app.eventEmitter.on(msg, fn);
	}

	before(state, fn){
		if(!(~app.states.indexOf(state))) return;

		const prevState = app.states[app.states.indexOf(state)-1];
		app.eventEmitter.on(prevState, fn);
		app.addBeforeEvent(state, this.id, fn);
	}

	emit(msg ,event){
		app.eventEmitter.emit( msg, event);
	}

	complete(event){
		const nextState = app.states[app.states.indexOf(app.state)+1];

		if(!nextState) {
			error('can`t complete ,because no more state');
			return;
		}
		app.removeBeforeEvent(nextState, this.id);
		app.afterComplete(nextState);
	}

	afterComplete(msg){
		const len = Object.keys(app.beforeEventMap[msg]||{}).length;
		if(len <= 0){
			app.nextState();
		}
	}

	nextState(){
		const nextState = app.states[app.states.indexOf(app.state)+1];
		app.setState(nextState);
	}

	setState(state){
		app.state = state;
		app.emit(state, new Event(state,'app'));
	}
}

export default function () {
	if(!app){
		app = new Application();
	}
	return app;
}
<|endoftext|>


<commit_before>exports.config = {
  seleniumServerJar: '../../node_modules/gulp-protractor/node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar',

  seleniumArgs: ['-Dwebdriver.ie.driver=./node_modules/gulp-protractor/node_modules/protractor/selenium/IEDriverServer.exe'],

  multiCapabilities: [
    {
      'platform': 'WINDOWS',
      'browserName': 'chrome',
      'name': 'ng-daterangepicker E2E Tests on chrome in WINDOWS',
      'tunnel-identifier' : process.env.TRAVIS_JOB_NUMBER
    },
    {
      'platform': 'WINDOWS',
      'browserName': 'internet explorer',
      'version': '11',
      'name': 'ng-daterangepicker E2E Tests on ie in WINDOWS',
      'tunnel-identifier' : process.env.TRAVIS_JOB_NUMBER
    }
  ],

  exclude: ['./spec/use-browser-default.js'],

  sauceUser: process.env.SAUCE_USERNAME,
  sauceKey: process.env.SAUCE_ACCESS_KEY,

  framework: 'jasmine',

  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000
  }
};
<commit_msg>Add window's version<commit_after>exports.config = {
  seleniumServerJar: '../../node_modules/gulp-protractor/node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar',

  seleniumArgs: ['-Dwebdriver.ie.driver=./node_modules/gulp-protractor/node_modules/protractor/selenium/IEDriverServer.exe'],

  multiCapabilities: [
    {
      'platform': 'WINDOWS',
      'browserName': 'chrome',
      'name': 'ng-daterangepicker E2E Tests on chrome in WINDOWS',
      'tunnel-identifier' : process.env.TRAVIS_JOB_NUMBER
    },
    {
      'os': 'Windows 7',
      'platform': 'WINDOWS',
      'browserName': 'internet explorer',
      'version': '11',
      'name': 'ng-daterangepicker E2E Tests on ie in WINDOWS',
      'tunnel-identifier' : process.env.TRAVIS_JOB_NUMBER
    }
  ],

  exclude: ['./spec/use-browser-default.js'],

  sauceUser: process.env.SAUCE_USERNAME,
  sauceKey: process.env.SAUCE_ACCESS_KEY,

  framework: 'jasmine',

  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000
  }
};
<|endoftext|>


<commit_before>angular.module('blueRidgeApp')
.controller('SubscriptionCtrl',function($scope,$location,Auth,Restangular,PaymentHelpers){
    Restangular.one('services','cashier').get().then(function(cashier){
        $scope.cashier=cashier;
    });

    $scope.alerts = [];

    $scope.closeAlert = function(index) {
        $scope.alerts.splice(index, 1);
    };

    $scope.open=function(){
        $scope.shouldBeOpen = true;
        Stripe.setPublishableKey($scope.cashier.key);

    };

    $scope.makePayment = function(card){

        if(typeof card != 'undefined'){
            var expiry = PaymentHelpers.cardExpiryVal(card.expiry);

            var subscriber = {
                name:card.name,
                number:card.number,
                exp_month:expiry.month,
                exp_year:expiry.year
            }
            Stripe.card.createToken(subscriber, $scope.subscribe);

        }else{
            $scope.alerts.push({ type: 'error', msg: 'Oh snap! Double check on you payment info and try submitting again.' });
        }

    };

    $scope.subscribe = function(status, response){
        if (response.error) {
            $scope.alerts.push({ type: 'error', msg: 'Oh my! '+response.error.message });
        } else {

            console.log(response);
        }
    };
});<commit_msg>close bottom<commit_after>angular.module('blueRidgeApp')
.controller('SubscriptionCtrl',function($scope,$location,Auth,Restangular,PaymentHelpers){
    Restangular.one('services','cashier').get().then(function(cashier){
        $scope.cashier=cashier;
    });

    $scope.alerts = [];

    $scope.closeAlert = function(index) {
        $scope.alerts.splice(index, 1);
    };

     $scope.close=function(){
        $scope.shouldBeOpen = false;
    };

    $scope.open=function(){
        $scope.shouldBeOpen = true;
        Stripe.setPublishableKey($scope.cashier.key);

    };

    $scope.makePayment = function(card){

        if(typeof card != 'undefined'){
            var expiry = PaymentHelpers.cardExpiryVal(card.expiry);

            var subscriber = {
                name:card.name,
                number:card.number,
                exp_month:expiry.month,
                exp_year:expiry.year
            }
            Stripe.card.createToken(subscriber, $scope.subscribe);

        }else{
            $scope.alerts.push({ type: 'error', msg: 'Oh snap! Double check your card details and try submitting again.' });
        }

    };

    $scope.subscribe = function(status, response){
        if (response.error) {
            $scope.alerts.push({ type: 'error', msg: 'Oh my! '+response.error.message });
        } else {

            console.log(response);
        }
    };
});<|endoftext|>


<commit_before>var Lazy = require("./lazy.node.js");
var _    = require("./site/lib/lodash.js");

function random(min, max) {
  return Math.floor(min + (Math.random() * (max + 1 - min)));
}

function randomChar() {
  return "ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(random(0, 26));
}

function randomString() {
  var length = random(10, 20);

  var str = "";
  while (str.length < length) {
    str += randomChar();
  }
  return str;
}

var gibberish = Lazy.generate(randomString).take(100000);
var json      = JSON.stringify(gibberish.toArray());

console.log("Generated " + json.length + "-character JSON string.");

console.log("Parsing w/ JSON.parse...");
var started    = new Date().getTime();
var jsonResult = _.take(JSON.parse(json), 10);
_.each(jsonResult, function(token) {});
var elapsed    = new Date().getTime() - started;
console.log("Finished in " + elapsed + "ms.");

console.log("Parsing w/ Lazy.parse...");
started        = new Date().getTime();
var lazyResult = Lazy.parse(json).take(10);
lazyResult.each(function(token) {});
elapsed        = new Date().getTime() - started;
console.log("Finished in " + elapsed + "ms.");

console.log("First 10 results (just to check):");
lazyResult.each(function(word, i) {
  console.log(i + ": " + word + " (Lazy), " + jsonResult[i] + " (JSON)");
});
<commit_msg>removing the ugly parse_test.js<commit_after><|endoftext|>


<commit_before>var searchBox = $("#search-input-wrap");
var TITLE = ['/get_started/', '/tutorials/', '/gluon/' , '/api/', '/community/contribute.html', ];
var DOC_TITLE = ['/faq/', '/architecture/', '/model_zoo/'];
var APISubmenu, versionSubmenu, docSubmenu;
$("#burgerMenu").children().each(function () {
    if($(this).children().first().html() == 'API') APISubmenu = $(this).clone();
    if($(this).children().first().html().startsWith('Versions')) versionSubmenu = $(this).clone();
    if($(this).children().first().html() == 'Docs') docSubmenu= $(this).clone();
});

function navbar() {
    var leftOffset = 40;
    var plusMenuList = [];
    var plusIconLeft =$("#search-input-wrap").offset().left - leftOffset;
    var isCovered = false;
    $("#main-nav").children().each(function () {
        var rightPos;
        if($(this).is(':hidden')) {
            $(this).show();
            rightPos = $(this).offset().left + $(this).width();
            $(this).hide;
        }
        else rightPos = $(this).offset().left + $(this).width();

        if(isCovered) {
            plusMenuList.push($(this).clone());
            $(this).hide();
        }
        else if(rightPos > plusIconLeft) {
            isCovered = true;
            $(".plusIcon").first().show();
            plusMenuList.push($(this).clone());
            $(this).hide();
        }
        else $(this).show();
    });

    if(plusMenuList.length == 0) {
        $(".plusIcon").first().hide();
        return;
    }
    $("#plusMenu").empty();
    for (var i = 0; i < plusMenuList.length; ++i) {
        if(plusMenuList[i].attr('id') == 'dropdown-menu-position-anchor') {
            $("#plusMenu").append(APISubmenu);
        }
        else if(plusMenuList[i].attr('id') == 'dropdown-menu-position-anchor-version') {
            $("#plusMenu").append(versionSubmenu);
        }
        else if(plusMenuList[i].attr('id') == 'dropdown-menu-position-anchor-docs') {
            $("#plusMenu").append(docSubmenu);
        }
        else {
            $("#plusMenu").append("

");
            plusMenuList[i].removeClass("main-nav-link");
            $("#plusMenu").children().last().append(plusMenuList[i]);
        }
    }
};

/*Show bottom border of current tab*/
function showTab() {
    var url = window.location.href;
    if(url.indexOf('/get_started/why_mxnet') != -1) return;
    for(var i = 0; i < TITLE.length; ++i) {
        if(url.indexOf(TITLE[i]) != -1) {
            var tab = $($('#main-nav').children().eq(i));
            if(!tab.is('a')) tab = tab.find('a').first();
            tab.css('border-bottom', '3px solid');
            return;
        }
    }
     for(var i = 0; i < DOC_TITLE.length; ++i) {
        if(url.indexOf(DOC_TITLE[i]) != -1) {
            var tab = $($('#main-nav').children().eq(4));
            if(!tab.is('a')) tab = tab.find('a').first();
            tab.css('border-bottom', '3px solid');
        }
     }
}

$(document).ready(function () {
    navbar();
    showTab();
    $(window).resize(function () {
        navbar();
        if($("body").prop("clientWidth") < 1000 || $('div.sphinxsidebar').css('visibility') == 'hidden') $('div.content').css('width', '100%');
        else $('div.content').css('width', 'calc(100% - 300px)');
    });
});<commit_msg>Fix active tab on website (#9757)<commit_after>var searchBox = $("#search-input-wrap");
var TITLE = ['/install/', '/gluon/' , '/api/', '/docs/', '/github/', '/community/', ];
var DOC_TITLE = ['/faq/', '/tutorials/', '/architecture/', '/model_zoo/'];
var APISubmenu, versionSubmenu, docSubmenu;
$("#burgerMenu").children().each(function () {
    if($(this).children().first().html() == 'API') APISubmenu = $(this).clone();
    if($(this).children().first().html().startsWith('Versions')) versionSubmenu = $(this).clone();
    if($(this).children().first().html() == 'Docs') docSubmenu= $(this).clone();
});

function navbar() {
    var leftOffset = 40;
    var plusMenuList = [];
    var plusIconLeft =$("#search-input-wrap").offset().left - leftOffset;
    var isCovered = false;
    $("#main-nav").children().each(function () {
        var rightPos;
        if($(this).is(':hidden')) {
            $(this).show();
            rightPos = $(this).offset().left + $(this).width();
            $(this).hide;
        }
        else rightPos = $(this).offset().left + $(this).width();

        if(isCovered) {
            plusMenuList.push($(this).clone());
            $(this).hide();
        }
        else if(rightPos > plusIconLeft) {
            isCovered = true;
            $(".plusIcon").first().show();
            plusMenuList.push($(this).clone());
            $(this).hide();
        }
        else $(this).show();
    });

    if(plusMenuList.length == 0) {
        $(".plusIcon").first().hide();
        return;
    }
    $("#plusMenu").empty();
    for (var i = 0; i < plusMenuList.length; ++i) {
        if(plusMenuList[i].attr('id') == 'dropdown-menu-position-anchor') {
            $("#plusMenu").append(APISubmenu);
        }
        else if(plusMenuList[i].attr('id') == 'dropdown-menu-position-anchor-version') {
            $("#plusMenu").append(versionSubmenu);
        }
        else if(plusMenuList[i].attr('id') == 'dropdown-menu-position-anchor-docs') {
            $("#plusMenu").append(docSubmenu);
        }
        else {
            $("#plusMenu").append("

");
            plusMenuList[i].removeClass("main-nav-link");
            $("#plusMenu").children().last().append(plusMenuList[i]);
        }
    }
};

/*Show bottom border of current tab*/
function showTab() {
    var url = window.location.href;
    if(url.indexOf('/get_started/why_mxnet') != -1) return;
    for(var i = 0; i < TITLE.length; ++i) {
        if(url.indexOf(TITLE[i]) != -1) {
            var tab = $($('#main-nav').children().eq(i));
            if(!tab.is('a')) tab = tab.find('a').first();
            tab.css('border-bottom', '3px solid');
            return;
        }
    }
     for(var i = 0; i < DOC_TITLE.length; ++i) {
        if(url.indexOf(DOC_TITLE[i]) != -1) {
            var tab = $($('#main-nav').children().eq(3));
            if(!tab.is('a')) tab = tab.find('a').first();
            tab.css('border-bottom', '3px solid');
        }
     }
}

$(document).ready(function () {
    navbar();
    showTab();
    $(window).resize(function () {
        navbar();
        if($("body").prop("clientWidth") < 1000 || $('div.sphinxsidebar').css('visibility') == 'hidden') $('div.content').css('width', '100%');
        else $('div.content').css('width', 'calc(100% - 300px)');
    });
});<|endoftext|>


<commit_before>import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import { render } from 'enzyme';
import ConfigProvider from '..';
import Alert from '../../alert';
import Anchor from '../../anchor';
import AutoComplete from '../../auto-complete';
import Avatar from '../../avatar';
import BackTop from '../../back-top';
import Badge from '../../badge';
import Breadcrumb from '../../breadcrumb';
import Button from '../../button';
import Calendar from '../../calendar';
import Card from '../../card';
import Carousel from '../../carousel';
import Cascader from '../../cascader';
import Checkbox from '../../checkbox';
import Collapse from '../../collapse';
import Comment from '../../comment';
import DatePicker from '../../date-picker';
import Divider from '../../divider';
import Drawer from '../../drawer';
import Dropdown from '../../dropdown';
import Empty from '../../empty';
import Form from '../../form';
import { Col, Row } from '../../grid';
import Input from '../../input';
import InputNumber from '../../input-number';
import Layout from '../../layout';
import List from '../../list';
import Menu from '../../menu';
import Modal from '../../modal';
import PageHeader from '../../page-header';
import Pagination from '../../pagination';
import Popconfirm from '../../popconfirm';
import Popover from '../../popover';
import Progress from '../../progress';
import Radio from '../../radio';
import Rate from '../../rate';
import Select from '../../select';
import Skeleton from '../../skeleton';
import Slider from '../../slider';
// eslint-disable-next-line import/no-named-as-default
import Spin from '../../spin';
import Statistic from '../../statistic';
import Steps from '../../steps';
import Switch from '../../switch';
import Table from '../../table';
import Tabs from '../../tabs';
import Tag from '../../tag';
import TimePicker from '../../time-picker';
import Timeline from '../../timeline';
import Tooltip from '../../tooltip';
import Transfer from '../../transfer';
import Tree from '../../tree';
import TreeSelect from '../../tree-select';
import Upload from '../../upload';

dayjs.extend(customParseFormat);
jest.mock('rc-util/lib/Portal');

describe('ConfigProvider', () => {
  describe('components', () => {
    function testPair(name, renderComponent) {
      describe(`${name}`, () => {
        // normal
        it('normal', () => {
          expect(render(renderComponent({}))).toMatchSnapshot();
        });

        // prefixCls
        it('prefixCls', () => {
          expect(render(renderComponent({ prefixCls: `prefix-${name}` }))).toMatchSnapshot();
        });

        // configProvider
        it('configProvider', () => {
          expect(
            render(
              <ConfigProvider pageHeader={{ ghost: false }} prefixCls="config">
                {renderComponent({})}
              </ConfigProvider>,
            ),
          ).toMatchSnapshot();
        });

        it('configProvider componentSize large', () => {
          expect(
            render(
              <ConfigProvider componentSize="large" prefixCls="config">
                {renderComponent({})}
              </ConfigProvider>,
            ),
          ).toMatchSnapshot();
        });

        it('configProvider componentSize middle', () => {
          expect(
            render(
              <ConfigProvider componentSize="middle" prefixCls="config">
                {renderComponent({})}
              </ConfigProvider>,
            ),
          ).toMatchSnapshot();
        });

        it('configProvider componentDisabled', () => {
          expect(
            render(
              <ConfigProvider componentDisabled prefixCls="config">
                {renderComponent({})}
              </ConfigProvider>,
            ),
          ).toMatchSnapshot();
        });

        it('configProvider virtual and dropdownMatchSelectWidth', () => {
          expect(
            render(
              <ConfigProvider virtual={false} dropdownMatchSelectWidth={false}>
                {renderComponent({})}
              </ConfigProvider>,
            ),
          ).toMatchSnapshot();
        });
      });
    }

    // Alert
    testPair('Alert', props => (
      <Alert {...props} message="Bamboo is Little Light" type="success" />
    ));

    // Anchor
    testPair('Anchor', props => (
      <Anchor {...props}>
        <Anchor.Link {...props} href="#bamboo" title="Little Light" />
      </Anchor>
    ));

    // AutoComplete
    testPair('AutoComplete', props => <AutoComplete {...props} />);

    // Avatar
    testPair('Avatar', props => <Avatar {...props} />);

    // BackTop
    testPair('BackTop', props => <BackTop visible {...props} />);

    // Badge
    testPair('Badge', props => {
      const newProps = {
        ...props,
      };

      // Hook for additional `scrollNumberPrefixCls` prop
      if (props.prefixCls) {
        newProps.scrollNumberPrefixCls = 'prefix-scroll-number';
      }

      return (

          <Badge {...newProps} count={5}>

          </Badge>

          <Badge {...newProps} dot>

          </Badge>

      );
    });

    // Breadcrumb
    testPair('Breadcrumb', props => (
      <Breadcrumb {...props}>
        <Breadcrumb.Item {...props}>Bamboo</Breadcrumb.Item>
        <Breadcrumb.Item {...props}>Light</Breadcrumb.Item>
      </Breadcrumb>
    ));

    // Button
    testPair('Button', props => (

        <Button {...props}>Bamboo</Button>
        <Button.Group {...props}>
          <Button {...props}>Little</Button>
          <Button {...props}>Light</Button>
        </Button.Group>

    ));

    // Calendar
    testPair('Calendar', props => (

        <Calendar {...props} value={dayjs('2000-09-03')} mode="month" />
        <Calendar {...props} value={dayjs('2000-09-03')} mode="year" />

    ));

    // Card
    testPair('Card', props => (
      <Card {...props}>
        <Card.Grid {...props}>
          <Card.Meta {...props} />
        </Card.Grid>
      </Card>
    ));

    // Carousel
    testPair('Carousel', props => (
      <Carousel {...props}>

Bamboo

Light

      </Carousel>
    ));

    // Cascader
    testPair('Cascader', props => <Cascader {...props} options={[]} showSearch />);

    // Checkbox
    testPair('Checkbox', props => (
      <Checkbox.Group {...props}>
        <Checkbox {...props}>Bamboo</Checkbox>
      </Checkbox.Group>
    ));

    // Collapse
    testPair('Collapse', props => (
      <Collapse {...props}>
        <Collapse.Panel header="Bamboo">

Light

        </Collapse.Panel>
      </Collapse>
    ));

    // Comment
    testPair('Comment', props => (
      <Comment {...props} content="Bamboo">
        <Comment {...props} content="Light" />
      </Comment>
    ));

    // DatePicker
    describe('DatePicker', () => {
      testPair('DatePicker', props => (

          <DatePicker {...props} />

      ));

      // RangePicker
      testPair('RangePicker', props => (

          <DatePicker.RangePicker {...props} />

      ));

      // MonthPicker
      testPair('MonthPicker', props => (

          <DatePicker.MonthPicker {...props} />

      ));

      // WeekPicker
      testPair('WeekPicker', props => (

          <DatePicker.WeekPicker {...props} />

      ));
    });

    // Empty
    testPair('Empty', props => <Empty {...props} />);

    // Divider
    testPair('Divider', props => <Divider {...props} />);

    // Drawer
    testPair('Drawer', props => <Drawer {...props} visible getContainer={false} />);

    // Dropdown
    testPair('Dropdown', props => {
      const menu = (
        <Menu {...props}>
          <Menu.Item {...props}>Bamboo</Menu.Item>
        </Menu>
      );

      return (
        <Dropdown.Button {...props} overlay={menu}>
          Light
        </Dropdown.Button>
      );
    });

    // Form
    testPair('Form', props => (
      <Form {...props}>
        <Form.Item {...props} validateStatus="error" help="Bamboo is Light">
          <Input {...props} />
        </Form.Item>
      </Form>
    ));

    // Grid
    testPair('Grid', props => {
      const rowProps = {};
      const colProps = {};
      if (props.prefixCls) {
        rowProps.prefixCls = 'prefix-row';
        colProps.prefixCls = 'prefix-col';
      }

      return (
        <Row {...rowProps}>
          <Col {...colProps} span={1} />
        </Row>
      );
    });

    // Input
    testPair('Input', props => (

        <Input.Group {...props}>
          <Input {...props} />
          <Input.Search {...props} />
        </Input.Group>
        <Input.Password {...props} />
        <Input.TextArea {...props} />

    ));

    // InputNumber
    testPair('InputNumber', props => <InputNumber {...props} />);

    // Layout
    testPair('Layout', props => {
      const siderProps = {};
      const headerProps = {};
      const contentProps = {};
      const footerProps = {};
      if (props.prefixCls) {
        siderProps.prefixCls = 'prefix-sider';
        headerProps.prefixCls = 'prefix-header';
        contentProps.prefixCls = 'prefix-content';
        footerProps.prefixCls = 'prefix-footer';
      }

      return (
        <Layout {...props}>
          <Layout.Sider {...siderProps} />
          <Layout {...props}>
            <Layout.Header {...headerProps} />
            <Layout.Content {...contentProps} />
            <Layout.Footer {...footerProps} />
          </Layout>
        </Layout>
      );
    });

    // List
    testPair('List', props => (
      <List
        {...props}
        itemLayout="horizontal"
        dataSource={['']}
        renderItem={() => (
          <List.Item {...props}>
            <List.Item.Meta
              {...props}
              avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
              title="Ant Design"
              description="Ant Design, a design language for background applications, is refined by Ant UED Team"
            />
          </List.Item>
        )}
      />
    ));

    // Menu
    testPair('Menu', props => (
      <Menu {...props} defaultOpenKeys={['bamboo']} mode="inline">
        <Menu.SubMenu {...props} key="bamboo" title="bamboo">
          <Menu.ItemGroup {...props} key="g1" title="Item 1">
            <Menu.Item {...props} key="1">
              Light
            </Menu.Item>
          </Menu.ItemGroup>
        </Menu.SubMenu>
      </Menu>
    ));

    // Modal
    testPair('Modal', props => (

        <Modal {...props} visible getContainer={false}>
          Bamboo is Little Light
        </Modal>

    ));

    // Pagination
    testPair('Pagination', props => (

        <Pagination showSizeChanger showQuickJumper {...props} />
        <Pagination size="small" showSizeChanger showQuickJumper {...props} />

    ));

    // PageHeader
    testPair('PageHeader', props => (

        <PageHeader title="pageHeader" {...props} />

    ));

    // Popconfirm
    testPair('Popconfirm', props => (

        <Popconfirm {...props} visible>
          Bamboo
        </Popconfirm>

    ));

    // Popover
    testPair('Popover', props => (

        <Popover {...props} visible>
          Light
        </Popover>

    ));

    // Progress
    testPair('Progress', props => <Progress {...props} />);

    // Radio
    testPair('Radio', props => (

        <Radio.Group {...props}>
          <Radio {...props}>Bamboo</Radio>
        </Radio.Group>
        <Radio.Group {...props}>
          <Radio.Button {...props}>Light</Radio.Button>
        </Radio.Group>

    ));

    // Rate
    testPair('Rate', props => <Rate {...props} />);

    // Select
    testPair('Select', props => (
      <Select {...props} open>
        <Select.OptGroup key="grp">
          <Select.Option key="Bamboo">Light</Select.Option>
        </Select.OptGroup>
      </Select>
    ));

    // Skeleton
    testPair('Skeleton', props => <Skeleton title avatar paragraph {...props} />);

    // Slider
    testPair('Slider', props => {
      const myProps = { ...props };
      if (myProps.prefixCls) {
        myProps.tooltipPrefixCls = `${myProps.prefixCls}-tooltip`;
      }
      return <Slider tooltipVisible {...myProps} />;
    });

    // Spin
    testPair('Spin', props => <Spin {...props} />);

    // Statistic
    testPair('Statistic', props => <Statistic {...props} value={0} />);

    // Steps
    testPair('Steps', props => {
      const myProps = { ...props };
      if (props.prefixCls) {
        myProps.iconPrefix = 'prefixIcon';
      }
      return (
        <Steps {...props}>
          <Steps.Step title="Bamboo" description="Little Light" />
        </Steps>
      );
    });

    // Switch
    testPair('Switch', props => <Switch {...props} />);

    // Table
    testPair('Table', props => {
      const columns = [
        {
          title: 'Name',
          dataIndex: 'name',
          filters: [
            {
              text: 'Joe',
              value: 'Joe',
            },
            {
              text: 'Submenu',
              value: 'Submenu',
              children: [
                {
                  text: 'Green',
                  value: 'Green',
                },
              ],
            },
          ],
          filterDropdownVisible: true,
          onFilter: (value, record) => record.name.indexOf(value) === 0,
          sorter: (a, b) => a.name.length - b.name.length,
        },
      ];

      const myProps = { ...props };
      if (props.prefixCls) {
        myProps.dropdownPrefixCls = 'prefix-dropdown';
      }

      return
;
    });

    // Tabs
    testPair('Tabs', props => (
      <Tabs {...props}>
        <Tabs.TabPane tab="Bamboo" key="Light" />
      </Tabs>
    ));

    // Tags
    testPair('Tags', props => (

        <Tag {...props}>Bamboo</Tag>
        <Tag.CheckableTag {...props}>Light</Tag.CheckableTag>

    ));

    // TimePicker
    testPair('TimePicker', props => (
      <TimePicker {...props} open defaultOpenValue={dayjs('00:00:00', 'HH:mm:ss')} />
    ));

    // Timeline
    testPair('Timeline', props => (
      <Timeline {...props}>
        <Timeline.Item {...props}>Bamboo</Timeline.Item>
      </Timeline>
    ));

    // Tooltip
    testPair('Tooltip', props => (
      <Tooltip {...props} title="Bamboo" visible>
        Light
      </Tooltip>
    ));

    // Transfer
    testPair('Transfer', props => <Transfer {...props} dataSource={[]} />);

    // Tree
    testPair('Tree', props => (

        <Tree {...props}>
          <Tree.TreeNode title="bamboo" />
        </Tree>

        <Tree.DirectoryTree {...props}>
          <Tree.TreeNode title="bamboo" />
        </Tree.DirectoryTree>

    ));

    // TreeSelect
    testPair('TreeSelect', props => (
      <TreeSelect {...props} open>
        <TreeSelect.TreeNode title="bamboo" value="light" />
      </TreeSelect>
    ));

    // Upload
    testPair('Upload', props => (
      <Upload
        {...props}
        defaultFileList={[
          {
            uid: '1',
            name: 'xxx.png',
            status: 'done',
          },
        ]}
      >

      </Upload>
    ));
  });
});
<commit_msg>test: fix lint<commit_after>import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import { render } from 'enzyme';
import React from 'react';
import ConfigProvider from '..';
import Alert from '../../alert';
import Anchor from '../../anchor';
import AutoComplete from '../../auto-complete';
import Avatar from '../../avatar';
import BackTop from '../../back-top';
import Badge from '../../badge';
import Breadcrumb from '../../breadcrumb';
import Button from '../../button';
import Calendar from '../../calendar';
import Card from '../../card';
import Carousel from '../../carousel';
import Cascader from '../../cascader';
import Checkbox from '../../checkbox';
import Collapse from '../../collapse';
import Comment from '../../comment';
import DatePicker from '../../date-picker';
import Divider from '../../divider';
import Drawer from '../../drawer';
import Dropdown from '../../dropdown';
import Empty from '../../empty';
import Form from '../../form';
import { Col, Row } from '../../grid';
import Input from '../../input';
import InputNumber from '../../input-number';
import Layout from '../../layout';
import List from '../../list';
import Menu from '../../menu';
import Modal from '../../modal';
import PageHeader from '../../page-header';
import Pagination from '../../pagination';
import Popconfirm from '../../popconfirm';
import Popover from '../../popover';
import Progress from '../../progress';
import Radio from '../../radio';
import Rate from '../../rate';
import Select from '../../select';
import Skeleton from '../../skeleton';
import Slider from '../../slider';
// eslint-disable-next-line import/no-named-as-default
import Spin from '../../spin';
import Statistic from '../../statistic';
import Steps from '../../steps';
import Switch from '../../switch';
import Table from '../../table';
import Tabs from '../../tabs';
import Tag from '../../tag';
import TimePicker from '../../time-picker';
import Timeline from '../../timeline';
import Tooltip from '../../tooltip';
import Transfer from '../../transfer';
import Tree from '../../tree';
import TreeSelect from '../../tree-select';
import Upload from '../../upload';

dayjs.extend(customParseFormat);
jest.mock('rc-util/lib/Portal');

describe('ConfigProvider', () => {
  describe('components', () => {
    function testPair(name, renderComponent) {
      describe(`${name}`, () => {
        // normal
        it('normal', () => {
          expect(render(renderComponent({}))).toMatchSnapshot();
        });

        // prefixCls
        it('prefixCls', () => {
          expect(render(renderComponent({ prefixCls: `prefix-${name}` }))).toMatchSnapshot();
        });

        // configProvider
        it('configProvider', () => {
          expect(
            render(
              <ConfigProvider pageHeader={{ ghost: false }} prefixCls="config">
                {renderComponent({})}
              </ConfigProvider>,
            ),
          ).toMatchSnapshot();
        });

        it('configProvider componentSize large', () => {
          expect(
            render(
              <ConfigProvider componentSize="large" prefixCls="config">
                {renderComponent({})}
              </ConfigProvider>,
            ),
          ).toMatchSnapshot();
        });

        it('configProvider componentSize middle', () => {
          expect(
            render(
              <ConfigProvider componentSize="middle" prefixCls="config">
                {renderComponent({})}
              </ConfigProvider>,
            ),
          ).toMatchSnapshot();
        });

        it('configProvider componentDisabled', () => {
          expect(
            render(
              <ConfigProvider componentDisabled prefixCls="config">
                {renderComponent({})}
              </ConfigProvider>,
            ),
          ).toMatchSnapshot();
        });

        it('configProvider virtual and dropdownMatchSelectWidth', () => {
          expect(
            render(
              <ConfigProvider virtual={false} dropdownMatchSelectWidth={false}>
                {renderComponent({})}
              </ConfigProvider>,
            ),
          ).toMatchSnapshot();
        });
      });
    }

    // Alert
    testPair('Alert', props => (
      <Alert {...props} message="Bamboo is Little Light" type="success" />
    ));

    // Anchor
    testPair('Anchor', props => (
      <Anchor {...props}>
        <Anchor.Link {...props} href="#bamboo" title="Little Light" />
      </Anchor>
    ));

    // AutoComplete
    testPair('AutoComplete', props => <AutoComplete {...props} />);

    // Avatar
    testPair('Avatar', props => <Avatar {...props} />);

    // BackTop
    testPair('BackTop', props => <BackTop visible {...props} />);

    // Badge
    testPair('Badge', props => {
      const newProps = {
        ...props,
      };

      // Hook for additional `scrollNumberPrefixCls` prop
      if (props.prefixCls) {
        newProps.scrollNumberPrefixCls = 'prefix-scroll-number';
      }

      return (

          <Badge {...newProps} count={5}>

          </Badge>

          <Badge {...newProps} dot>

          </Badge>

      );
    });

    // Breadcrumb
    testPair('Breadcrumb', props => (
      <Breadcrumb {...props}>
        <Breadcrumb.Item {...props}>Bamboo</Breadcrumb.Item>
        <Breadcrumb.Item {...props}>Light</Breadcrumb.Item>
      </Breadcrumb>
    ));

    // Button
    testPair('Button', props => (

        <Button {...props}>Bamboo</Button>
        <Button.Group {...props}>
          <Button {...props}>Little</Button>
          <Button {...props}>Light</Button>
        </Button.Group>

    ));

    // Calendar
    testPair('Calendar', props => (

        <Calendar {...props} value={dayjs('2000-09-03')} mode="month" />
        <Calendar {...props} value={dayjs('2000-09-03')} mode="year" />

    ));

    // Card
    testPair('Card', props => (
      <Card {...props}>
        <Card.Grid {...props}>
          <Card.Meta {...props} />
        </Card.Grid>
      </Card>
    ));

    // Carousel
    testPair('Carousel', props => (
      <Carousel {...props}>

Bamboo

Light

      </Carousel>
    ));

    // Cascader
    testPair('Cascader', props => <Cascader {...props} options={[]} showSearch />);

    // Checkbox
    testPair('Checkbox', props => (
      <Checkbox.Group {...props}>
        <Checkbox {...props}>Bamboo</Checkbox>
      </Checkbox.Group>
    ));

    // Collapse
    testPair('Collapse', props => (
      <Collapse {...props}>
        <Collapse.Panel header="Bamboo">

Light

        </Collapse.Panel>
      </Collapse>
    ));

    // Comment
    testPair('Comment', props => (
      <Comment {...props} content="Bamboo">
        <Comment {...props} content="Light" />
      </Comment>
    ));

    // DatePicker
    describe('DatePicker', () => {
      testPair('DatePicker', props => (

          <DatePicker {...props} />

      ));

      // RangePicker
      testPair('RangePicker', props => (

          <DatePicker.RangePicker {...props} />

      ));

      // MonthPicker
      testPair('MonthPicker', props => (

          <DatePicker.MonthPicker {...props} />

      ));

      // WeekPicker
      testPair('WeekPicker', props => (

          <DatePicker.WeekPicker {...props} />

      ));
    });

    // Empty
    testPair('Empty', props => <Empty {...props} />);

    // Divider
    testPair('Divider', props => <Divider {...props} />);

    // Drawer
    testPair('Drawer', props => <Drawer {...props} visible getContainer={false} />);

    // Dropdown
    testPair('Dropdown', props => {
      const menu = (
        <Menu {...props}>
          <Menu.Item {...props}>Bamboo</Menu.Item>
        </Menu>
      );

      return (
        <Dropdown.Button {...props} overlay={menu}>
          Light
        </Dropdown.Button>
      );
    });

    // Form
    testPair('Form', props => (
      <Form {...props}>
        <Form.Item {...props} validateStatus="error" help="Bamboo is Light">
          <Input {...props} />
        </Form.Item>
      </Form>
    ));

    // Grid
    testPair('Grid', props => {
      const rowProps = {};
      const colProps = {};
      if (props.prefixCls) {
        rowProps.prefixCls = 'prefix-row';
        colProps.prefixCls = 'prefix-col';
      }

      return (
        <Row {...rowProps}>
          <Col {...colProps} span={1} />
        </Row>
      );
    });

    // Input
    testPair('Input', props => (

        <Input.Group {...props}>
          <Input {...props} />
          <Input.Search {...props} />
        </Input.Group>
        <Input.Password {...props} />
        <Input.TextArea {...props} />

    ));

    // InputNumber
    testPair('InputNumber', props => <InputNumber {...props} />);

    // Layout
    testPair('Layout', props => {
      const siderProps = {};
      const headerProps = {};
      const contentProps = {};
      const footerProps = {};
      if (props.prefixCls) {
        siderProps.prefixCls = 'prefix-sider';
        headerProps.prefixCls = 'prefix-header';
        contentProps.prefixCls = 'prefix-content';
        footerProps.prefixCls = 'prefix-footer';
      }

      return (
        <Layout {...props}>
          <Layout.Sider {...siderProps} />
          <Layout {...props}>
            <Layout.Header {...headerProps} />
            <Layout.Content {...contentProps} />
            <Layout.Footer {...footerProps} />
          </Layout>
        </Layout>
      );
    });

    // List
    testPair('List', props => (
      <List
        {...props}
        itemLayout="horizontal"
        dataSource={['']}
        renderItem={() => (
          <List.Item {...props}>
            <List.Item.Meta
              {...props}
              avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
              title="Ant Design"
              description="Ant Design, a design language for background applications, is refined by Ant UED Team"
            />
          </List.Item>
        )}
      />
    ));

    // Menu
    testPair('Menu', props => (
      <Menu {...props} defaultOpenKeys={['bamboo']} mode="inline">
        <Menu.SubMenu {...props} key="bamboo" title="bamboo">
          <Menu.ItemGroup {...props} key="g1" title="Item 1">
            <Menu.Item {...props} key="1">
              Light
            </Menu.Item>
          </Menu.ItemGroup>
        </Menu.SubMenu>
      </Menu>
    ));

    // Modal
    testPair('Modal', props => (

        <Modal {...props} visible getContainer={false}>
          Bamboo is Little Light
        </Modal>

    ));

    // Pagination
    testPair('Pagination', props => (

        <Pagination showSizeChanger showQuickJumper {...props} />
        <Pagination size="small" showSizeChanger showQuickJumper {...props} />

    ));

    // PageHeader
    testPair('PageHeader', props => (

        <PageHeader title="pageHeader" {...props} />

    ));

    // Popconfirm
    testPair('Popconfirm', props => (

        <Popconfirm {...props} visible>
          Bamboo
        </Popconfirm>

    ));

    // Popover
    testPair('Popover', props => (

        <Popover {...props} visible>
          Light
        </Popover>

    ));

    // Progress
    testPair('Progress', props => <Progress {...props} />);

    // Radio
    testPair('Radio', props => (

        <Radio.Group {...props}>
          <Radio {...props}>Bamboo</Radio>
        </Radio.Group>
        <Radio.Group {...props}>
          <Radio.Button {...props}>Light</Radio.Button>
        </Radio.Group>

    ));

    // Rate
    testPair('Rate', props => <Rate {...props} />);

    // Select
    testPair('Select', props => (
      <Select {...props} open>
        <Select.OptGroup key="grp">
          <Select.Option key="Bamboo">Light</Select.Option>
        </Select.OptGroup>
      </Select>
    ));

    // Skeleton
    testPair('Skeleton', props => <Skeleton title avatar paragraph {...props} />);

    // Slider
    testPair('Slider', props => {
      const myProps = { ...props };
      if (myProps.prefixCls) {
        myProps.tooltipPrefixCls = `${myProps.prefixCls}-tooltip`;
      }
      return <Slider tooltipVisible {...myProps} />;
    });

    // Spin
    testPair('Spin', props => <Spin {...props} />);

    // Statistic
    testPair('Statistic', props => <Statistic {...props} value={0} />);

    // Steps
    testPair('Steps', props => {
      const myProps = { ...props };
      if (props.prefixCls) {
        myProps.iconPrefix = 'prefixIcon';
      }
      return (
        <Steps {...props}>
          <Steps.Step title="Bamboo" description="Little Light" />
        </Steps>
      );
    });

    // Switch
    testPair('Switch', props => <Switch {...props} />);

    // Table
    testPair('Table', props => {
      const columns = [
        {
          title: 'Name',
          dataIndex: 'name',
          filters: [
            {
              text: 'Joe',
              value: 'Joe',
            },
            {
              text: 'Submenu',
              value: 'Submenu',
              children: [
                {
                  text: 'Green',
                  value: 'Green',
                },
              ],
            },
          ],
          filterDropdownVisible: true,
          onFilter: (value, record) => record.name.indexOf(value) === 0,
          sorter: (a, b) => a.name.length - b.name.length,
        },
      ];

      const myProps = { ...props };
      if (props.prefixCls) {
        myProps.dropdownPrefixCls = 'prefix-dropdown';
      }

      return
;
    });

    // Tabs
    testPair('Tabs', props => (
      <Tabs {...props}>
        <Tabs.TabPane tab="Bamboo" key="Light" />
      </Tabs>
    ));

    // Tags
    testPair('Tags', props => (

        <Tag {...props}>Bamboo</Tag>
        <Tag.CheckableTag {...props}>Light</Tag.CheckableTag>

    ));

    // TimePicker
    testPair('TimePicker', props => (
      <TimePicker {...props} open defaultOpenValue={dayjs('00:00:00', 'HH:mm:ss')} />
    ));

    // Timeline
    testPair('Timeline', props => (
      <Timeline {...props}>
        <Timeline.Item {...props}>Bamboo</Timeline.Item>
      </Timeline>
    ));

    // Tooltip
    testPair('Tooltip', props => (
      <Tooltip {...props} title="Bamboo" visible>
        Light
      </Tooltip>
    ));

    // Transfer
    testPair('Transfer', props => <Transfer {...props} dataSource={[]} />);

    // Tree
    testPair('Tree', props => (

        <Tree {...props}>
          <Tree.TreeNode title="bamboo" />
        </Tree>

        <Tree.DirectoryTree {...props}>
          <Tree.TreeNode title="bamboo" />
        </Tree.DirectoryTree>

    ));

    // TreeSelect
    testPair('TreeSelect', props => (
      <TreeSelect {...props} open>
        <TreeSelect.TreeNode title="bamboo" value="light" />
      </TreeSelect>
    ));

    // Upload
    testPair('Upload', props => (
      <Upload
        {...props}
        defaultFileList={[
          {
            uid: '1',
            name: 'xxx.png',
            status: 'done',
          },
        ]}
      >

      </Upload>
    ));
  });
});
<|endoftext|>


<commit_before>module('users.timfelgentreff.experimental.assert').requires('users.timfelgentreff.babelsberg.constraintinterpreter').toRun(function() {

	JSLoader.loadJs(module('users.timfelgentreff.csp.underscore-min').uri());

	/***************************************************************
	 * Continuous asserts
	 ***************************************************************/

	// TODO: improve syntax of bbb.assert
	// TODO: multiple asserts and multiple variable interconnected
	// TODO: enable and disable AssertConstraints
	// TODO: integration with other solvers

	Error.subclass("ContinuousAssertError", {
		initialize: function ContinuousAssertError(msg) {
			if (Error.captureStackTrace) {
				Error.captureStackTrace(this, ContinuousAssertError);
			} else {
				this.stack = (new Error).stack || '';
			}
			this.message = msg;
		},
		name: "ContinuousAssertError"
	});

	Object.subclass("AssertSolver", {
		initialize: function(message) {
			this.message = message;
		},
	    isConstraintObject: function() { return true; },
	    always: function(opts, func) {
	    	//console.log("AssertSolver.always");
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new AssertSolver.Constraint(this, cobj, func));
			try {
				if(!opts.postponeEnabling) { cobj.enable(); }
			} catch(e) {
				if(e instanceof ContinuousAssertError) {
					cobj.disable();
				}
				throw e;
			}
	        return cobj;
	    },
	    constraintVariableFor: function(value, ivarname, bbbCVar) {
	    	//console.log("AssertSolver.constraintVariableFor", value, ivarname, bbbCVar);
	    	return new AssertSolver.Variable(this, value, ivarname, bbbCVar);
	    },
	    solve: function() {
	    	//console.log("AssertSolver.solve");
	    	this.check();
	    },
	    check: function() {
	    	//console.log("AssertSolver.check");
	    	if(this.constraint && this.constraint.enabled && typeof this.constraint.predicate === "function")
	    		if(!this.constraint.predicate())
	    			throw new ContinuousAssertError(this.message);
	    },
	    weight: 10
	});

	Object.subclass("AssertSolver.Variable", {
		initialize: function(solver, value, ivarname, bbbCVar) {
	    	//console.log("AssertSolver.Variable.initialize");
			this.solver = solver;
			this.__val__ = value;
		},
	    isConstraintObject: function() { return true; },
	    toFulfill: function(assertPredicate) {
	    	//console.log("AssertSolver.Variable.toFulfill", assertPredicate);
	    	this.assertPredicate = assertPredicate;
	    },
	    suggestValue: function(value) {
	    	//console.log("AssertSolver.Variable.suggestValue", value);
			var prev = this.__val__;
	    	this.__val__ = value;
			try {
				this.solver.solve();
			} catch(e) {
				// revert value in case of a violated assertion
				if(e instanceof ContinuousAssertError) {
					this.__val__ = prev;
				}
				throw e;
			}

			// re-constrain variables
			var bbbConstraint = this.solver.constraint.bbbConstraint;
			var enabled = bbbConstraint._enabled;
			bbbConstraint.initialize(bbbConstraint.predicate, bbbConstraint.solver);
			bbbConstraint.addPrimitiveConstraint(this.solver.constraint);
			if(enabled) bbbConstraint.enable();

	    	return this.__val__;
	    },
	    value: function() {
	    	return this.__val__;
	    },
	    setReadonly: function(bool) {
	    	//console.log("AssertSolver.Variable.setReadonly", bool);
	    	this.readonly = bool;
	    },
	    isReadonly: function() {
	    	//console.log("AssertSolver.Variable.isReadonly");
	        return this.readonly;
	    },
	    cnEquals: function() {
	    	//console.log("AssertSolver.Variable.cnEquals");
	        return new AssertSolver.PrimitiveConstraint(this, arguments);
	    }
	});

	Object.subclass("AssertSolver.PrimitiveConstraint", {
	    isConstraintObject: function() { return true; },
	    initialize: function(variable, args) {
	    	//console.log("AssertSolver.PrimitiveConstraint.initialize", variable, args);
			this.enabled = false;
	    	this.solver = variable.solver;
	    },
	    enable: function() {
	    	//console.log("AssertSolver.PrimitiveConstraint.enable");
			this.enabled = true;
	    },
	    disable: function() {
	    	//console.log("AssertSolver.PrimitiveConstraint.disable");
			this.enabled = false;
	    }
	});

	Object.subclass("AssertSolver.Constraint", {
	    isConstraintObject: function() { return true; },
	    initialize: function(solver, bbbConstraint, func) {
	    	//console.log("AssertSolver.Constraint.initialize");
			this.enabled = false;
	    	this.solver = solver;
	    	this.solver.constraint = this;
			this.bbbConstraint = bbbConstraint;

	    	// extract predicate from bbbConstraint
	    	this.predicate = func;/*_.chain(bbbConstraint.constraintvariables)
	    		.map(function(variable) {
	    			return variable.externalVariables(this.solver);
	    		}, this)
	    		.find(function(externalVariable) {
	    			return typeof externalVariable.assertPredicate === "function";
	    		})
	    		.value()
	    		//.assertPredicate;*/
	    },
	    enable: function() {
	    	//console.log("AssertSolver.Constraint.enable");
			this.enabled = true;
	    },
	    disable: function() {
	    	//console.log("AssertSolver.Constraint.disable");
			this.enabled = false;
	    }
	});

	Object.extend(Babelsberg.prototype, {
		assert: function(opts, func) {
			opts.solver = new AssertSolver(opts.message);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        return this.always(opts, func);
		}
	});

	/***************************************************************
	 * Triggering
	 ***************************************************************/
	AssertSolver.subclass("TriggerSolver", {
		initialize: function(callback) {
			this.callback = callback;
			this.triggeredOnce = false;
		},
	    always: function(opts, func) {
	    	//console.log("TriggerSolver.always");
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new AssertSolver.Constraint(this, cobj, func));
			if(!opts.postponeEnabling) { cobj.enable(); }
	        return cobj;
	    },
	    solve: function() {
	    	//console.log("TriggerSolver.solve", this.constraint.predicate());
	    	if(this.constraint &&
				this.constraint.enabled &&
				typeof this.constraint.predicate === "function"
			) {
	    		if(this.constraint.predicate()) {
					if(!this.triggeredOnce) {
						this.triggeredOnce = true;
						bbb.addCallback(this.callback, this.constraint.bbbConstraint, []);
					}
				} else {
					this.triggeredOnce = false;
				}
			}
	    },
	    weight: 10
	});

	Object.extend(Babelsberg.prototype, {
		trigger: function(opts, func) {
			opts.solver = new TriggerSolver(opts.callback);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        return this.always(opts, func);
		}
	});

	/***************************************************************
	 * Layer activation
	 ***************************************************************/
	AssertSolver.subclass("LayerActivationSolver", {
		initialize: function(layer) {
			this.layer = layer;
		},
	    always: function(opts, func) {
	    	//console.log("LayerActivationSolver.always");
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new AssertSolver.Constraint(this, cobj, func));
			cobj.enable();
	        return cobj;
	    },
	    solve: function() {
	    	//console.log("LayerActivationSolver.solve", this.constraint.predicate());
	    	if(this.constraint &&
				this.constraint.enabled &&
				typeof this.constraint.predicate === "function"
			) {
				var predicateFulfilled = this.constraint.predicate();
	    		if(predicateFulfilled && !this.layer.isGlobal()) {
	    			this.layer.beGlobal();
				} else  if(!predicateFulfilled && this.layer.isGlobal()) {
	    			this.layer.beNotGlobal();
				}
			}
	    },
	    weight: 10
	});

	// hotfix
	// instead of cop.GlobalLayers.removeAt(idx); just use standard conform splice method
	Object.extend(cop, {
		disableLayer: function(layer) {
			var idx = cop.GlobalLayers.indexOf(layer)
			if (idx < 0) return;
			cop.GlobalLayers.splice(idx, 1);
			cop.invalidateLayerComposition();
		},
	});

	Object.extend(Layer.prototype, {
		activeOn: function(opts, func) {
			opts.solver = new LayerActivationSolver(this);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        bbb.always(opts, func);

			return this;
		}
	});

	/***************************************************************
	 * Scoped constraints
	 ***************************************************************/
	Object.extend(Layer.prototype, {
		always: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.always(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);
		},
		assert: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.assert(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);
		},
		trigger: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.trigger(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);
		},
		_activate: function() {
			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.forEach(function(cobj) {
				cobj.enable();
			});
		},
		_deactivate: function() {
			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.forEach(function(cobj) {
				cobj.disable();
			});
		}
	});

	var copWithLayers = cop.withLayers;
	var copWithoutLayers = cop.withoutLayers;
	var copEnableLayer = cop.enableLayer;
	var copDisableLayer = cop.disableLayer;
	Object.extend(cop, {
		/* Layer Activation */
		withLayers: function withLayers(layers, func) {
			layers.forEach(function(layer) { layer._activate(); });

			try {
				return copWithLayers.apply(this, arguments);
			} finally {
				layers.forEach(function(layer) { layer._deactivate(); });
			}
		},

		withoutLayers: function withoutLayers(layers, func) {
			layers.forEach(function(layer) { layer._deactivate(); });

			try {
				return copWithoutLayers.apply(this, arguments);
			} finally {
				layers.forEach(function(layer) { layer._activate(); });
			}
		},

		/* Global Layer Activation */
		enableLayer: function(layer) {
			layer._activate();
			return copEnableLayer.apply(this, arguments);
		},

		disableLayer: function(layer) {
			layer._deactivate();
			return copDisableLayer.apply(this, arguments);
		}
	});

});
<commit_msg>refactoring to abstract ReactiveSolver<commit_after>module('users.timfelgentreff.experimental.assert').requires('users.timfelgentreff.babelsberg.constraintinterpreter').toRun(function() {

	JSLoader.loadJs(module('users.timfelgentreff.csp.underscore-min').uri());

	/***************************************************************
	 * Abstract Reactive Solver
	 ***************************************************************/

	Object.subclass("ReactiveSolver", {
	    isConstraintObject: function() { return true; },
	    constraintVariableFor: function(value, ivarname, bbbCVar) {
	    	return new ReactiveSolver.Variable(this, value, ivarname, bbbCVar);
	    },
	    weight: 10
	});

	Object.subclass("ReactiveSolver.Variable", {
	    isConstraintObject: function() { return true; },
		initialize: function(solver, value, ivarname, bbbCVar) {
			this.solver = solver;
			this.__val__ = value;
		},
	    suggestValue: function(value) {
			var prev = this.__val__;
	    	this.__val__ = value;
			try {
				this.solver.solve();
			} catch(e) {
				// revert value in case of a violated assertion
				if(e instanceof ContinuousAssertError) {
					this.__val__ = prev;
				}
				throw e;
			}

			// re-constrain variables
			var bbbConstraint = this.solver.constraint.bbbConstraint;
			var enabled = bbbConstraint._enabled;
			bbbConstraint.initialize(bbbConstraint.predicate, bbbConstraint.solver);
			bbbConstraint.addPrimitiveConstraint(this.solver.constraint);
			if(enabled) bbbConstraint.enable();

	    	return this.__val__;
	    },
	    value: function() {
	    	return this.__val__;
	    },
	    setReadonly: function(bool) {
	    	this.readonly = bool;
	    },
	    isReadonly: function() {
	        return this.readonly;
	    },
	    cnEquals: function() {
	        return new ReactiveSolver.PrimitiveConstraint(this, arguments);
	    }
	});

	Object.subclass("ReactiveSolver.PrimitiveConstraint", {
	    isConstraintObject: function() { return true; },
	    initialize: function(variable, args) {
			this.enabled = false;
	    	this.solver = variable.solver;
	    },
	    enable: function() {
			this.enabled = true;
	    },
	    disable: function() {
			this.enabled = false;
	    }
	});

	Object.subclass("ReactiveSolver.Constraint", {
	    isConstraintObject: function() { return true; },
	    initialize: function(solver, bbbConstraint, func) {
			this.enabled = false;
	    	this.solver = solver;
	    	this.solver.constraint = this;
			this.bbbConstraint = bbbConstraint;

	    	this.predicate = func;
	    },
	    enable: function() {
			this.enabled = true;
	    },
	    disable: function() {
			this.enabled = false;
	    }
	});

	/***************************************************************
	 * Continuous asserts
	 ***************************************************************/

	// TODO: integration with other solvers

	Error.subclass("ContinuousAssertError", {
		initialize: function ContinuousAssertError(msg) {
			if (Error.captureStackTrace) {
				Error.captureStackTrace(this, ContinuousAssertError);
			} else {
				this.stack = (new Error).stack || '';
			}
			this.message = msg;
		},
		name: "ContinuousAssertError"
	});

	ReactiveSolver.subclass("AssertSolver", {
		initialize: function(message) {
			this.message = message;
		},
	    always: function(opts, func) {
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new ReactiveSolver.Constraint(this, cobj, func));
			try {
				if(!opts.postponeEnabling) { cobj.enable(); }
			} catch(e) {
				if(e instanceof ContinuousAssertError) {
					cobj.disable();
				}
				throw e;
			}
	        return cobj;
	    },
	    solve: function() {
	    	if(this.constraint && this.constraint.enabled && typeof this.constraint.predicate === "function")
	    		if(!this.constraint.predicate())
	    			throw new ContinuousAssertError(this.message);
	    }
	});

	Object.extend(Babelsberg.prototype, {
		assert: function(opts, func) {
			opts.solver = new AssertSolver(opts.message);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        return this.always(opts, func);
		}
	});

	/***************************************************************
	 * Triggering
	 ***************************************************************/
	AssertSolver.subclass("TriggerSolver", {
		initialize: function(callback) {
			this.callback = callback;
			this.triggeredOnce = false;
		},
	    always: function(opts, func) {
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new ReactiveSolver.Constraint(this, cobj, func));
			if(!opts.postponeEnabling) { cobj.enable(); }
	        return cobj;
	    },
	    solve: function() {
	    	if(this.constraint &&
				this.constraint.enabled &&
				typeof this.constraint.predicate === "function"
			) {
	    		if(this.constraint.predicate()) {
					if(!this.triggeredOnce) {
						this.triggeredOnce = true;
						bbb.addCallback(this.callback, this.constraint.bbbConstraint, []);
					}
				} else {
					this.triggeredOnce = false;
				}
			}
	    },
	    weight: 10
	});

	Object.extend(Babelsberg.prototype, {
		trigger: function(opts, func) {
			opts.solver = new TriggerSolver(opts.callback);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        return this.always(opts, func);
		}
	});

	/***************************************************************
	 * Layer activation
	 ***************************************************************/
	AssertSolver.subclass("LayerActivationSolver", {
		initialize: function(layer) {
			this.layer = layer;
		},
	    always: function(opts, func) {
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new ReactiveSolver.Constraint(this, cobj, func));
			cobj.enable();
	        return cobj;
	    },
	    solve: function() {
	    	if(this.constraint &&
				this.constraint.enabled &&
				typeof this.constraint.predicate === "function"
			) {
				var predicateFulfilled = this.constraint.predicate();
	    		if(predicateFulfilled && !this.layer.isGlobal()) {
	    			this.layer.beGlobal();
				} else  if(!predicateFulfilled && this.layer.isGlobal()) {
	    			this.layer.beNotGlobal();
				}
			}
	    },
	    weight: 10
	});

	// HACK: instead of cop.GlobalLayers.removeAt(idx); just use standard conform splice method
	Object.extend(cop, {
		disableLayer: function(layer) {
			var idx = cop.GlobalLayers.indexOf(layer)
			if (idx < 0) return;
			cop.GlobalLayers.splice(idx, 1);
			cop.invalidateLayerComposition();
		},
	});

	Object.extend(Layer.prototype, {
		activeOn: function(opts, func) {
			opts.solver = new LayerActivationSolver(this);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        bbb.always(opts, func);

			return this;
		}
	});

	/***************************************************************
	 * Scoped constraints
	 ***************************************************************/
	Object.extend(Layer.prototype, {
		always: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.always(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);
		},
		assert: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.assert(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);
		},
		trigger: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.trigger(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);
		},
		_activate: function() {
			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.forEach(function(cobj) {
				cobj.enable();
			});
		},
		_deactivate: function() {
			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.forEach(function(cobj) {
				cobj.disable();
			});
		}
	});

	var copWithLayers = cop.withLayers;
	var copWithoutLayers = cop.withoutLayers;
	var copEnableLayer = cop.enableLayer;
	var copDisableLayer = cop.disableLayer;
	Object.extend(cop, {
		/* Layer Activation */
		withLayers: function withLayers(layers, func) {
			layers.forEach(function(layer) { layer._activate(); });

			try {
				return copWithLayers.apply(this, arguments);
			} finally {
				layers.forEach(function(layer) { layer._deactivate(); });
			}
		},

		withoutLayers: function withoutLayers(layers, func) {
			layers.forEach(function(layer) { layer._deactivate(); });

			try {
				return copWithoutLayers.apply(this, arguments);
			} finally {
				layers.forEach(function(layer) { layer._activate(); });
			}
		},

		/* Global Layer Activation */
		enableLayer: function(layer) {
			layer._activate();
			return copEnableLayer.apply(this, arguments);
		},

		disableLayer: function(layer) {
			layer._deactivate();
			return copDisableLayer.apply(this, arguments);
		}
	});
});
<|endoftext|>