<commit_before>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/* global require */
var LoggingEnhancer = require('../bower_components/better-logging-base/dist/logging-enhancer.min').LoggingEnhancer;

(function (logEnhancer, angular, sprintf, moment) {
	'use strict';

	angular.module('angular-logger', []).
	provider('logEnhancer', function() {
		var provider = this;

        this.datetimePattern = 'LLL'; 	// default datetime stamp pattern, overwrite in config phase
        this.datetimeLocale = window.navigator.userLanguage || window.navigator.language || 'en';
        this.prefixPattern = '%s::[%s]> '; 		    // default prefix pattern, overwrite in config phase
        this.LEVEL = logEnhancer.LEVEL;             // with these configure loglevels in config fase
        this.logLevels = {'*': this.LEVEL.TRACE}; 	// everything by everyone should be visible by default

		this.$get = function() {
			return {

                // Actually modifies $log. Without calling this in the run phase, $log remains untouched
				enhanceAngularLog : function($log) {
					$log.LEVEL = provider.LEVEL; // assign to $log, so the user can change them after config phase
					$log.logLevels = provider.logLevels; // assign to $log, so the user can change them after config phase

					$log.getInstance = function(context) {
						return {
							trace	: logEnhancer.enhanceLogging($log.$$orig$log.debug, $log.LEVEL.TRACE, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
							debug	: logEnhancer.enhanceLogging($log.$$orig$log.debug, $log.LEVEL.DEBUG, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
							log		: logEnhancer.enhanceLogging($log.$$orig$log.log,   $log.LEVEL.INFO,  context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
							info	: logEnhancer.enhanceLogging($log.$$orig$log.info,  $log.LEVEL.INFO,  context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
							warn	: logEnhancer.enhanceLogging($log.$$orig$log.warn,  $log.LEVEL.WARN,  context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
							error	: logEnhancer.enhanceLogging($log.$$orig$log.error, $log.LEVEL.ERROR, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern)
						};
					};
				}
			};
		};
	}).

	/*
		Default config and example config as well.
		Overrides default logging pattern and global logLevel
	*/
    config(['logEnhancerProvider', function (logEnhancerProvider) {
        logEnhancerProvider.datetimePattern = 'LLL';
        logEnhancerProvider.datetimeLocale = window.navigator.userLanguage || window.navigator.language || 'en';
        logEnhancerProvider.prefixPattern = '%s::[%s]> ';
        logEnhancerProvider.logLevels = {'*': logEnhancerProvider.LEVEL.TRACE};
        /*
            // example structure:
            logEnhancerProvider.logLevels = {
                'a.b.c': logEnhancerProvider.LEVEL.TRACE, // trace + debug + info + warn + error
                'a.b.d': logEnhancerProvider.LEVEL.ERROR, // error
                'a.b': logEnhancerProvider.LEVEL.DEBUG, // debug + info + warn + error
                'a': logEnhancerProvider.LEVEL.WARN, // warn + error
                '*': logEnhancerProvider.LEVEL.INFO // info + warn + error
            };
        */
    }]).

    config(["$provide", "logEnhancerProvider", function ($provide, p) {
		$provide.decorator("$log", ['$delegate', function ($delegate) {
			return {
			    // keep original methods, otherwise the enhanced functions on .getInstance() will have a double (global context) prefix
			    $$orig$log: angular.extend({}, $delegate),
    			trace	: logEnhancer.enhanceLogging($delegate.debug, p.LEVEL.TRACE, 'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
    			debug	: logEnhancer.enhanceLogging($delegate.debug, p.LEVEL.DEBUG, 'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
    			log		: logEnhancer.enhanceLogging($delegate.log,   p.LEVEL.INFO,  'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
    			info	: logEnhancer.enhanceLogging($delegate.info,  p.LEVEL.INFO,  'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
    			warn	: logEnhancer.enhanceLogging($delegate.warn,  p.LEVEL.WARN,  'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
    			error	: logEnhancer.enhanceLogging($delegate.error, p.LEVEL.ERROR, 'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern)
			};
		}]);
	}]).

    run(['$log', 'logEnhancer', function ($log, logEnhancer) {
        if (!sprintf) {
            $log.warn('sprintf.js not found: https://github.com/alexei/sprintf.js, using fixed layout pattern "%s::[%s]> "');
        }
        if (!moment) {
            $log.warn('moment.js not found: http://momentjs.com, using non-localized simple Date format');
        }
        logEnhancer.enhanceAngularLog($log);
		$log.info('logging enhancer initiated');
    }]);
}(new LoggingEnhancer(window.sprintf, window.moment), window.angular, window.sprintf, window.moment));
},{"../bower_components/better-logging-base/dist/logging-enhancer.min":2}],2:[function(require,module,exports){
!function(){"use strict";var n=function(n,e){var t=this;this.LEVEL={TRACE:4,DEBUG:3,INFO:2,WARN:1,ERROR:0,OFF:-1},this.enhanceLogging=function(o,r,i,u,l,f,a){function c(n,e,o){function r(n,e){if(n){if(void 0!==e.logLevels[n])return e.logLevels[n];if(-1!==n.indexOf("."))return r(n.substring(0,n.lastIndexOf(".")),e)}return void 0!==e.logLevels["*"]?e.logLevels["*"]:t.LEVEL.TRACE}return e>t.LEVEL.OFF&&e<=r(n,o)}function s(e,o,r,i,u){function l(e){var o="undefined"!=typeof n,r=o&&e.length>=2&&"string"==typeof e[0]&&-1!==e[0].indexOf("%");if(r)try{var i=t.countSprintfHolders(e[0]);i>0&&(e[0]=n.apply(null,e),e.splice(1,i))}catch(u){e.unshift(u)}return e}var f=d(o,r,i,u),a=l([].slice.call(e));return[f].concat([].slice.call(a))}function d(t,o,r,i){var u="";if("undefined"!=typeof e)u=e().locale(r).format(o);else{var l=new Date,f=(new Date).toTimeString().match(/^([0-9]{2}:[0-9]{2}:[0-9]{2})/)[0];u=l.getDate()+"-"+(l.getMonth()+1)+"-"+l.getFullYear()+" "+f}return"undefined"!=typeof n?n(i,u,t):u+"::["+t+"]> "}return u.logLevels=u.logLevels||[],function(){if(c(i,r,u)){var n=s(arguments,i,l,f,a);return o.apply(null,n),n}return null}},t.countSprintfHolders=function(e){function t(n){return function(){r=Math.max(r,n)}}var o=/\x25\([a-zA-Z0-9_]+\)[b-fijosuxX]/.test(e);if(o)return 1;var r=0;return n(e,t(1),t(2),t(3),t(4),t(5),t(6),t(7),t(8),t(9),t(10)),r}};if("undefined"!=typeof module)module.exports.LoggingEnhancer=n;else if("undefined"!=typeof exports)exports.LoggingEnhancer=n;else{if("undefined"==typeof window)throw new Error("unable to expose LoggingEnhancer: no module, exports object and no global window detected");window.loggingEnhancer=new n(window.sprintf,window.moment)}}();
},{}]},{},[1]);
<commit_msg>quote consistency<commit_after>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/* global require */
var LoggingEnhancer = require('../bower_components/better-logging-base/dist/logging-enhancer.min').LoggingEnhancer;

(function (logEnhancer, angular, sprintf, moment) {
	'use strict';

	angular.module('angular-logger', []).
	provider('logEnhancer', function() {
		var provider = this;

        this.datetimePattern = 'LLL'; 	// default datetime stamp pattern, overwrite in config phase
        this.datetimeLocale = window.navigator.userLanguage || window.navigator.language || 'en';
        this.prefixPattern = '%s::[%s]> '; 		    // default prefix pattern, overwrite in config phase
        this.LEVEL = logEnhancer.LEVEL;             // with these configure loglevels in config fase
        this.logLevels = {'*': this.LEVEL.TRACE}; 	// everything by everyone should be visible by default

		this.$get = function() {
			return {

                // Actually modifies $log. Without calling this in the run phase, $log remains untouched
				enhanceAngularLog : function($log) {
					$log.LEVEL = provider.LEVEL; // assign to $log, so the user can change them after config phase
					$log.logLevels = provider.logLevels; // assign to $log, so the user can change them after config phase

					$log.getInstance = function(context) {
						return {
							trace	: logEnhancer.enhanceLogging($log.$$orig$log.debug, $log.LEVEL.TRACE, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
							debug	: logEnhancer.enhanceLogging($log.$$orig$log.debug, $log.LEVEL.DEBUG, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
							log		: logEnhancer.enhanceLogging($log.$$orig$log.log,   $log.LEVEL.INFO,  context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
							info	: logEnhancer.enhanceLogging($log.$$orig$log.info,  $log.LEVEL.INFO,  context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
							warn	: logEnhancer.enhanceLogging($log.$$orig$log.warn,  $log.LEVEL.WARN,  context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern),
							error	: logEnhancer.enhanceLogging($log.$$orig$log.error, $log.LEVEL.ERROR, context, $log, provider.datetimePattern, provider.datetimeLocale, provider.prefixPattern)
						};
					};
				}
			};
		};
	}).

	/*
		Default config and example config as well.
		Overrides default logging pattern and global logLevel
	*/
    config(['logEnhancerProvider', function (logEnhancerProvider) {
        logEnhancerProvider.datetimePattern = 'LLL';
        logEnhancerProvider.datetimeLocale = window.navigator.userLanguage || window.navigator.language || 'en';
        logEnhancerProvider.prefixPattern = '%s::[%s]> ';
        logEnhancerProvider.logLevels = {'*': logEnhancerProvider.LEVEL.TRACE};
        /*
            // example structure:
            logEnhancerProvider.logLevels = {
                'a.b.c': logEnhancerProvider.LEVEL.TRACE, // trace + debug + info + warn + error
                'a.b.d': logEnhancerProvider.LEVEL.ERROR, // error
                'a.b': logEnhancerProvider.LEVEL.DEBUG, // debug + info + warn + error
                'a': logEnhancerProvider.LEVEL.WARN, // warn + error
                '*': logEnhancerProvider.LEVEL.INFO // info + warn + error
            };
        */
    }]).

    config(['$provide', 'logEnhancerProvider', function ($provide, p) {
		$provide.decorator('$log', ['$delegate', function ($delegate) {
			return {
			    // keep original methods, otherwise the enhanced functions on .getInstance() will have a double (global context) prefix
			    $$orig$log: angular.extend({}, $delegate),
    			trace	: logEnhancer.enhanceLogging($delegate.debug, p.LEVEL.TRACE, 'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
    			debug	: logEnhancer.enhanceLogging($delegate.debug, p.LEVEL.DEBUG, 'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
    			log		: logEnhancer.enhanceLogging($delegate.log,   p.LEVEL.INFO,  'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
    			info	: logEnhancer.enhanceLogging($delegate.info,  p.LEVEL.INFO,  'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
    			warn	: logEnhancer.enhanceLogging($delegate.warn,  p.LEVEL.WARN,  'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern),
    			error	: logEnhancer.enhanceLogging($delegate.error, p.LEVEL.ERROR, 'global', $delegate, p.datetimePattern, p.datetimeLocale, p.prefixPattern)
			};
		}]);
	}]).

    run(['$log', 'logEnhancer', function ($log, logEnhancer) {
        if (!sprintf) {
            $log.warn('sprintf.js not found: https://github.com/alexei/sprintf.js, using fixed layout pattern "%s::[%s]> "');
        }
        if (!moment) {
            $log.warn('moment.js not found: http://momentjs.com, using non-localized simple Date format');
        }
        logEnhancer.enhanceAngularLog($log);
		$log.info('logging enhancer initiated');
    }]);
}(new LoggingEnhancer(window.sprintf, window.moment), window.angular, window.sprintf, window.moment));

},{"../bower_components/better-logging-base/dist/logging-enhancer.min":2}],2:[function(require,module,exports){
!function(){"use strict";var n=function(n,e){var t=this;this.LEVEL={TRACE:4,DEBUG:3,INFO:2,WARN:1,ERROR:0,OFF:-1},this.enhanceLogging=function(o,r,i,u,l,f,a){function c(n,e,o){function r(n,e){if(n){if(void 0!==e.logLevels[n])return e.logLevels[n];if(-1!==n.indexOf("."))return r(n.substring(0,n.lastIndexOf(".")),e)}return void 0!==e.logLevels["*"]?e.logLevels["*"]:t.LEVEL.TRACE}return e>t.LEVEL.OFF&&e<=r(n,o)}function s(e,o,r,i,u){function l(e){var o="undefined"!=typeof n,r=o&&e.length>=2&&"string"==typeof e[0]&&-1!==e[0].indexOf("%");if(r)try{var i=t.countSprintfHolders(e[0]);i>0&&(e[0]=n.apply(null,e),e.splice(1,i))}catch(u){e.unshift(u)}return e}var f=d(o,r,i,u),a=l([].slice.call(e));return[f].concat([].slice.call(a))}function d(t,o,r,i){var u="";if("undefined"!=typeof e)u=e().locale(r).format(o);else{var l=new Date,f=(new Date).toTimeString().match(/^([0-9]{2}:[0-9]{2}:[0-9]{2})/)[0];u=l.getDate()+"-"+(l.getMonth()+1)+"-"+l.getFullYear()+" "+f}return"undefined"!=typeof n?n(i,u,t):u+"::["+t+"]> "}return u.logLevels=u.logLevels||[],function(){if(c(i,r,u)){var n=s(arguments,i,l,f,a);return o.apply(null,n),n}return null}},t.countSprintfHolders=function(e){function t(n){return function(){r=Math.max(r,n)}}var o=/\x25\([a-zA-Z0-9_]+\)[b-fijosuxX]/.test(e);if(o)return 1;var r=0;return n(e,t(1),t(2),t(3),t(4),t(5),t(6),t(7),t(8),t(9),t(10)),r}};if("undefined"!=typeof module)module.exports.LoggingEnhancer=n;else if("undefined"!=typeof exports)exports.LoggingEnhancer=n;else{if("undefined"==typeof window)throw new Error("unable to expose LoggingEnhancer: no module, exports object and no global window detected");window.loggingEnhancer=new n(window.sprintf,window.moment)}}();
},{}]},{},[1]);
<|endoftext|>


<commit_before>!function(){"use strict";window.namespace=function(a){for(var b,c=window,d=a.split(".");b=d.shift();)c[b]=c[b]||{},c=c[b]}}(window._),this.DashModalJST=this.DashModalJST||{},this.DashModalJST["scripts/dash-modal/template.ejs"]=function(obj){obj||(obj={});{var __t,__p="";_.escape}with(obj)__p+='
\n
\n
\n
\n
\n          ×\n

\n

\n
\n
\n
\n
\n
\n';return __p},function(){var a=function(a,b){return function(){return a.apply(b,arguments)}};namespace("DashModal"),DashModal.EscapeKeyUp=function(){function b(){this.handleKeyup=a(this.handleKeyup,this)}return b.ESCAPE_KEY_CODE=27,b.prototype.respondWith=function(a){return this.callback=a,$(document).bind("keyup",this.handleKeyup)},b.prototype.removeListeners=function(){return $(document).unbind("keyup",this.handleKeyup)},b.prototype.handleKeyup=function(a){return a.keyCode===DashModal.EscapeKeyUp.ESCAPE_KEY_CODE?this.callback():void 0},b}()}.call(this),function(){namespace("DashModal"),DashModal.NullEscapeKeyUp=function(){function a(){}return a.prototype.respondWith=function(){},a.prototype.removeListeners=function(){},a}()}.call(this),function(){var a=function(a,b){return function(){return a.apply(b,arguments)}},b=function(a,b){function d(){this.constructor=a}for(var e in b)c.call(b,e)&&(a[e]=b[e]);return d.prototype=b.prototype,a.prototype=new d,a.__super__=b.prototype,a},c={}.hasOwnProperty;namespace("DashModal"),DashModal.View=function(c){function d(){return this.hide=a(this.hide,this),d.__super__.constructor.apply(this,arguments)}return b(d,c),d.prototype.template=DashModalJST["scripts/dash-modal/template.ejs"],d.prototype.initialize=function(a){return this.options=a,this.view=this.options.view,this.escapeKeyUp=this.buildEscapeKeyUp()},d.prototype.events={"click [data-id=modal-inner]":"stopPropagation","click [data-id=modal]":"outerCountainerClick","click [data-id=close]":"hide"},d.prototype.stopPropagation=function(a){return a.stopPropagation()},d.prototype.outerCountainerClick=function(){return this.options.shouldCloseOnOverlay?this.hide():void 0},d.prototype.show=function(){return this.escapeKeyUp.respondWith(this.hide),this.$el.html(this.template({modalSize:this.options.modalSize})),this.options.shouldCloseOnX||this.removeCloseButton(),this.listenTo(this.view,"hideModal",this.hide),this.$("[data-id=view-container]").html(this.view.render().$el),$("body").addClass("prevent-scrolling"),this.$("[data-id=modal]").addClass("in"),$("[data-id=modal-container]").html(this.el),this},d.prototype.hide=function(){var a;return this.escapeKeyUp.removeListeners(),"function"==typeof(a=this.options).onCloseCallback&&a.onCloseCallback(),this.$("[data-id=modal]").removeClass("in"),setTimeout(function(a){return function(){return a.$el.hide()}}(this),150),$("body").removeClass("prevent-scrolling")},d.prototype.isVisible=function(){return"prevent-scrolling"===$("body").attr("class")},d.prototype.removeCloseButton=function(){return this.$("[data-id=close]").remove()},d.prototype.buildEscapeKeyUp=function(){return this.options.shouldCloseOnEscape?new DashModal.EscapeKeyUp:new DashModal.NullEscapeKeyUp},d}(Backbone.View)}.call(this);<commit_msg>build dashmodal<commit_after>!function(){"use strict";window.namespace=function(a){for(var b,c=window,d=a.split(".");b=d.shift();)c[b]=c[b]||{},c=c[b]}}(window._),this.DashModalJST=this.DashModalJST||{},this.DashModalJST["scripts/dash-modal/template.ejs"]=function(obj){obj||(obj={});{var __t,__p="";_.escape}with(obj)__p+='
\n
\n
\n
\n
\n          ×\n

\n

\n
\n
\n
\n
\n
\n';return __p},function(){var a=function(a,b){return function(){return a.apply(b,arguments)}};namespace("DashModal"),DashModal.EscapeKeyUp=function(){function b(){this.handleKeyup=a(this.handleKeyup,this)}return b.ESCAPE_KEY_CODE=27,b.prototype.respondWith=function(a){return this.callback=a,$(document).bind("keyup",this.handleKeyup)},b.prototype.removeListeners=function(){return $(document).unbind("keyup",this.handleKeyup)},b.prototype.handleKeyup=function(a){return a.keyCode===DashModal.EscapeKeyUp.ESCAPE_KEY_CODE?this.callback():void 0},b}()}.call(this),function(){namespace("DashModal"),DashModal.NullEscapeKeyUp=function(){function a(){}return a.prototype.respondWith=function(){},a.prototype.removeListeners=function(){},a}()}.call(this),function(){var a=function(a,b){return function(){return a.apply(b,arguments)}},b=function(a,b){function d(){this.constructor=a}for(var e in b)c.call(b,e)&&(a[e]=b[e]);return d.prototype=b.prototype,a.prototype=new d,a.__super__=b.prototype,a},c={}.hasOwnProperty;namespace("DashModal"),DashModal.View=function(c){function d(){return this.hide=a(this.hide,this),d.__super__.constructor.apply(this,arguments)}return b(d,c),d.prototype.template=DashModalJST["scripts/dash-modal/template.ejs"],d.prototype.initialize=function(a){return this.options=a,this.view=this.options.view,this.escapeKeyUp=this.buildEscapeKeyUp()},d.prototype.events={"click [data-id=modal-inner]":"stopPropagation","click [data-id=modal]":"outerCountainerClick","click [data-id=close]":"hide"},d.prototype.stopPropagation=function(a){return a.stopPropagation()},d.prototype.outerCountainerClick=function(){return this.options.shouldCloseOnOverlay?this.hide():void 0},d.prototype.show=function(){return this.escapeKeyUp.respondWith(this.hide),this.$el.html(this.template({modalSize:this.options.modalSize})),this.options.hasXButton||this.removeCloseButton(),this.listenTo(this.view,"hideModal",this.hide),this.$("[data-id=view-container]").html(this.view.render().$el),$("body").addClass("prevent-scrolling"),this.$("[data-id=modal]").addClass("in"),$("[data-id=modal-container]").html(this.el),this},d.prototype.hide=function(){var a;return this.escapeKeyUp.removeListeners(),"function"==typeof(a=this.options).onCloseCallback&&a.onCloseCallback(),this.$("[data-id=modal]").removeClass("in"),setTimeout(function(a){return function(){return a.$el.hide()}}(this),150),$("body").removeClass("prevent-scrolling")},d.prototype.isVisible=function(){return"prevent-scrolling"===$("body").attr("class")},d.prototype.removeCloseButton=function(){return this.$("[data-id=close]").remove()},d.prototype.buildEscapeKeyUp=function(){return this.options.shouldCloseOnEscape?new DashModal.EscapeKeyUp:new DashModal.NullEscapeKeyUp},d}(Backbone.View)}.call(this);<|endoftext|>


<commit_before>/* global featureFile, scenarios, steps */
const Yadda = require('yadda');
const buildDriver = require('./driver-core');
var mocha = require('mocha');

function defineWindowInLibrary(library, framework) {
  if (typeof framework === 'object' && !Array.isArray(framework)) {
    library.define(
      'a web browser',
      function dontSetWindow(done) {
        done();
      }
    );
  } else {
    library.define(
      'a web browser',
      function setWindowSize(done) {
        this.driver
          .manage()
          .window()
          .setSize(this.width, this.height)
          .then(() => done());
      }
    );
  }
  library.define(
    'end the test',
    function endTest() {
      this.driver.quit();
    }
  );
  return library;
}

function buildYadda(library, framework) {
  if (library === null || library === undefined) {
    throw new Error('step library has not been defined please write some steps');
  }
  if (framework.stepLevel) {
    Yadda.plugins.mocha.StepLevelPlugin.init();
    const features = new Yadda.FeatureFileSearch('features');
    const builtLibrary = defineWindowInLibrary(library, framework);
    const yadda = Yadda.createInstance(
      builtLibrary,
      {
        ctx: {},
        driver: buildDriver(framework),
        width: framework && framework.size ?
        framework.size.width :
        1024,
        height: framework && framework.size ?
        framework.size.height :
        728,
      }
    );
    return features
      .each(
        file => featureFile(
          file,
          (feature) => {
            scenarios(
              feature.scenarios,
              (scenario) => {
                steps(
                  scenario.steps,
                  (step, done) => {
                    yadda.run(step, { mocha: this }, done);
                  }
                );
              }
            );
          }
        )
      );
  } else {
    Yadda.plugins.mocha.ScenarioLevelPlugin.init();
    const features = new Yadda.FeatureFileSearch('features');
    const builtLibrary = defineWindowInLibrary(library, framework);
    const yadda = Yadda.createInstance(
      builtLibrary,
      {
        ctx: {},
        driver: buildDriver(framework),
        width: framework && framework.size ?
        framework.size.width :
        1024,
        height: framework && framework.size ?
        framework.size.height :
        728,
      }
    );

    return features.each(file =>
      featureFile(file, (feature) => {
        scenarios(feature.scenarios, function (scenario, done) {
          yadda.run(scenario.steps, { mocha: this }, done);
        })
      })
    )
  }

}

module.exports = buildYadda;
<commit_msg>removing the arrow functions as it is not supported<commit_after>/* global featureFile, scenarios, steps */
const Yadda = require('yadda');
const buildDriver = require('./driver-core');
var mocha = require('mocha');

function defineWindowInLibrary(library, framework) {
  if (typeof framework === 'object' && !Array.isArray(framework)) {
    library.define(
      'a web browser',
      function dontSetWindow(done) {
        done();
      }
    );
  } else {
    library.define(
      'a web browser',
      function setWindowSize(done) {
        this.driver
          .manage()
          .window()
          .setSize(this.width, this.height)
          .then(() => done());
      }
    );
  }
  library.define(
    'end the test',
    function endTest() {
      this.driver.quit();
    }
  );
  return library;
}

function buildYadda(library, framework) {
  if (library === null || library === undefined) {
    throw new Error('step library has not been defined please write some steps');
  }
  if (framework.stepLevel) {
    Yadda.plugins.mocha.StepLevelPlugin.init();
    const features = new Yadda.FeatureFileSearch('features');
    const builtLibrary = defineWindowInLibrary(library, framework);
    const yadda = Yadda.createInstance(
      builtLibrary,
      {
        mocha: this,
        ctx: {},
        driver: buildDriver(framework),
        width: framework && framework.size ?
        framework.size.width :
        1024,
        height: framework && framework.size ?
        framework.size.height :
        728,
      }
    );
    return features.each(function(file) {
      featureFile(file, function(feature) {
        scenarios(feature.scenarios, function(scenario) {
          steps(scenario.steps, function(step, done) {
            yadda.run(step, { mocha: this }, done);
          });
        });
      });
    });
  } else {
    Yadda.plugins.mocha.ScenarioLevelPlugin.init();
    const features = new Yadda.FeatureFileSearch('features');
    const builtLibrary = defineWindowInLibrary(library, framework);
    const yadda = Yadda.createInstance(
      builtLibrary,
      {
        ctx: {},
        driver: buildDriver(framework),
        width: framework && framework.size ?
        framework.size.width :
        1024,
        height: framework && framework.size ?
        framework.size.height :
        728,
      }
    );

    return features.each(function(file) {
      featureFile(file, function(feature) {
        scenarios(feature.scenarios, function(scenario, done) {
            yadda.run(scenario.steps, { mocha: this }, done);
        });
      });
    });
  }

}

module.exports = buildYadda;

<|endoftext|>


<commit_before>const HTMLElement=(e=>{function t(){}return t.prototype=window.HTMLElement.prototype,t})();class TokenList{constructor(e){const t=e=>/{(\w+|#)}/.test(e.textContent)&&(e.text=e.textContent).match(/[^{]+(?=})/g).map(t=>(this[t]||(this[t]=[])).push(e)),n=document.createNodeIterator(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,e=>e.attributes&&[].slice.call(e.attributes).map(t)||t(e),null);for(;n.nextNode(););}bind(e){const t=t=>n=>n.textContent=n.textContent.split("{"+t+"}").join(e[t]);for(let n in this)this[n].map(e=>(e.textContent=e.text)&&e);for(let n in this)this[n].map(t(n))}}(e=>{function t(e){let t=new XMLHttpRequest;t.link=e,t.onload=n,t.open("GET",e.href),t.responseType="document",t.send()}function n(){let e=this.link,t=this.response,n=e.nextChild,l=e.content=t.querySelector("template");for(let o of document.querySelectorAll(e.id))l&&s.call(o,l);for(let s of t.querySelectorAll("style,link,script"))!function(e,t,n){let s=t.getAttribute("as"),l=document.createElement("script"==s?s:t.localName);["id","rel","href","src","textContent","as","defer","crossOrigin"].map(e=>t[e]&&e in l&&(l[e]=t[e])),"style"==s&&(l.rel="stylesheet"),"script"==s&&(l.src=l.href),e.parentNode.insertBefore(l,n)}(e,s,n)}function s(e){e=document.importNode(e,!0);let t;[].slice.call(e.attributes).map(e=>!this.attributes[e.name]&&this.setAttribute(e.name,e.value));for(let n of this.querySelectorAll("[slot]"))(t=(e.content||e).querySelector("slot[name="+n.getAttribute("slot")+"]"))&&t.parentNode.replaceChild(n,t);return this.innerHTML=e.innerHTML}new MutationObserver(e=>{for(let n of e)for(let e of n.addedNodes)/^p/.test(e.rel)&&/\-/.test(e.id)&&t(e),/\-/.test(e.localName)&&(link=document.querySelector("#"+e.localName))&&link.content&&s.call(e,link.content)&&customElements.upgrade(e)}).observe(document.documentElement,{childList:!0,subtree:!0}),[].slice.call(document.querySelectorAll('[rel^=pre][id~="-"]')).map(t)})();const Template=e=>{e.length&&(e=document.querySelector("template[name="+e+"]"));let t=e.innerHTML,n=e.nextSibling;return e.innerHTML="",e.bind=function(e){const s=document.createElement("section");for(let t of this.dependents||[])t.parentNode.removeChild(t);s.innerHTML=[].concat(e).reduce((e,n,s)=>{let l=t;"object"!=typeof n&&(n={self:n}),n["#"]=s;for(let t in n)l=l.split("{"+t+"}").join(n[t]);return e+l},"");for(let t of this.dependents=[].slice.call(s.childNodes))this.parentNode.insertBefore(t,n)}.bind(e),e};window.customElements=window.customElements||{},new class{constructor(){customElements.define=this.define.bind(this),customElements.upgrade=this.upgrade.bind(this)}define(e,t){this[e]=t,[].slice.call(document.querySelectorAll(e)).map(this.upgrade,this)}upgrade(e){this[e.localName]&&Object.setPrototypeOf(e,this[e.localName].prototype).connectedCallback()}};const ParentNode=e=>class extends e{select(){return this.selectAll(...arguments)[0]}selectAll(e,...t){return e=[].concat(e),[].slice.call(this.querySelectorAll(t.reduce((t,n)=>t+n+e.shift(),e.shift())))}},EventTarget=e=>class extends e{on(e,t){this.addEventListener(e,this.renderable(t))}renderable(e){return t=>!1!==e.call(this,t)&&t.defaultPrevented||this.render()}},GlobalEventHandlers=e=>class extends e{onconnect(){this.templates=this.selectAll("template[name]").map(Template),this.tokens=new TokenList(this),super.onconnect&&super.onconnect()}reflect(e){/^on/.test(e)&&e in HTMLElement.prototype&&this.on(e.substr(2),this[e])}register(e,t,n){for(let s of[].slice.call(e.attributes))/^on/.test(n=s.name)&&(t=(/{\s*(\w+)/.exec(e[n])||[])[1])&&(e[n]=this.renderable(this[t]))}},Custom=e=>class extends(ParentNode(EventTarget(GlobalEventHandlers(e)))){connectedCallback(){this.context={},super.initialize&&super.initialize(),Object.getOwnPropertyNames(e.prototype).map(this.reflect,this),this.onconnect(),this.render()}render(){for(let e of this.templates)e.bind(this[e.getAttribute("name")]);this.tokens.bind(this),this.register(this),this.selectAll("*").map(this.register,this),super.onidle&&super.onidle()}},Element=e=>t=>customElements.define(e+"",Custom(t));<commit_msg>:muscle: bump ??? distribution dist/snuggsi.min.es.js<commit_after>const HTMLElement=(e=>{function t(){}return t.prototype=window.HTMLElement.prototype,t})();class TokenList{constructor(e){const t=e=>{console.log("text content",e.textContent),/{(\w+|#)}/.test(e.textContent)&&(e.text=e.textContent).match(/[^{]+(?=})/g).map(t=>(this[t]||(this[t]=[])).push(e))},n=document.createNodeIterator(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,e=>e.attributes&&[].slice.call(e.attributes).map(t)||t(e),null);for(;n.nextNode(););}bind(e){const t=t=>n=>n.textContent=n.textContent.split("{"+t+"}").join(e[t]);for(let n in this)console.log("symbol",n),this[n].map(e=>(e.textContent=e.text)&&e);for(let n in this)this[n].map(t(n))}}(e=>{function t(e){let t=new XMLHttpRequest;t.link=e,t.onload=n,t.open("GET",e.href),t.responseType="document",t.send()}function n(){let e=this.link,t=this.response,n=e.nextChild,l=e.content=t.querySelector("template");for(let o of document.querySelectorAll(e.id))l&&s.call(o,l);for(let s of t.querySelectorAll("style,link,script"))!function(e,t,n){let s=t.getAttribute("as"),l=document.createElement("script"==s?s:t.localName);["id","rel","href","src","textContent","as","defer","crossOrigin"].map(e=>t[e]&&e in l&&(l[e]=t[e])),"style"==s&&(l.rel="stylesheet"),"script"==s&&(l.src=l.href),e.parentNode.insertBefore(l,n)}(e,s,n)}function s(e){e=document.importNode(e,!0);let t;[].slice.call(e.attributes).map(e=>!this.attributes[e.name]&&this.setAttribute(e.name,e.value));for(let n of this.querySelectorAll("[slot]"))(t=(e.content||e).querySelector("slot[name="+n.getAttribute("slot")+"]"))&&t.parentNode.replaceChild(n,t);return this.innerHTML=e.innerHTML}new MutationObserver(e=>{for(let n of e)for(let e of n.addedNodes)/^p/.test(e.rel)&&/\-/.test(e.id)&&t(e),/\-/.test(e.localName)&&(link=document.querySelector("#"+e.localName))&&link.content&&s.call(e,link.content)&&customElements.upgrade(e)}).observe(document.documentElement,{childList:!0,subtree:!0}),[].slice.call(document.querySelectorAll('[rel^=pre][id~="-"]')).map(t)})();const Template=e=>{e.length&&(e=document.querySelector("template[name="+e+"]"));let t=e.innerHTML,n=e.nextSibling;return e.innerHTML="",e.bind=function(e){const s=document.createElement("section");for(let t of this.dependents||[])t.parentNode.removeChild(t);s.innerHTML=[].concat(e).reduce((e,n,s)=>{let l=t;"object"!=typeof n&&(n={self:n}),n["#"]=s;for(let t in n)l=l.split("{"+t+"}").join(n[t]);return e+l},"");for(let t of this.dependents=[].slice.call(s.childNodes))this.parentNode.insertBefore(t,n)}.bind(e),e};window.customElements=window.customElements||{},new class{constructor(){customElements.define=this.define.bind(this),customElements.upgrade=this.upgrade.bind(this)}define(e,t){this[e]=t,[].slice.call(document.querySelectorAll(e)).map(this.upgrade,this)}upgrade(e){this[e.localName]&&Object.setPrototypeOf(e,this[e.localName].prototype).connectedCallback()}};const ParentNode=e=>class extends e{select(){return this.selectAll(...arguments)[0]}selectAll(e,...t){return e=[].concat(e),[].slice.call(this.querySelectorAll(t.reduce((t,n)=>t+n+e.shift(),e.shift())))}},EventTarget=e=>class extends e{on(e,t){this.addEventListener(e,this.renderable(t))}renderable(e){return t=>!1!==e.call(this,t)&&t.defaultPrevented||this.render()}},GlobalEventHandlers=e=>class extends e{onconnect(){this.templates=this.selectAll("template[name]").map(Template),this.tokens=new TokenList(this),super.onconnect&&super.onconnect()}reflect(e){/^on/.test(e)&&e in HTMLElement.prototype&&this.on(e.substr(2),this[e])}register(e,t,n){for(let s of[].slice.call(e.attributes))/^on/.test(n=s.name)&&(t=(/{\s*(\w+)/.exec(e[n])||[])[1])&&(e[n]=this.renderable(this[t]))}},Custom=e=>class extends(ParentNode(EventTarget(GlobalEventHandlers(e)))){connectedCallback(){this.context={},super.initialize&&super.initialize(),Object.getOwnPropertyNames(e.prototype).map(this.reflect,this),this.onconnect(),this.render()}render(){for(let e of this.templates)e.bind(this[e.getAttribute("name")]);this.tokens.bind(this),this.register(this),this.selectAll("*").map(this.register,this),super.onidle&&super.onidle()}},Element=e=>t=>customElements.define(e+"",Custom(t));<|endoftext|>


<commit_before>'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  return typeof obj;
} : function (obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

var _createClass = function () {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  return function (Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps);
    if (staticProps) defineProperties(Constructor, staticProps);
    return Constructor;
  };
}();

var Stylex = function () {
  function Stylex() {
    _classCallCheck(this, Stylex);

    this.ruleIndex = 0;
    this.rules = {};

    var isClient = typeof window !== 'undefined';
    this.isClient = isClient;

    if (isClient) {
      var styleTag = document.getElementById('styleVars');

      if (styleTag === null) {
        styleTag = document.createElement('style');

        styleTag.appendChild(document.createTextNode(''));
        styleTag.setAttribute('rel', 'stylesheet');
        styleTag.setAttribute('type', 'text/css');
        styleTag.setAttribute('id', 'styleVars');

        document.head.appendChild(styleTag);
      }

      this.el = styleTag;
      this.sheet = styleTag.sheet;
    }
  }

  _createClass(Stylex, [{
    key: 'set',
    value: function set(varname, props, value, important) {
      var hyphenate = this.hyphenate;

      var newRules = {};

      if ((typeof props === 'undefined' ? 'undefined' : _typeof(props)) === 'object') {
        for (var key in props) {
          if (_typeof(props[key]) === 'object') {
            if (typeof props[key].value === 'undefined') {
              // This is a nested child
              if (typeof newRules[varname + key] === 'undefined') {
                newRules[varname + key] = {};
              }
              for (var j in props[key]) {
                if (_typeof(props[key][j]) === 'object') {
                  // This is a style schema
                  var _value = props[key][j].value + (props[key][j].important ? ' !important' : '');
                  newRules[varname + key][hyphenate(j)] = _value;
                } else {
                  // This is a k/v pair
                  newRules[varname + key][hyphenate(j)] = props[key][j];
                }
              }
            } else {
              // This is a style schema
              if (typeof newRules[varname] === 'undefined') {
                newRules[varname] = {};
              }
              var _value2 = props[key].value + (props[key].important ? ' !important' : '');
              newRules[varname][hyphenate(key)] = _value2;
            }
          } else {
            // This is a k/v pair
            if (typeof newRules[varname] === 'undefined') {
              newRules[varname] = {};
            }
            newRules[varname][hyphenate(key)] = props[key];
          }
        }
      } else {
        newRules[varname] = {};
        newRules[varname][hyphenate(props)] = value + (important ? ' !important' : '');
      }

      for (var _key in newRules) {
        this._setRule(_key, newRules[_key]);
      }

      return {
        then: function then(cb) {
          setTimeout(cb, 0);
        }
      };
    }
  }, {
    key: '_setRule',
    value: function _setRule(key, props) {
      var rules = this.rules,
          sheet = this.sheet,
          isClient = this.isClient;

      if (typeof rules[key] === 'undefined') {
        rules[key] = { index: this.ruleIndex++, props: {} };
      } else {
        if (isClient) sheet.deleteRule(rules[key].index);
      }

      var styles = [];
      for (var k in props) {
        var v = props[k];
        styles.push(k + ':' + v);
      }

      rules[key].props = props;
      if (isClient) sheet.insertRule('.var--' + key + ' { ' + styles.join(';') + ' }', rules[key].index);
    }
  }, {
    key: 'hyphenate',
    value: function hyphenate(str) {
      return str.split(/(?=[A-Z])/).join('-').toLowerCase();
    }
  }]);

  return Stylex;
}();
<commit_msg>Update stylex-browser.js<commit_after>'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  return typeof obj;
} : function (obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

var _createClass = function () {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  return function (Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps);
    if (staticProps) defineProperties(Constructor, staticProps);
    return Constructor;
  };
}();

var Stylex = function () {
  function Stylex() {
    _classCallCheck(this, Stylex);

    this.ruleIndex = 0;
    this.rules = {};

    var isClient = typeof window !== 'undefined';
    this.isClient = isClient;

    if (isClient) {
      var styleTag = document.getElementById('styleVars');

      if (styleTag === null) {
        styleTag = document.createElement('style');

        styleTag.appendChild(document.createTextNode(''));
        styleTag.setAttribute('rel', 'stylesheet');
        styleTag.setAttribute('type', 'text/css');
        styleTag.setAttribute('id', 'styleVars');

        document.head.appendChild(styleTag);
      }

      this.el = styleTag;
      this.sheet = styleTag.sheet;
    }
  }

  _createClass(Stylex, [{
    key: 'set',
    value: function set(varname, props, value, important) {
      var hyphenate = this.hyphenate;

      var newRules = {};

      if ((typeof props === 'undefined' ? 'undefined' : _typeof(props)) === 'object') {
        for (var key in props) {
          if (_typeof(props[key]) === 'object') {
            if (typeof props[key].value === 'undefined') {
              // This is a nested child
              if (typeof newRules[varname + key] === 'undefined') {
                newRules[varname + key] = {};
              }
              for (var j in props[key]) {
                if (_typeof(props[key][j]) === 'object') {
                  // This is a style schema
                  var _value = props[key][j].value + (props[key][j].important ? ' !important' : '');
                  newRules[varname + key][hyphenate(j)] = _value;
                } else {
                  // This is a k/v pair
                  newRules[varname + key][hyphenate(j)] = props[key][j];
                }
              }
            } else {
              // This is a style schema
              if (typeof newRules[varname] === 'undefined') {
                newRules[varname] = {};
              }
              var _value2 = props[key].value + (props[key].important ? ' !important' : '');
              newRules[varname][hyphenate(key)] = _value2;
            }
          } else {
            // This is a k/v pair
            if (typeof newRules[varname] === 'undefined') {
              newRules[varname] = {};
            }
            newRules[varname][hyphenate(key)] = props[key];
          }
        }
      } else {
        newRules[varname] = {};
        newRules[varname][hyphenate(props)] = value + (important ? ' !important' : '');
      }

      for (var _key in newRules) {
        this._setRule(_key, newRules[_key]);
      }

      return {
        then: function then(cb) {
          setTimeout(cb, 0);
        }
      };
    }
  }, {
    key: '_setRule',
    value: function _setRule(key, props) {
      var rules = this.rules,
          sheet = this.sheet,
          isClient = this.isClient;

      if (typeof rules[key] === 'undefined') {
        rules[key] = { index: this.ruleIndex++, props: {} };
      } else {
        if (isClient) sheet.deleteRule(rules[key].index);
      }

      var styles = [];
      for (var k in props) {
        var v = props[k];
        styles.push(k + ':' + v);
      }

      rules[key].props = props;
      if (isClient) sheet.insertRule('.var--' + key + ' { ' + styles.join(';') + ' }', rules[key].index);
    }
  }, {
    key: 'hyphenate',
    value: function hyphenate(str) {
      return str.split(/(?=[A-Z])/).join('-').toLowerCase();
    }
  }]);

  return Stylex;
}();
<|endoftext|>


<commit_before><commit_msg>Add code from class<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Ericsson AB. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer
 *    in the documentation and/or other materials provided with the
 *    distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

"use strict";

var domObject = (function () {

    function createAttributeDescriptor(name, attributes) {
        return {
            "get": function () {
                var attribute = attributes[name];
                return typeof attribute == "function" ? attribute() : attribute;
            },
            "enumerable": true
        };
    }

    return {
        "addReadOnlyAttributes": function (target, attributes) {
            for (var name in attributes)
                Object.defineProperty(target, name, createAttributeDescriptor(name, attributes));
        },

        "addConstants": function (target, constants) {
            for (var name in constants)
                Object.defineProperty(target, name, {
                    "value": constants[name],
                    "enumerable": true
                });
        }
    };
})();

function EventTarget(attributes) {
    var _this = this;
    var listenersMap = {};

    if (attributes)
        addEventListenerAttributes(this, attributes);

    this.addEventListener = function (type, listener, useCapture) {
        if (typeof(listener) != "function")
            throw new TypeError("listener argument (" + listener + ") is not a function");
        var listeners = listenersMap[type];
        if (!listeners)
            listeners = listenersMap[type] = [];

        if (listeners.indexOf(listener) < 0)
            listeners.push(listener);
    };

    this.removeEventListener = function (type, listener, useCapture) {
        var listeners = listenersMap[type];
        if (!listeners)
            return;

        var i = listeners.indexOf(listener);
        if (i >= 0)
            listeners.splice(i, 1);
    };

    this.dispatchEvent = function (evt) {
        var listeners = [];

        var attributeListener = _this["on" + evt.type];
        if (attributeListener)
            listeners.push(attributeListener);

        if (listenersMap[evt.type])
            Array.prototype.push.apply(listeners, listenersMap[evt.type]);

        var errors = [];
        var result = true;
        listeners.forEach(function (listener) {
            try {
                result = !(listener(evt) === false) && result;
            } catch (e) {
                errors.push(e);
            }
        });

        errors.forEach(function (e) {
            setTimeout(function () {
                throw e;
            });
        });

        return result;
    };

    function addEventListenerAttributes(target, attributes) {
        for (var name in attributes)
            Object.defineProperty(target, name, createEventListenerDescriptor(name, attributes));
    }

    function createEventListenerDescriptor(name, attributes) {
        return {
            "get": function () { return attributes[name]; },
            "set": function (cb) { attributes[name] = (typeof(cb) == "function") ? cb : null; },
            "enumerable": true
        };
    }
}

function checkDictionary(name, dict, typeMap) {
    for (var memberName in dict) {
        if (!dict.hasOwnProperty(memberName) || !typeMap.hasOwnProperty(memberName))
            continue;

        var message = name + ": Dictionary member " + memberName;
        checkType(message, dict[memberName], typeMap[memberName]);
    }
}

function checkArguments(name, argsTypeTemplate, numRequired, args) {
    if (args.length < numRequired) {
        throw new TypeError(name + ": Too few arguments (got " + args.length + " expected " +
            numRequired + ")");
    }

    var typeTemplates = argsTypeTemplate.split(/\s*,\s*/);

    for (var i = 0; i < args.length && i < typeTemplates.length; i++) {
        var message = name + ": Argument " + (i + 1);
        checkType(message, args[i], typeTemplates[i]);
    }
}

function checkType(name, value, typeTemplate) {
    var expetedTypes = typeTemplate.split(/\s*\|\s*/);
    if (!canConvert(value, expetedTypes)) {
        throw new TypeError(name + " is of wrong type (expected " +
            expetedTypes.join(" or ") + ")");
    }
}

function canConvert(value, expetedTypes) {
    var type = typeof value;
    for (var i = 0; i < expetedTypes.length; i++) {
        var expetedType = expetedTypes[i];
        if (expetedType == "string" || expetedType == "boolean")
            return true; // type conversion will never throw
        if (expetedType == "number") {
            var asNumber = +value;
            if (!isNaN(asNumber) && asNumber != -Infinity && asNumber != Infinity)
                return true;
        }
        if (type == "object") {
            if (expetedType == "object")
                return true;
            // could be a specific object type or host object (e.g. Array)
            var constructor = self[expetedType];
            if (constructor && value instanceof constructor)
                return true;
        }
        if (type == expetedType && expetedType == "function")
            return true;
    }
    return false;
}

function randomString() {
    var randomValues = new Uint8Array(27);
    crypto.getRandomValues(randomValues);
    return btoa(String.fromCharCode.apply(null, randomValues));
}

function createError(name, message) {
    var constructor = self[name] || self.Error;
    var error = new constructor(message);
    error.name = name;
    return error;
}

function entityReplace(str) {
    return escape(str).replace(/%([0-9A-F]{2})/g, function (match) {
        return "&#" + parseInt(match.substr(1), 16) + ";"
    });
}
<commit_msg>domutils: Use the expected variable name<commit_after>/*
 * Copyright (C) 2014 Ericsson AB. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer
 *    in the documentation and/or other materials provided with the
 *    distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

"use strict";

var domObject = (function () {

    function createAttributeDescriptor(name, attributes) {
        return {
            "get": function () {
                var attribute = attributes[name];
                return typeof attribute == "function" ? attribute() : attribute;
            },
            "enumerable": true
        };
    }

    return {
        "addReadOnlyAttributes": function (target, attributes) {
            for (var name in attributes)
                Object.defineProperty(target, name, createAttributeDescriptor(name, attributes));
        },

        "addConstants": function (target, constants) {
            for (var name in constants)
                Object.defineProperty(target, name, {
                    "value": constants[name],
                    "enumerable": true
                });
        }
    };
})();

function EventTarget(attributes) {
    var _this = this;
    var listenersMap = {};

    if (attributes)
        addEventListenerAttributes(this, attributes);

    this.addEventListener = function (type, listener, useCapture) {
        if (typeof(listener) != "function")
            throw new TypeError("listener argument (" + listener + ") is not a function");
        var listeners = listenersMap[type];
        if (!listeners)
            listeners = listenersMap[type] = [];

        if (listeners.indexOf(listener) < 0)
            listeners.push(listener);
    };

    this.removeEventListener = function (type, listener, useCapture) {
        var listeners = listenersMap[type];
        if (!listeners)
            return;

        var i = listeners.indexOf(listener);
        if (i >= 0)
            listeners.splice(i, 1);
    };

    this.dispatchEvent = function (evt) {
        var listeners = [];

        var attributeListener = _this["on" + evt.type];
        if (attributeListener)
            listeners.push(attributeListener);

        if (listenersMap[evt.type])
            Array.prototype.push.apply(listeners, listenersMap[evt.type]);

        var errors = [];
        var result = true;
        listeners.forEach(function (listener) {
            try {
                result = !(listener(evt) === false) && result;
            } catch (e) {
                errors.push(e);
            }
        });

        errors.forEach(function (e) {
            setTimeout(function () {
                throw e;
            });
        });

        return result;
    };

    function addEventListenerAttributes(target, attributes) {
        for (var name in attributes)
            Object.defineProperty(target, name, createEventListenerDescriptor(name, attributes));
    }

    function createEventListenerDescriptor(name, attributes) {
        return {
            "get": function () { return attributes[name]; },
            "set": function (cb) { attributes[name] = (typeof(cb) == "function") ? cb : null; },
            "enumerable": true
        };
    }
}

function checkDictionary(name, dict, typeMap) {
    for (var memberName in dict) {
        if (!dict.hasOwnProperty(memberName) || !typeMap.hasOwnProperty(memberName))
            continue;

        var message = name + ": Dictionary member " + memberName;
        checkType(message, dict[memberName], typeMap[memberName]);
    }
}

function checkArguments(name, argsTypeTemplate, numRequired, args) {
    if (args.length < numRequired) {
        throw new TypeError(name + ": Too few arguments (got " + args.length + " expected " +
            numRequired + ")");
    }

    var typeTemplates = argsTypeTemplate.split(/\s*,\s*/);

    for (var i = 0; i < args.length && i < typeTemplates.length; i++) {
        var message = name + ": Argument " + (i + 1);
        checkType(message, args[i], typeTemplates[i]);
    }
}

function checkType(name, value, typeTemplate) {
    var expectedTypes = typeTemplate.split(/\s*\|\s*/);
    if (!canConvert(value, expectedTypes)) {
        throw new TypeError(name + " is of wrong type (expected " +
            expectedTypes.join(" or ") + ")");
    }
}

function canConvert(value, expectedTypes) {
    var type = typeof value;
    for (var i = 0; i < expectedTypes.length; i++) {
        var expectedType = expectedTypes[i];
        if (expectedType == "string" || expectedType == "boolean")
            return true; // type conversion will never throw
        if (expectedType == "number") {
            var asNumber = +value;
            if (!isNaN(asNumber) && asNumber != -Infinity && asNumber != Infinity)
                return true;
        }
        if (type == "object") {
            if (expectedType == "object")
                return true;
            // could be a specific object type or host object (e.g. Array)
            var constructor = self[expectedType];
            if (constructor && value instanceof constructor)
                return true;
        }
        if (type == expectedType && expectedType == "function")
            return true;
    }
    return false;
}

function randomString() {
    var randomValues = new Uint8Array(27);
    crypto.getRandomValues(randomValues);
    return btoa(String.fromCharCode.apply(null, randomValues));
}

function createError(name, message) {
    var constructor = self[name] || self.Error;
    var error = new constructor(message);
    error.name = name;
    return error;
}

function entityReplace(str) {
    return escape(str).replace(/%([0-9A-F]{2})/g, function (match) {
        return "&#" + parseInt(match.substr(1), 16) + ";"
    });
}
<|endoftext|>


<commit_before>// ----------------------------------------------------------------------------
// Usage:
//
//      npm run export-exchanges
// ----------------------------------------------------------------------------

"use strict";

const fs        = require ('fs')
    , countries = require ('./countries')
    , asTable   = require ('as-table')
    , execSync  = require ('child_process').execSync
    , log       = require ('ololog').unlimited
    , ansi      = require ('ansicolor').nice
    , { keys, values, entries } = Object
    , { replaceInFile } = require ('./fs.js')

// ----------------------------------------------------------------------------

function cloneGitHubWiki (gitWikiPath) {

    if (!fs.existsSync (gitWikiPath)) {
        log.bright.cyan ('Cloning ccxt.wiki...')
        execSync ('git clone https://github.com/ccxt/ccxt.wiki.git ' + gitWikiPath)
    }
}

// ----------------------------------------------------------------------------

function logExportExchanges (filename, regex, replacement) {
    log.bright.cyan ('Exporting exchanges →', filename.yellow)
    replaceInFile (filename, regex, replacement)
}

// ----------------------------------------------------------------------------

function exportExchanges ({ python2Folder, python3Folder, phpFolder }) {

    log.bright.yellow ('Exporting exchanges...')

    const includedIds = fs.readFileSync ('exchanges.cfg')
        .toString () // Buffer → String
        .split ('\n') // String → Array
        .map (line => line.split ('#')[0].trim ()) // trim comments
        .filter (exchange => exchange); // filter empty lines

    const isIncluded = (id) => ((includedIds.length === 0) || includedIds.includes (id))

    const ids = fs.readdirSync ('./js/')
        .filter (file => file.includes ('.js'))
        .map (file => file.slice (0, -3))
        .filter (isIncluded);

    const pad = function (string, n) {
        return (string + ' '.repeat (n)).slice (0, n)
    }

    ;[
        {
            folder: '.',
            file: '/ccxt.js',
            regex:  /(?:const|var)\s+exchanges\s+\=\s+\{[^\}]+\}/,
            replacement: "const exchanges = {\n" + ids.map (id => pad ("    '" + id + "':", 30) + " require ('./js/" + id + ".js'),").join ("\n") + "    \n}",
        },
        {
            folder: python2Folder,
            file: '/__init__.py',
            regex: /exchanges \= \[[^\]]+\]/,
            replacement: "exchanges = [\n" + "    '" + ids.join ("',\n    '") + "'," + "\n]",
        },
        {
            folder: python2Folder,
            file: '/__init__.py',
            regex: /(?:from ccxt\.[^\.]+ import [^\s]+\s+\# noqa\: F401[\r]?[\n])+[\r]?[\n]exchanges/,
            replacement: ids.map (id => pad ('from ccxt.' + id + ' import ' + id, 60) + '# noqa: F401').join ("\n") + "\n\nexchanges",
        },
        {
            folder: python3Folder,
            file: '/__init__.py',
            regex: /(?:from ccxt\.async_support\.[^\.]+ import [^\s]+\s+\# noqa\: F401[\r]?[\n])+[\r]?[\n]exchanges/,
            replacement: ids.map (id => pad ('from ccxt.async_support.' + id + ' import ' + id, 74) + '# noqa: F401').join ("\n") + "\n\nexchanges",
        },
        {
            folder: python3Folder,
            file: '/__init__.py',
            regex: /exchanges \= \[[^\]]+\]/,
            replacement: "exchanges = [\n" + "    '" + ids.join ("',\n    '") + "'," + "\n]",
        },
        {
            folder: phpFolder,
            file: '/base/Exchange.php',
            regex: /public static \$exchanges \= array\s*\([^\)]+\)/,
            replacement: "public static $exchanges = array(\n        '" + ids.join ("',\n        '") + "',\n    )",
        },

    ].forEach (({ folder, file, regex, replacement }) => {
        if (folder) {
            logExportExchanges (folder + file, regex, replacement)
        }
    })

    log.bright.green ('Base sources updated successfully.')

    return ids
}

// ----------------------------------------------------------------------------

function createExchanges (ids) {

    const ccxt = require ('../ccxt.js')

    const createExchange = (id) => {
        ccxt[id].prototype.checkRequiredDependencies = () => {} // suppress it
        return new (ccxt)[id] ()
    }

    return ccxt.indexBy (ids.map (createExchange), 'id')
}

// // ----------------------------------------------------------------------------
// // strategically placed exactly here (we can require it AFTER the export)
// const ccxt = require ('../ccxt.js')
// // ----------------------------------------------------------------------------
// // create exchanges
// const createExchange = (id) => {
//     ccxt[id].prototype.checkRequiredDependencies = () => {} // suppress it
//     return new (ccxt)[id] ()
// }
// const exchanges = ccxt.indexBy (ids.map (createExchange), 'id')

// ----------------------------------------------------------------------------
// TODO: REWRITE THIS ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

function exportSupportedAndCertifiedExchanges (exchanges, wikiPath) {

    // ............................................................................
    // markup constants and helper functions

    const countryName = (code) => countries[code] || code

    const ccxtCertifiedBadge = '[![CCXT Certified](https://img.shields.io/badge/CCXT-certified-green.svg)](https://github.com/ccxt/ccxt/wiki/Certification)'
    const logoHeading = ' '.repeat (7) + 'logo' + ' '.repeat (7)
    const tableHeadings = [ logoHeading, 'id', 'name', 'ver', 'doc', 'certified', ]
    const exchangesByCountryHeading = [ 'country / region', ... tableHeadings ]

    // ----------------------------------------------------------------------------
    // list all supported exchanges

    const exchangesNotListedInDocs = []

    let tableData = values (exchanges)
        .filter (exchange => !exchangesNotListedInDocs.includes (exchange.id))
        .map (exchange => {
            let logo = exchange.urls['logo']
            let website = Array.isArray (exchange.urls.www) ? exchange.urls.www[0] : exchange.urls.www
            let url = exchange.urls.referral || website
            let countries = Array.isArray (exchange.countries) ? exchange.countries.map (countryName).join (', ') : countryName (exchange.countries)
            let doc = Array.isArray (exchange.urls.doc) ? exchange.urls.doc[0] : exchange.urls.doc
            let version = exchange.version ? exchange.version : '\*'
            let matches = version.match (/[^0-9]*([0-9].*)/)
            if (matches) {
                version = matches[1];
            }
            return [
                '[![' + exchange.id + '](' + logo + ')](' + url + ')',
                exchange.id,
                '[' + exchange.name + '](' + url + ')',
                version,
                '[API](' + doc + ')',
                exchange.certified ? ccxtCertifiedBadge : '',
                countries,
            ]
        })

    // prepend the table header
    tableData.splice (0, 0, tableHeadings)

    function makeTable (jsonArray) {
        let table = asTable.configure ({ 'delimiter': ' | ' }) (jsonArray)
        let lines = table.split ("\n")
        lines.splice (1,0, lines[0].replace (/[^\|]/g, '-'))
        let headerLine = lines[1].split ('|')
        headerLine[3] = ':' + headerLine[3].slice (1, headerLine[3].length - 1) + ':'
        headerLine[4] = ':' + headerLine[4].slice (1, headerLine[4].length - 1) + ':'
        lines[1] = headerLine.join ('|')
        return lines.map (line => '|' + line + '|').join ("\n")
    }

    const exchangesTable = makeTable (tableData)
    const numExchanges = keys (exchanges).length
    const beginning = "The ccxt library currently supports the following "
    const ending = " cryptocurrency exchange markets and trading APIs:\n\n"
    const totalString = beginning + numExchanges + ending
    const allExchanges = totalString + exchangesTable + "$1"
    const allExchangesRegex = new RegExp ("[^\n]+[\n]{2}\\|[^`]+\\|([\n][\n]|[\n]$|$)", 'm')
    logExportExchanges ('README.md', allExchangesRegex, allExchanges)
    logExportExchanges (wikiPath + '/Manual.md', allExchangesRegex, allExchanges)
    logExportExchanges (wikiPath + '/Exchange-Markets.md', allExchangesRegex, allExchanges)

    const certifiedFieldIndex = tableHeadings.indexOf ('certified')
    const certified = tableData.filter ((x) => x[certifiedFieldIndex] !== '' )
    const certifiedExchangesRegex = new RegExp ("^(## Certified Cryptocurrency Exchanges\n{3})(?:\\|.+\\|$\n)+", 'm')
    const certifiedExchangesTable = makeTable (certified)
    const certifiedExchanges = '$1' + certifiedExchangesTable + "\n"
    logExportExchanges ('README.md', certifiedExchangesRegex, certifiedExchanges)

    let exchangesByCountries = []
    keys (countries).forEach (code => {
        let country = countries[code]
        let result = []
        keys (exchanges).forEach (id => {
            let exchange = exchanges[id]
            let logo = exchange.urls['logo']
            let website = Array.isArray (exchange.urls.www) ? exchange.urls.www[0] : exchange.urls.www
            let url = exchange.urls.referral || website
            let doc = Array.isArray (exchange.urls.doc) ? exchange.urls.doc[0] : exchange.urls.doc
            let version = exchange.version ? exchange.version : '\*'
            let matches = version.match (/[^0-9]*([0-9].*)/)
            if (matches)
                version = matches[1];
            let shouldInclude = false
            if (Array.isArray (exchange.countries)) {
                if (exchange.countries.indexOf (code) > -1)
                    shouldInclude = true
            } else {
                if (code == exchange.countries)
                    shouldInclude = true
            }
            if (shouldInclude) {
                let entry = [
                    country,
                    '[![' + exchange.id + '](' + logo + ')](' + url + ')',
                    exchange.id,
                    '[' + exchange.name + '](' + url + ')',
                    version,
                    '[API](' + doc + ')',
                    // doesn't fit in width
                    // exchange.certified ? ccxtCertifiedBadge : '',
                ]
                result.push (entry)
            }
        })
        exchangesByCountries = exchangesByCountries.concat (result)
    });

    let countryKeyIndex = exchangesByCountryHeading.indexOf ('country / region')
    exchangesByCountries = exchangesByCountries.sort ((a, b) => {
        let countryA = a[countryKeyIndex].toLowerCase ()
        let countryB = b[countryKeyIndex].toLowerCase ()
        if (countryA > countryB) {
            return 1
        } else if (countryA < countryB) {
            return -1;
        } else {
            if (a['id'] > b['id'])
                return 1;
            else if (a['id'] < b['id'])
                return -1;
            else
                return 0;
        }
    })

    exchangesByCountries.splice (0, 0, exchangesByCountryHeading)
    let lines = makeTable (exchangesByCountries)
    let result = "# Exchanges By Country\n\nThe ccxt library currently supports the following cryptocurrency exchange markets and trading APIs:\n\n" + lines + "\n\n"
    let filename = wikiPath + '/Exchange-Markets-By-Country.md'
    fs.truncateSync (filename)
    fs.writeFileSync (filename, result)
}

// TODO: REWRITE THIS ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
// ----------------------------------------------------------------------------

function exportExchangeIdsToExchangesJson (exchanges) {
    log.bright ('Exporting exchange ids to'.cyan, 'exchanges.json'.yellow)
    fs.writeFileSync ('exchanges.json', JSON.stringify ({ ids: keys (exchanges) }, null, 4))
}

// ----------------------------------------------------------------------------

function exportWikiToGitHub (wikiPath, gitWikiPath) {

    log.bright.cyan ('Exporting wiki to GitHub')

    const ccxtWikiFiles = {
        'README.md': 'Home.md',
        'Install.md': 'Install.md',
        'Manual.md': 'Manual.md',
        'Exchange-Markets.md': 'Exchange-Markets.md',
        'Exchange-Markets-By-Country.md': 'Exchange-Markets-By-Country.md',
    }

    for (const [ sourceFile, destinationFile ] of entries (ccxtWikiFiles)) {

        const sourcePath = wikiPath + '/' + sourceFile
        const destinationPath = gitWikiPath + '/' + destinationFile
        log.bright.cyan ('Exporting', sourcePath.yellow, '→', destinationPath.yellow)
        fs.writeFileSync (destinationPath, fs.readFileSync (sourcePath))
    }
}

// ----------------------------------------------------------------------------

function exportKeywordsToPackageJson (exchanges) {

    log.bright ('Exporting exchange keywords to'.cyan, 'package.json'.yellow)

    const packageJSON = require ('../package.json')
    const keywords = new Set (packageJSON.keywords)

    for (const ex of values (exchanges)) {
        for (const url of Array.isArray (ex.urls.www) ? ex.urls.www : [ex.urls.www]) {
            keywords.add (url.replace (/(http|https):\/\/(www\.)?/, '').replace (/\/.*/, ''))
        }
        keywords.add (ex.name)
    }

    packageJSON.keywords = [...keywords]
    fs.writeFileSync ('./package.json', JSON.stringify (packageJSON, null, 2))
}

// ----------------------------------------------------------------------------

function exportEverything () {

    const wikiPath = 'wiki'
        , gitWikiPath = 'build/ccxt.wiki'

    cloneGitHubWiki (gitWikiPath)
    const ids = exportExchanges ({
        python2Folder: './python/ccxt',
        python3Folder: './python/ccxt/async_support',
        phpFolder: './php'
    })

    // strategically placed exactly here (we can require it AFTER the export)
    const exchanges = createExchanges (ids)

    exportSupportedAndCertifiedExchanges (exchanges, wikiPath)
    exportExchangeIdsToExchangesJson (exchanges)
    exportWikiToGitHub (wikiPath, gitWikiPath)
    exportKeywordsToPackageJson (exchanges)

    log.bright.green ('Exported successfully.')
}

// ============================================================================
// main entry point

if (require.main === module) {

    // if called directly like `node module`

    exportEverything ()

} else {

    // do nothing if required as a module
}

// ============================================================================

module.exports = {
    cloneGitHubWiki,
    exportExchanges,
    createExchanges,
    exportSupportedAndCertifiedExchanges,
    exportExchangeIdsToExchangesJson,
    exportWikiToGitHub,
    exportKeywordsToPackageJson,
    exportEverything,
}
<commit_msg>build/export-exchanges edits<commit_after>// ----------------------------------------------------------------------------
// Usage:
//
//      npm run export-exchanges
// ----------------------------------------------------------------------------

"use strict";

const fs        = require ('fs')
    , countries = require ('./countries')
    , asTable   = require ('as-table')
    , execSync  = require ('child_process').execSync
    , log       = require ('ololog').unlimited
    , ansi      = require ('ansicolor').nice
    , { keys, values, entries } = Object
    , { replaceInFile } = require ('./fs.js')

// ----------------------------------------------------------------------------

function cloneGitHubWiki (gitWikiPath) {

    if (!fs.existsSync (gitWikiPath)) {
        log.bright.cyan ('Cloning ccxt.wiki...')
        execSync ('git clone https://github.com/ccxt/ccxt.wiki.git ' + gitWikiPath)
    }
}

// ----------------------------------------------------------------------------

function logExportExchanges (filename, regex, replacement) {
    log.bright.cyan ('Exporting exchanges →', filename.yellow)
    replaceInFile (filename, regex, replacement)
}

// ----------------------------------------------------------------------------

function exportExchanges ({ js, python2, python3, php }) {

    log.bright.yellow ('Exporting exchanges...')

    const includedIds = fs.readFileSync ('exchanges.cfg')
        .toString () // Buffer → String
        .split ('\n') // String → Array
        .map (line => line.split ('#')[0].trim ()) // trim comments
        .filter (exchange => exchange); // filter empty lines

    const isIncluded = (id) => ((includedIds.length === 0) || includedIds.includes (id))

    const ids = fs.readdirSync ('./js/')
        .filter (file => file.includes ('.js'))
        .map (file => file.slice (0, -3))
        .filter (isIncluded);

    const pad = function (string, n) {
        return (string + ' '.repeat (n)).slice (0, n)
    }

    ;[
        Object.assign ({}, js, {
            regex:  /(?:const|var)\s+exchanges\s+\=\s+\{[^\}]+\}/,
            replacement: "const exchanges = {\n" + ids.map (id => pad ("    '" + id + "':", 30) + " require ('./js/" + id + ".js'),").join ("\n") + "    \n}",
        }),
        Object.assign ({}, python2, {
            regex: /exchanges \= \[[^\]]+\]/,
            replacement: "exchanges = [\n" + "    '" + ids.join ("',\n    '") + "'," + "\n]",
        }),
        Object.assign ({}, python2, {
            regex: /(?:from ccxt\.[^\.]+ import [^\s]+\s+\# noqa\: F401[\r]?[\n])+[\r]?[\n]exchanges/,
            replacement: ids.map (id => pad ('from ccxt.' + id + ' import ' + id, 60) + '# noqa: F401').join ("\n") + "\n\nexchanges",
        }),
        Object.assign ({}, python3, {
            regex: /(?:from ccxt\.async_support\.[^\.]+ import [^\s]+\s+\# noqa\: F401[\r]?[\n])+[\r]?[\n]exchanges/,
            replacement: ids.map (id => pad ('from ccxt.async_support.' + id + ' import ' + id, 74) + '# noqa: F401').join ("\n") + "\n\nexchanges",
        }),
        Object.assign ({}, python3, {
            regex: /exchanges \= \[[^\]]+\]/,
            replacement: "exchanges = [\n" + "    '" + ids.join ("',\n    '") + "'," + "\n]",
        }),
        Object.assign ({}, php, {
            regex: /public static \$exchanges \= array\s*\([^\)]+\)/,
            replacement: "public static $exchanges = array(\n        '" + ids.join ("',\n        '") + "',\n    )",
        }),

    ].forEach (({ folder, file, regex, replacement }) => {
        if (folder) {
            logExportExchanges (folder + file, regex, replacement)
        }
    })

    log.bright.green ('Base sources updated successfully.')

    return ids
}

// ----------------------------------------------------------------------------

function createExchanges (ids) {

    const ccxt = require ('../ccxt.js')

    const createExchange = (id) => {
        ccxt[id].prototype.checkRequiredDependencies = () => {} // suppress it
        return new (ccxt)[id] ()
    }

    return ccxt.indexBy (ids.map (createExchange), 'id')
}

// // ----------------------------------------------------------------------------
// // strategically placed exactly here (we can require it AFTER the export)
// const ccxt = require ('../ccxt.js')
// // ----------------------------------------------------------------------------
// // create exchanges
// const createExchange = (id) => {
//     ccxt[id].prototype.checkRequiredDependencies = () => {} // suppress it
//     return new (ccxt)[id] ()
// }
// const exchanges = ccxt.indexBy (ids.map (createExchange), 'id')

// ----------------------------------------------------------------------------
// TODO: REWRITE THIS ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

function exportSupportedAndCertifiedExchanges (exchanges, wikiPath) {

    // ............................................................................
    // markup constants and helper functions

    const countryName = (code) => countries[code] || code

    const ccxtCertifiedBadge = '[![CCXT Certified](https://img.shields.io/badge/CCXT-certified-green.svg)](https://github.com/ccxt/ccxt/wiki/Certification)'
    const logoHeading = ' '.repeat (7) + 'logo' + ' '.repeat (7)
    const tableHeadings = [ logoHeading, 'id', 'name', 'ver', 'doc', 'certified', ]
    const exchangesByCountryHeading = [ 'country / region', ... tableHeadings ]

    // ----------------------------------------------------------------------------
    // list all supported exchanges

    const exchangesNotListedInDocs = []

    let tableData = values (exchanges)
        .filter (exchange => !exchangesNotListedInDocs.includes (exchange.id))
        .map (exchange => {
            let logo = exchange.urls['logo']
            let website = Array.isArray (exchange.urls.www) ? exchange.urls.www[0] : exchange.urls.www
            let url = exchange.urls.referral || website
            let countries = Array.isArray (exchange.countries) ? exchange.countries.map (countryName).join (', ') : countryName (exchange.countries)
            let doc = Array.isArray (exchange.urls.doc) ? exchange.urls.doc[0] : exchange.urls.doc
            let version = exchange.version ? exchange.version : '\*'
            let matches = version.match (/[^0-9]*([0-9].*)/)
            if (matches) {
                version = matches[1];
            }
            return [
                '[![' + exchange.id + '](' + logo + ')](' + url + ')',
                exchange.id,
                '[' + exchange.name + '](' + url + ')',
                version,
                '[API](' + doc + ')',
                exchange.certified ? ccxtCertifiedBadge : '',
                countries,
            ]
        })

    // prepend the table header
    tableData.splice (0, 0, tableHeadings)

    function makeTable (jsonArray) {
        let table = asTable.configure ({ 'delimiter': ' | ' }) (jsonArray)
        let lines = table.split ("\n")
        lines.splice (1,0, lines[0].replace (/[^\|]/g, '-'))
        let headerLine = lines[1].split ('|')
        headerLine[3] = ':' + headerLine[3].slice (1, headerLine[3].length - 1) + ':'
        headerLine[4] = ':' + headerLine[4].slice (1, headerLine[4].length - 1) + ':'
        lines[1] = headerLine.join ('|')
        return lines.map (line => '|' + line + '|').join ("\n")
    }

    const exchangesTable = makeTable (tableData)
    const numExchanges = keys (exchanges).length
    const beginning = "The ccxt library currently supports the following "
    const ending = " cryptocurrency exchange markets and trading APIs:\n\n"
    const totalString = beginning + numExchanges + ending
    const allExchanges = totalString + exchangesTable + "$1"
    const allExchangesRegex = new RegExp ("[^\n]+[\n]{2}\\|[^`]+\\|([\n][\n]|[\n]$|$)", 'm')
    logExportExchanges ('README.md', allExchangesRegex, allExchanges)
    logExportExchanges (wikiPath + '/Manual.md', allExchangesRegex, allExchanges)
    logExportExchanges (wikiPath + '/Exchange-Markets.md', allExchangesRegex, allExchanges)

    const certifiedFieldIndex = tableHeadings.indexOf ('certified')
    const certified = tableData.filter ((x) => x[certifiedFieldIndex] !== '' )
    const certifiedExchangesRegex = new RegExp ("^(## Certified Cryptocurrency Exchanges\n{3})(?:\\|.+\\|$\n)+", 'm')
    const certifiedExchangesTable = makeTable (certified)
    const certifiedExchanges = '$1' + certifiedExchangesTable + "\n"
    logExportExchanges ('README.md', certifiedExchangesRegex, certifiedExchanges)

    let exchangesByCountries = []
    keys (countries).forEach (code => {
        let country = countries[code]
        let result = []
        keys (exchanges).forEach (id => {
            let exchange = exchanges[id]
            let logo = exchange.urls['logo']
            let website = Array.isArray (exchange.urls.www) ? exchange.urls.www[0] : exchange.urls.www
            let url = exchange.urls.referral || website
            let doc = Array.isArray (exchange.urls.doc) ? exchange.urls.doc[0] : exchange.urls.doc
            let version = exchange.version ? exchange.version : '\*'
            let matches = version.match (/[^0-9]*([0-9].*)/)
            if (matches)
                version = matches[1];
            let shouldInclude = false
            if (Array.isArray (exchange.countries)) {
                if (exchange.countries.indexOf (code) > -1)
                    shouldInclude = true
            } else {
                if (code == exchange.countries)
                    shouldInclude = true
            }
            if (shouldInclude) {
                let entry = [
                    country,
                    '[![' + exchange.id + '](' + logo + ')](' + url + ')',
                    exchange.id,
                    '[' + exchange.name + '](' + url + ')',
                    version,
                    '[API](' + doc + ')',
                    // doesn't fit in width
                    // exchange.certified ? ccxtCertifiedBadge : '',
                ]
                result.push (entry)
            }
        })
        exchangesByCountries = exchangesByCountries.concat (result)
    });

    let countryKeyIndex = exchangesByCountryHeading.indexOf ('country / region')
    exchangesByCountries = exchangesByCountries.sort ((a, b) => {
        let countryA = a[countryKeyIndex].toLowerCase ()
        let countryB = b[countryKeyIndex].toLowerCase ()
        if (countryA > countryB) {
            return 1
        } else if (countryA < countryB) {
            return -1;
        } else {
            if (a['id'] > b['id'])
                return 1;
            else if (a['id'] < b['id'])
                return -1;
            else
                return 0;
        }
    })

    exchangesByCountries.splice (0, 0, exchangesByCountryHeading)
    let lines = makeTable (exchangesByCountries)
    let result = "# Exchanges By Country\n\nThe ccxt library currently supports the following cryptocurrency exchange markets and trading APIs:\n\n" + lines + "\n\n"
    let filename = wikiPath + '/Exchange-Markets-By-Country.md'
    fs.truncateSync (filename)
    fs.writeFileSync (filename, result)
}

// TODO: REWRITE THIS ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
// ----------------------------------------------------------------------------

function exportExchangeIdsToExchangesJson (exchanges) {
    log.bright ('Exporting exchange ids to'.cyan, 'exchanges.json'.yellow)
    fs.writeFileSync ('exchanges.json', JSON.stringify ({ ids: keys (exchanges) }, null, 4))
}

// ----------------------------------------------------------------------------

function exportWikiToGitHub (wikiPath, gitWikiPath) {

    log.bright.cyan ('Exporting wiki to GitHub')

    const ccxtWikiFiles = {
        'README.md': 'Home.md',
        'Install.md': 'Install.md',
        'Manual.md': 'Manual.md',
        'Exchange-Markets.md': 'Exchange-Markets.md',
        'Exchange-Markets-By-Country.md': 'Exchange-Markets-By-Country.md',
    }

    for (const [ sourceFile, destinationFile ] of entries (ccxtWikiFiles)) {

        const sourcePath = wikiPath + '/' + sourceFile
        const destinationPath = gitWikiPath + '/' + destinationFile
        log.bright.cyan ('Exporting', sourcePath.yellow, '→', destinationPath.yellow)
        fs.writeFileSync (destinationPath, fs.readFileSync (sourcePath))
    }
}

// ----------------------------------------------------------------------------

function exportKeywordsToPackageJson (exchanges) {

    log.bright ('Exporting exchange keywords to'.cyan, 'package.json'.yellow)

    // const packageJSON = require ('../package.json')
    const packageJSON = JSON.parse (fs.readFileSync ('./package.json'))
    const keywords = new Set (packageJSON.keywords)

    for (const ex of values (exchanges)) {
        for (const url of Array.isArray (ex.urls.www) ? ex.urls.www : [ex.urls.www]) {
            keywords.add (url.replace (/(http|https):\/\/(www\.)?/, '').replace (/\/.*/, ''))
        }
        keywords.add (ex.name)
    }

    packageJSON.keywords = [...keywords]
    fs.writeFileSync ('./package.json', JSON.stringify (packageJSON, null, 2))
}

// ----------------------------------------------------------------------------

function exportEverything () {

    const wikiPath = 'wiki'
        , gitWikiPath = 'build/ccxt.wiki'

    cloneGitHubWiki (gitWikiPath)
    const ids = exportExchanges ({
        js:      { folder: '.', file: '/ccxt.js' },
        python2: { folder: './python/ccxt', file: '/__init__.py' },
        python3: { folder: './python/ccxt/async_support', file: '/__init__.py' },
        php:     { folder: './php', file: '/base/Exchange.php' },
    })

    // strategically placed exactly here (we can require it AFTER the export)
    const exchanges = createExchanges (ids)

    exportSupportedAndCertifiedExchanges (exchanges, wikiPath)
    exportExchangeIdsToExchangesJson (exchanges)
    exportWikiToGitHub (wikiPath, gitWikiPath)
    exportKeywordsToPackageJson (exchanges)

    log.bright.green ('Exported successfully.')
}

// ============================================================================
// main entry point

if (require.main === module) {

    // if called directly like `node module`

    exportEverything ()

} else {

    // do nothing if required as a module
}

// ============================================================================

module.exports = {
    cloneGitHubWiki,
    exportExchanges,
    createExchanges,
    exportSupportedAndCertifiedExchanges,
    exportExchangeIdsToExchangesJson,
    exportWikiToGitHub,
    exportKeywordsToPackageJson,
    exportEverything,
}
<|endoftext|>


<commit_before>/* Search in a bitonic array
 * An array is bitonic if it is comprised of an increasing sequence of integers followed immediately
 * by a decreasing sequence of integers.
 * Write a program that, given a bitonic array of N distinct integer values,
 * determines whether a given integer is in the array.
 *
 * * Standard version - Use ~ 3lgN compares in the worst case
 * * Signing bonus - USe ~2lgN compares in the worst case ( and prove that no algorithm
 * can guarantee to perform fewer than ~2lgN compares in the worst case)
 */

<commit_msg>add bitonic array example<commit_after>/* Search in a bitonic array
 * An array is bitonic if it is comprised of an increasing sequence of integers followed immediately
 * by a decreasing sequence of integers.
 * Write a program that, given a bitonic array of N distinct integer values,
 * determines whether a given integer is in the array.
 *
 * * Standard version - Use ~ 3lgN compares in the worst case
 * * Signing bonus - USe ~2lgN compares in the worst case ( and prove that no algorithm
 * can guarantee to perform fewer than ~2lgN compares in the worst case)
 */

'use strict';

class BinarySearch{
  constructor(){ }
  rank(key, arr){
    // console.log('RANK', key, arr);
    let lo = 0, hi = arr.length-1;
    while (lo <= hi){
      let mid = Math.floor(lo + (hi - lo)/2);
      // console.log('NEW MID', lo, hi, mid);
      if (key > arr[mid]){
        lo = mid + 1;
      } else if (key < arr[mid]){
        hi = mid - 1;
      } else {
        return mid;
      }
    }
    return -1;
  }
};

class AlternateBinarySearch{
  constructor(){ }
  findMax(arr){
    console.log('FIND MAX', arr);
    let lo = 0, hi = arr.length-1;
    while (arr[Math.floor(lo + (hi - lo)/2)] > arr[Math.floor(lo + (hi - lo)/2) - 1]){
      let mid = Math.floor(lo + (hi - lo)/2);
      console.log('MID', mid);
      if (arr[mid] > arr[mid+1] && arr[mid] > arr[mid-1]){
        return mid;
      } else if (arr[mid] < arr[mid-1]){
        hi = mid - 1;
      } else if (arr[mid] < arr[mid-1]){
        lo = mid + 1;
      }
    }
  }
};

let arr = [0, 2, 5, 7, 100, 80, 50, 20, 4, 1];

class Bitonic{
  constructor(arr){
    this.a = arr;
    /*
    for(let i=1; i<arr.length; i++){ // N-1 worst case complexity
      if (arr[i] < arr[i-1]){
        this.mid = i - 1;
        break;
      }
    }
   */
  let ab = new AlternateBinarySearch();
  this.mid = ab.findMax(arr);
  }
  contains(value){
    let b = new BinarySearch();
    // both combined make log N worst case complexity
    let search1 = b.rank(value, this.a.slice(0, this.mid));
    let search2 = b.rank(value, this.a.slice(this.mid).reverse());
    if (search1 == -1 && search2 == -1){
      return false;
    } else {
      return true;
    }
  }
};

let bitonic = new Bitonic(arr);
console.log('INITIAL BITONIC', bitonic);
console.log('HAS 1?', bitonic.contains(1));
console.log('HAS 10?', bitonic.contains(10));
console.log('HAS 7?', bitonic.contains(7));
let abs = new AlternateBinarySearch();
console.log(abs.findMax([1, 35, 80, 70]));
<|endoftext|>