<commit_before>"use strict";

define(['src/options', 'src/schema', 'jquery.qunit'], function (CSLEDIT_options, CSLEDIT_Schema) {
	module("CSLEDIT_schema", {
		setup : function () {
			window.CSLEDIT_schema = new CSLEDIT_Schema();
		},
		teardown : function () {
			delete window.CSLEDIT_schema;
		}
	});

	asyncTest("child elements", function () {
		CSLEDIT_schema.callWhenReady( function () {
			ok("style" in CSLEDIT_schema.childElements("root"));
			ok("locale" in CSLEDIT_schema.childElements("root"));
			ok("info" in CSLEDIT_schema.childElements("root/style"));
			ok("citation" in CSLEDIT_schema.childElements("root/style"));
			ok("bibliography" in CSLEDIT_schema.childElements("root/style"));
			start();
		});
	});

	asyncTest("element type", function () {
		CSLEDIT_schema.callWhenReady( function () {
			equal(CSLEDIT_schema.elementDataType("contributor/uri"), "anyURI");
			equal(CSLEDIT_schema.elementDataType("root/style"), null);
			start();
		});
	});

	asyncTest("attributes", function () {
		CSLEDIT_schema.callWhenReady( function () {
			var styleAttributes = CSLEDIT_schema.attributes("root/style"),
				index;

			ok("default-locale" in styleAttributes);
			equal(styleAttributes["default-locale"].values.length, 1);
			equal(styleAttributes["default-locale"].values[0].type, "data");
			equal(styleAttributes["default-locale"].values[0].value, "language");

			equal(styleAttributes["delimiter-precedes-et-al"].values[0].value, "contextual");
			equal(styleAttributes["delimiter-precedes-et-al"].defaultValue, "contextual");

			ok("font-weight" in CSLEDIT_schema.attributes("layout/text"));
			start();
		});
	});

	asyncTest("list", function () {
		CSLEDIT_schema.callWhenReady( function () {
			equal(CSLEDIT_schema.choices("layout/text")[3].attributes["variable"].list, false);
			equal(CSLEDIT_schema.attributes("choose/if")["variable"].list, true);
			start();
		});
	});

	asyncTest("all data integrity check", function () {
		CSLEDIT_schema.callWhenReady( function () {
			var allData = CSLEDIT_schema.allData(),
				elementName;

			for(elementName in allData) {
				ok(allData[elementName].attributeValues.length <= 1);
			}
			start();
		});
	});

	asyncTest("choices", function () {
		CSLEDIT_schema.callWhenReady( function () {
			equal(CSLEDIT_schema.choices("layout/text").length, 4, "length");
			ok("macro" in CSLEDIT_schema.choices("layout/text")[0].attributes);
			ok("term" in CSLEDIT_schema.choices("layout/text")[1].attributes);
			ok("form" in CSLEDIT_schema.choices("layout/text")[1].attributes);
			ok("plural" in CSLEDIT_schema.choices("layout/text")[1].attributes);
			ok("value" in CSLEDIT_schema.choices("layout/text")[2].attributes);
			ok("variable" in CSLEDIT_schema.choices("layout/text")[3].attributes);
			ok("form" in CSLEDIT_schema.choices("layout/text")[3].attributes);

			// shouldn't have the choices in the normal nodes
			ok(!("macro" in CSLEDIT_schema.attributes("layout/text")));
			start();
		});
	});

	asyncTest("child element quantifiers", function () {
		CSLEDIT_schema.callWhenReady( function () {
			// TODO: get quantifiers working properly

			//equal(CSLEDIT_schema.childElements("layout/choose")['if'], "one");
			equal(CSLEDIT_schema.childElements("layout/choose")['else-if'], "zeroOrMore");
			//equal(CSLEDIT_schema.childElements("layout/choose")['else'], "optional");
			start();
		});
	});
});
<commit_msg>rename schema with capital letter<commit_after>"use strict";

define(['src/options', 'src/Schema', 'jquery.qunit'], function (CSLEDIT_options, CSLEDIT_Schema) {
	module("CSLEDIT_schema", {
		setup : function () {
			window.CSLEDIT_schema = new CSLEDIT_Schema();
		},
		teardown : function () {
			delete window.CSLEDIT_schema;
		}
	});

	asyncTest("child elements", function () {
		CSLEDIT_schema.callWhenReady( function () {
			ok("style" in CSLEDIT_schema.childElements("root"));
			ok("locale" in CSLEDIT_schema.childElements("root"));
			ok("info" in CSLEDIT_schema.childElements("root/style"));
			ok("citation" in CSLEDIT_schema.childElements("root/style"));
			ok("bibliography" in CSLEDIT_schema.childElements("root/style"));
			start();
		});
	});

	asyncTest("element type", function () {
		CSLEDIT_schema.callWhenReady( function () {
			equal(CSLEDIT_schema.elementDataType("contributor/uri"), "anyURI");
			equal(CSLEDIT_schema.elementDataType("root/style"), null);
			start();
		});
	});

	asyncTest("attributes", function () {
		CSLEDIT_schema.callWhenReady( function () {
			var styleAttributes = CSLEDIT_schema.attributes("root/style"),
				index;

			ok("default-locale" in styleAttributes);
			equal(styleAttributes["default-locale"].values.length, 1);
			equal(styleAttributes["default-locale"].values[0].type, "data");
			equal(styleAttributes["default-locale"].values[0].value, "language");

			equal(styleAttributes["delimiter-precedes-et-al"].values[0].value, "contextual");
			equal(styleAttributes["delimiter-precedes-et-al"].defaultValue, "contextual");

			ok("font-weight" in CSLEDIT_schema.attributes("layout/text"));
			start();
		});
	});

	asyncTest("list", function () {
		CSLEDIT_schema.callWhenReady( function () {
			equal(CSLEDIT_schema.choices("layout/text")[3].attributes["variable"].list, false);
			equal(CSLEDIT_schema.attributes("choose/if")["variable"].list, true);
			start();
		});
	});

	asyncTest("all data integrity check", function () {
		CSLEDIT_schema.callWhenReady( function () {
			var allData = CSLEDIT_schema.allData(),
				elementName;

			for(elementName in allData) {
				ok(allData[elementName].attributeValues.length <= 1);
			}
			start();
		});
	});

	asyncTest("choices", function () {
		CSLEDIT_schema.callWhenReady( function () {
			equal(CSLEDIT_schema.choices("layout/text").length, 4, "length");
			ok("macro" in CSLEDIT_schema.choices("layout/text")[0].attributes);
			ok("term" in CSLEDIT_schema.choices("layout/text")[1].attributes);
			ok("form" in CSLEDIT_schema.choices("layout/text")[1].attributes);
			ok("plural" in CSLEDIT_schema.choices("layout/text")[1].attributes);
			ok("value" in CSLEDIT_schema.choices("layout/text")[2].attributes);
			ok("variable" in CSLEDIT_schema.choices("layout/text")[3].attributes);
			ok("form" in CSLEDIT_schema.choices("layout/text")[3].attributes);

			// shouldn't have the choices in the normal nodes
			ok(!("macro" in CSLEDIT_schema.attributes("layout/text")));
			start();
		});
	});

	asyncTest("child element quantifiers", function () {
		CSLEDIT_schema.callWhenReady( function () {
			// TODO: get quantifiers working properly

			//equal(CSLEDIT_schema.childElements("layout/choose")['if'], "one");
			equal(CSLEDIT_schema.childElements("layout/choose")['else-if'], "zeroOrMore");
			//equal(CSLEDIT_schema.childElements("layout/choose")['else'], "optional");
			start();
		});
	});
});
<|endoftext|>


<commit_before>'use strict'

/*
 * adonis-framework
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/

const { ServiceProvider } = require('@adonisjs/fold')

class AppProvider extends ServiceProvider {
  /**
   * Registering the env provider under
   * Adonis/Src/Env namespace.
   *
   * @method _registerEnv
   *
   * @return {void}
   *
   * @private
   */
  _registerEnv () {
    this.app.singleton('Adonis/Src/Env', (app) => {
      const Helpers = app.use('Adonis/Src/Helpers')
      const Env = require('../src/Env')
      return new Env(Helpers.appRoot())
    })
    this.app.alias('Adonis/Src/Env', 'Env')
  }

  /**
   * Registering the config provider under
   * Adonis/Src/Config namespace
   *
   * @method _registerConfig
   *
   * @return {void}
   *
   * @private
   */
  _registerConfig () {
    this.app.singleton('Adonis/Src/Config', (app) => {
      const Helpers = app.use('Adonis/Src/Helpers')
      const Config = require('../src/Config')
      return new Config(Helpers.configPath())
    })
    this.app.alias('Adonis/Src/Config', 'Config')
  }

  /**
   * Registering the request provider under
   * Adonis/Src/Request namespace
   *
   * @method _registerRequest
   *
   * @return {void}
   *
   * @private
   */
  _registerRequest () {
    this.app.bind('Adonis/Src/Request', () => {
      return require('../src/Request')
    })
  }

  /**
   * Registering the response provider under
   * Adonis/Src/Response namespace
   *
   * @method _registerResponse
   *
   * @return {void}
   *
   * @private
   */
  _registerResponse () {
    this.app.bind('Adonis/Src/Response', () => {
      return require('../src/Response')
    })
  }

  /**
   * Registering the route provider under
   * Adonis/Src/Route namespace
   *
   * @method _registerRoute
   *
   * @return {void}
   *
   * @private
   */
  _registerRoute () {
    this.app.singleton('Adonis/Src/Route', () => {
      return require('../src/Route/Manager')
    })
    this.app.alias('Adonis/Src/Route', 'Route')
  }

  /**
   * Registers the logger provider under
   * Adonis/Src/Logger namespace
   *
   * @method _registerLogger
   *
   * @return {void}
   */
  _registerLogger () {
    this.app.singleton('Adonis/Src/Logger', (app) => {
      const LoggerManager = require('../src/Logger/Manager')
      return new LoggerManager(app.use('Adonis/Src/Config'))
    })
    this.app.alias('Adonis/Src/Logger', 'Logger')
  }

  /**
   * Register the server provider under
   * Adonis/Src/Server namespace.
   *
   * @method _registerServer
   *
   * @return {void}
   *
   * @private
   */
  _registerServer () {
    this.app.singleton('Adonis/Src/Server', (app) => {
      const Context = app.use('Adonis/Src/Context')
      const Route = app.use('Adonis/Src/Route')
      const Exception = app.use('Adonis/Src/Exception')
      const Logger = app.use('Adonis/Src/Logger')
      const Server = require('../src/Server')
      return new Server(Context, Route, Logger, Exception)
    })
    this.app.alias('Adonis/Src/Server', 'Server')
  }

  /**
   * Registers the hash provider
   *
   * @method _registerHash
   *
   * @return {void}
   *
   * @private
   */
  _registerHash () {
    this.app.singleton('Adonis/Src/Hash', () => {
      return require('../src/Hash')
    })
    this.app.alias('Adonis/Src/Hash', 'Hash')
  }

  /**
   * Register the context provider
   *
   * @method _registerContext
   *
   * @return {void}
   *
   * @private
   */
  _registerContext () {
    this.app.bind('Adonis/Src/Context', () => {
      return require('../src/Context')
    })
    this.app.alias('Adonis/Src/Context', 'Context')
  }

  /**
   * Register the static resource middleware provider
   *
   * @method _registerStaticMiddleware
   *
   * @return {void}
   *
   * @private
   */
  _registerStaticMiddleware () {
    this.app.bind('Adonis/Middleware/Static', (app) => {
      const Static = require('../src/Static')
      return Static(app.use('Adonis/Src/Helpers'), app.use('Adonis/Src/Config'))
    })
  }

  /**
   * Registers the exceptions provider
   *
   * @method _registerException
   *
   * @return {void}
   */
  _registerException () {
    this.app.singleton('Adonis/Src/Exception', () => {
      return require('../src/Exception')
    })
    this.app.alias('Adonis/Src/Exception', 'Exception')
  }

  /**
   * Register the exception handler
   *
   * @method _registerExceptionHandler
   *
   * @return {void}
   *
   * @private
   */
  _registerExceptionHandler () {
    this.app.bind('Adonis/Exceptions/Handler', () => {
      return new (require('../src/App/Handler'))
    })
  }

  /**
   * Register the encryption provider
   *
   * @method _registerEncryption
   *
   * @return {void}
   */
  _registerEncryption () {
    this.app.singleton('Adonis/Src/Encryption', (app) => {
      const Encryption = require('../src/Encryption')
      return new Encryption(app.use('Adonis/Src/Config'))
    })
    this.app.alias('Adonis/Src/Encryption', 'Encryption')
  }

  /**
   * Registers the event provider under `Adonis/Src/Event`
   * namespace.
   *
   * @method _registerEvent
   *
   * @return {void}
   */
  _registerEvent () {
    this.app.singleton('Adonis/Src/Event', (app) => {
      const Event = require('../src/Event')
      return new Event(app.use('Adonis/Src/Config'))
    })
    this.app.alias('Adonis/Src/Event', 'Event')
  }

  /**
   * Register all the required providers
   *
   * @method register
   *
   * @return {void}
   */
  register () {
    this._registerEnv()
    this._registerConfig()
    this._registerContext()
    this._registerRequest()
    this._registerResponse()
    this._registerRoute()
    this._registerLogger()
    this._registerServer()
    this._registerHash()
    this._registerException()
    this._registerExceptionHandler()
    this._registerEncryption()
    this._registerStaticMiddleware()
    this._registerEvent()
  }

  /**
   * The boot method called by Ioc container to
   * boot the providers
   *
   * @method boot
   *
   * @return {void}
   */
  boot () {
    const Context = this.app.use('Adonis/Src/Context')
    const Request = this.app.use('Adonis/Src/Request')
    const Response = this.app.use('Adonis/Src/Response')

    Context.getter('request', function () {
      return new Request(this.req, this.res, use('Adonis/Src/Config'))
    }, true)

    Context.getter('response', function () {
      return new Response(this.req, this.res)
    }, true)
  }
}

module.exports = AppProvider
<commit_msg>style(lint): fix linting errors<commit_after>'use strict'

/*
 * adonis-framework
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/

const { ServiceProvider } = require('@adonisjs/fold')

class AppProvider extends ServiceProvider {
  /**
   * Registering the env provider under
   * Adonis/Src/Env namespace.
   *
   * @method _registerEnv
   *
   * @return {void}
   *
   * @private
   */
  _registerEnv () {
    this.app.singleton('Adonis/Src/Env', (app) => {
      const Helpers = app.use('Adonis/Src/Helpers')
      const Env = require('../src/Env')
      return new Env(Helpers.appRoot())
    })
    this.app.alias('Adonis/Src/Env', 'Env')
  }

  /**
   * Registering the config provider under
   * Adonis/Src/Config namespace
   *
   * @method _registerConfig
   *
   * @return {void}
   *
   * @private
   */
  _registerConfig () {
    this.app.singleton('Adonis/Src/Config', (app) => {
      const Helpers = app.use('Adonis/Src/Helpers')
      const Config = require('../src/Config')
      return new Config(Helpers.configPath())
    })
    this.app.alias('Adonis/Src/Config', 'Config')
  }

  /**
   * Registering the request provider under
   * Adonis/Src/Request namespace
   *
   * @method _registerRequest
   *
   * @return {void}
   *
   * @private
   */
  _registerRequest () {
    this.app.bind('Adonis/Src/Request', () => {
      return require('../src/Request')
    })
  }

  /**
   * Registering the response provider under
   * Adonis/Src/Response namespace
   *
   * @method _registerResponse
   *
   * @return {void}
   *
   * @private
   */
  _registerResponse () {
    this.app.bind('Adonis/Src/Response', () => {
      return require('../src/Response')
    })
  }

  /**
   * Registering the route provider under
   * Adonis/Src/Route namespace
   *
   * @method _registerRoute
   *
   * @return {void}
   *
   * @private
   */
  _registerRoute () {
    this.app.singleton('Adonis/Src/Route', () => {
      return require('../src/Route/Manager')
    })
    this.app.alias('Adonis/Src/Route', 'Route')
  }

  /**
   * Registers the logger provider under
   * Adonis/Src/Logger namespace
   *
   * @method _registerLogger
   *
   * @return {void}
   */
  _registerLogger () {
    this.app.singleton('Adonis/Src/Logger', (app) => {
      const LoggerManager = require('../src/Logger/Manager')
      return new LoggerManager(app.use('Adonis/Src/Config'))
    })
    this.app.alias('Adonis/Src/Logger', 'Logger')
  }

  /**
   * Register the server provider under
   * Adonis/Src/Server namespace.
   *
   * @method _registerServer
   *
   * @return {void}
   *
   * @private
   */
  _registerServer () {
    this.app.singleton('Adonis/Src/Server', (app) => {
      const Context = app.use('Adonis/Src/Context')
      const Route = app.use('Adonis/Src/Route')
      const Exception = app.use('Adonis/Src/Exception')
      const Logger = app.use('Adonis/Src/Logger')
      const Server = require('../src/Server')
      return new Server(Context, Route, Logger, Exception)
    })
    this.app.alias('Adonis/Src/Server', 'Server')
  }

  /**
   * Registers the hash provider
   *
   * @method _registerHash
   *
   * @return {void}
   *
   * @private
   */
  _registerHash () {
    this.app.singleton('Adonis/Src/Hash', () => {
      return require('../src/Hash')
    })
    this.app.alias('Adonis/Src/Hash', 'Hash')
  }

  /**
   * Register the context provider
   *
   * @method _registerContext
   *
   * @return {void}
   *
   * @private
   */
  _registerContext () {
    this.app.bind('Adonis/Src/Context', () => {
      return require('../src/Context')
    })
    this.app.alias('Adonis/Src/Context', 'Context')
  }

  /**
   * Register the static resource middleware provider
   *
   * @method _registerStaticMiddleware
   *
   * @return {void}
   *
   * @private
   */
  _registerStaticMiddleware () {
    this.app.bind('Adonis/Middleware/Static', (app) => {
      const Static = require('../src/Static')
      return Static(app.use('Adonis/Src/Helpers'), app.use('Adonis/Src/Config'))
    })
  }

  /**
   * Registers the exceptions provider
   *
   * @method _registerException
   *
   * @return {void}
   */
  _registerException () {
    this.app.singleton('Adonis/Src/Exception', () => {
      return require('../src/Exception')
    })
    this.app.alias('Adonis/Src/Exception', 'Exception')
  }

  /**
   * Register the exception handler
   *
   * @method _registerExceptionHandler
   *
   * @return {void}
   *
   * @private
   */
  _registerExceptionHandler () {
    this.app.bind('Adonis/Exceptions/Handler', () => {
      return new (require('../src/App/Handler'))()
    })
  }

  /**
   * Register the encryption provider
   *
   * @method _registerEncryption
   *
   * @return {void}
   */
  _registerEncryption () {
    this.app.singleton('Adonis/Src/Encryption', (app) => {
      const Encryption = require('../src/Encryption')
      return new Encryption(app.use('Adonis/Src/Config'))
    })
    this.app.alias('Adonis/Src/Encryption', 'Encryption')
  }

  /**
   * Registers the event provider under `Adonis/Src/Event`
   * namespace.
   *
   * @method _registerEvent
   *
   * @return {void}
   */
  _registerEvent () {
    this.app.singleton('Adonis/Src/Event', (app) => {
      const Event = require('../src/Event')
      return new Event(app.use('Adonis/Src/Config'))
    })
    this.app.alias('Adonis/Src/Event', 'Event')
  }

  /**
   * Register all the required providers
   *
   * @method register
   *
   * @return {void}
   */
  register () {
    this._registerEnv()
    this._registerConfig()
    this._registerContext()
    this._registerRequest()
    this._registerResponse()
    this._registerRoute()
    this._registerLogger()
    this._registerServer()
    this._registerHash()
    this._registerException()
    this._registerExceptionHandler()
    this._registerEncryption()
    this._registerStaticMiddleware()
    this._registerEvent()
  }

  /**
   * The boot method called by Ioc container to
   * boot the providers
   *
   * @method boot
   *
   * @return {void}
   */
  boot () {
    const Context = this.app.use('Adonis/Src/Context')
    const Request = this.app.use('Adonis/Src/Request')
    const Response = this.app.use('Adonis/Src/Response')

    Context.getter('request', function () {
      return new Request(this.req, this.res, use('Adonis/Src/Config'))
    }, true)

    Context.getter('response', function () {
      return new Response(this.req, this.res)
    }, true)
  }
}

module.exports = AppProvider
<|endoftext|>


<commit_before>/*
 * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var Transform = require('stream').Transform;
var debug = require('debug')('signalk:n2kAnalyzer');

function N2KAnalyzer() {
  Transform.call(this, {
    objectMode: true
  });

  this.analyzerProcess = require('child_process').spawn('sh', ['-c', 'analyzer -json']);
  this.analyzerProcess.stderr.on('data', function(data) {
    console.error(data.toString());
  });
  this.analyzerProcess.on('close', function(code) {
    console.error('Analyzer process exited with code ' + code);
  });

  this.linereader = require('readline').createInterface(this.analyzerProcess.stdout, this.analyzerProcess.stdin);
  var that = this;
  this.linereader.on('line', function(data) {
    try {
      that.push(JSON.parse(data));
    } catch (ex) {
      console.error(ex.stack);
    }
  });
}

require('util').inherits(N2KAnalyzer, Transform);

N2KAnalyzer.prototype._transform = function(chunk, encoding, done) {
  var data = chunk.toString();
  this.analyzerProcess.stdin.write(chunk.toString() + '\n');
  done();
}
N2KAnalyzer.prototype.pipe = function(pipeTo) {
  this.pipeTo = pipeTo;
  N2KAnalyzer.super_.prototype.pipe.call(this, pipeTo);
}

N2KAnalyzer.prototype.end = function() {
  debug('end, killing child analyzer process');
  this.analyzerProcess.kill();
  this.pipeTo.end();
}

module.exports = N2KAnalyzer;<commit_msg>Use analyzer -si to produce SI units<commit_after>/*
 * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var Transform = require('stream').Transform;
var debug = require('debug')('signalk:n2kAnalyzer');

function N2KAnalyzer() {
  Transform.call(this, {
    objectMode: true
  });

  this.analyzerProcess = require('child_process').spawn('sh', ['-c', 'analyzer -json -si']);
  this.analyzerProcess.stderr.on('data', function(data) {
    console.error(data.toString());
  });
  this.analyzerProcess.on('close', function(code) {
    console.error('Analyzer process exited with code ' + code);
  });

  this.linereader = require('readline').createInterface(this.analyzerProcess.stdout, this.analyzerProcess.stdin);
  var that = this;
  this.linereader.on('line', function(data) {
    try {
      that.push(JSON.parse(data));
    } catch (ex) {
      console.error(ex.stack);
    }
  });
}

require('util').inherits(N2KAnalyzer, Transform);

N2KAnalyzer.prototype._transform = function(chunk, encoding, done) {
  var data = chunk.toString();
  this.analyzerProcess.stdin.write(chunk.toString() + '\n');
  done();
}
N2KAnalyzer.prototype.pipe = function(pipeTo) {
  this.pipeTo = pipeTo;
  N2KAnalyzer.super_.prototype.pipe.call(this, pipeTo);
}

N2KAnalyzer.prototype.end = function() {
  debug('end, killing child analyzer process');
  this.analyzerProcess.kill();
  this.pipeTo.end();
}

module.exports = N2KAnalyzer;<|endoftext|>


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

/**
 * Returns a list of font names used across all pages in a story.
 *
 * @param {Array<import('../types').Page>} pages List of pages.
 *
 * @return {Array<string>} Font names.
 */
export function getInUseFontsForPages(pages) {
  return [
    ...new Set(
      pages
        .reduce((storyMemo, { elements = [] }) => {
          return [
            ...storyMemo,
            ...elements.reduce((pageMemo, element) => {
              if (element.type === 'text' && Boolean(element.font?.family)) {
                return [...pageMemo, element.font?.family];
              }
              return pageMemo;
            }, []),
          ];
        }, [])
        .filter(Boolean)
    ),
  ];
}

/**
 * Returns a list of text sets that include the fonts provided in the options object.
 *
 * @param {Array<Object>} options Object containing an array of fonts and text sets to filter.
 *
 * @return {Array<Object>} List of text sets that match the array of fonts.
 */
export function getTextSetsForFonts({ fonts, textSets }) {
  return textSets
    .reduce((textSetMemo, currentTextSet) => {
      const hasFontInUse = currentTextSet.reduce(
        (elementMemo, currentElement) => {
          if (
            currentElement.type === 'text' &&
            Boolean(currentElement.font?.family)
          ) {
            return (
              elementMemo | (fonts.indexOf(currentElement.font?.family) !== -1)
            );
          }
          return elementMemo;
        },
        false
      );
      return [...textSetMemo, hasFontInUse && currentTextSet];
    }, [])
    .filter(Boolean);
}
<commit_msg>Cleaned up util functions to reduce the usage of reduce.<commit_after>/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Returns a list of font names used across all pages in a story.
 *
 * @param {Array<import('../types').Page>} pages List of pages.
 *
 * @return {Array<string>} Font names.
 */
export function getInUseFontsForPages(pages) {
  return (
    Array.from(
      new Set(
        pages
          .map(({ elements = [] }) =>
            elements.map((element) => {
              if (element.type === 'text' && Boolean(element.font?.family)) {
                return element.font?.family;
              }
              return null;
            })
          )
          .flat()
          .filter(Boolean)
      )
    ) || []
  );
}

/**
 * Returns a list of text sets that include the fonts provided in the options object.
 *
 * @param {Array<Object>} options Object containing an array of fonts and text sets to filter.
 *
 * @return {Array<Object>} List of text sets that match the array of fonts.
 */
export function getTextSetsForFonts({ fonts, textSets }) {
  return textSets
    .map((currentTextSet) => {
      const hasFontInUse = currentTextSet.reduce(
        (elementMemo, currentElement) => {
          if (
            currentElement.type === 'text' &&
            Boolean(currentElement.font?.family)
          ) {
            return (
              elementMemo | (fonts.indexOf(currentElement.font?.family) !== -1)
            );
          }
          return elementMemo;
        },
        false
      );
      return hasFontInUse && currentTextSet;
    })
    .filter(Boolean);
}
<|endoftext|>


<commit_before>'use strict'

import * as input from '../input/input.js'

import * as timerView from './timerView.js'

let timerActive = false
let timerID = 0

export const Timer = ({
startTime = new Date().getTime(),
// Multiplying inputs to convert minutes to seconds:
pomodoro = input.userInputs.pomodoroLength * 60,
shortBreak = input.userInputs.shortBreakLength * 60,
longBreak = input.userInputs.longBreakLength * 60,
pomodoroCount = 0,
currentActivity = 'pomodoro',
// Converting seconds to milliseconds for comparing with Date.getTime()
endTime = startTime + (pomodoro * 1000),
timeLeft = pomodoro
} = {}) => ({
  startTime,
  pomodoro,
  shortBreak,
  longBreak,
  pomodoroCount,
  currentActivity,
  endTime,
  timeLeft
})

export function toggleTimer (timer = Timer(), display = timerView.TimerView()) {
  if (timerActive === true) {
    clearTimeout(timerID)
    timerActive = false
    timerView.updateTimerView()
  } else {
    timerID = setTimeout(checkTimer, 1000, timer, display)
    timerActive = true
    timerView.updateTimerView(display)
  }
}

export function checkTimer (timerToCheck, display) {
  let currentTime = new Date().getTime()
  timerToCheck.timeLeft--
  timerView.updateTimerView(timerView.TimerView({
    title: display.title,
    time: timerToCheck.timeLeft
  }))
  if (currentTime >= timerToCheck.endTime) {
    timerActive = false
    finishTimer(timerToCheck)
  } else {
    timerID = setTimeout(checkTimer, 1000, timerToCheck, display)
  }
}

export function finishTimer (previousTimer) {
  if (document.getElementById('alarm') !== null) {
    let alarm = document.getElementById('alarm')
    alarm.play()
  }
  if (previousTimer.currentActivity === 'pomodoro' && previousTimer.pomodoroCount < 3) {
    let newEndtime = new Date().getTime() + (previousTimer.shortBreak * 1000)
    let newTimeLeft = previousTimer.shortBreak
    notify('You finished! Good work! Take a short break, you deserve it', 'Short Break Started')
    toggleTimer(Timer({
      pomodoroCount: previousTimer.pomodoroCount + 1,
      currentActivity: 'shortBreak',
      endTime: newEndtime,
      timeLeft: newTimeLeft
    }), timerView.TimerView({
      title: 'Short Break',
      time: previousTimer.shortBreak
    }))
  } else if (previousTimer.currentActivity === 'pomodoro' && previousTimer.pomodoroCount >= 3) {
    let newEndtime = new Date().getTime() + (previousTimer.longBreak * 1000)
    let newTimeLeft = previousTimer.longBreak
    notify('Four in a row! Awesome! Take a long one, dude.', 'Long Break Started')
    toggleTimer(Timer({
      pomodoroCount: 0,
      currentActivity: 'longBreak',
      endTime: newEndtime,
      timeLeft: newTimeLeft
    }), timerView.TimerView({
      title: 'Long Break',
      time: previousTimer.longBreak
    }))
  } else {
    // Using previousTimer.pomodoro so that changing input values doesn't change the timer while it's running
    let newEndtime = new Date().getTime() + (previousTimer.pomodoro * 1000)
    notify('Recharged a bit? Good! Pick something new and go get \'em!', 'Pomodoro Started')
    toggleTimer(Timer({ // timeLeft and currentActivity left out so that it uses the default value
      pomodoroCount: previousTimer.pomodoroCount,
      endTime: newEndtime
    }))
  }
}

export function notify (theBody, theTitle) {
  let options = {
    body: theBody
  }
  let n = new Notification(theTitle, options)
  // close the notification for browsers who don't close it automatically
  setTimeout(n.close.bind(n), 10000)

  n.onclick = function (event) {
    if (document.getElementById('alarm') !== null) {
      let alarm = document.getElementById('alarm')
      alarm.pause()
    }
  }
}
<commit_msg>Timer object parameters for timer lengths now default to the input element values<commit_after>'use strict'

import * as input from '../input/input.js'

import * as timerView from './timerView.js'

let timerActive = false
let timerID = 0

export const Timer = ({
startTime = new Date().getTime(),
// Multiplying inputs to convert minutes to seconds:
pomodoro = document.getElementById('pomodoroInput').value * 60,
shortBreak = document.getElementById('shortBreakInput').value * 60,
longBreak = document.getElementById('longBreakInput').value * 60,
pomodoroCount = 0,
currentActivity = 'pomodoro',
// Converting seconds to milliseconds for comparing with Date.getTime()
endTime = startTime + (pomodoro * 1000),
timeLeft = pomodoro
} = {}) => ({
  startTime,
  pomodoro,
  shortBreak,
  longBreak,
  pomodoroCount,
  currentActivity,
  endTime,
  timeLeft
})

export function toggleTimer (timer = Timer(), display = timerView.TimerView()) {
  if (timerActive === true) {
    clearTimeout(timerID)
    timerActive = false
    timerView.updateTimerView()
  } else {
    timerID = setTimeout(checkTimer, 1000, timer, display)
    timerActive = true
    timerView.updateTimerView(display)
  }
}

export function checkTimer (timerToCheck, display) {
  let currentTime = new Date().getTime()
  timerToCheck.timeLeft--
  timerView.updateTimerView(timerView.TimerView({
    title: display.title,
    time: timerToCheck.timeLeft
  }))
  if (currentTime >= timerToCheck.endTime) {
    timerActive = false
    finishTimer(timerToCheck)
  } else {
    timerID = setTimeout(checkTimer, 1000, timerToCheck, display)
  }
}

export function finishTimer (previousTimer) {
  if (document.getElementById('alarm') !== null) {
    let alarm = document.getElementById('alarm')
    alarm.play()
  }
  if (previousTimer.currentActivity === 'pomodoro' && previousTimer.pomodoroCount < 3) {
    let newEndtime = new Date().getTime() + (previousTimer.shortBreak * 1000)
    let newTimeLeft = previousTimer.shortBreak
    notify('You finished! Good work! Take a short break, you deserve it', 'Short Break Started')
    toggleTimer(Timer({
      pomodoroCount: previousTimer.pomodoroCount + 1,
      currentActivity: 'shortBreak',
      endTime: newEndtime,
      timeLeft: newTimeLeft
    }), timerView.TimerView({
      title: 'Short Break',
      time: previousTimer.shortBreak
    }))
  } else if (previousTimer.currentActivity === 'pomodoro' && previousTimer.pomodoroCount >= 3) {
    let newEndtime = new Date().getTime() + (previousTimer.longBreak * 1000)
    let newTimeLeft = previousTimer.longBreak
    notify('Four in a row! Awesome! Take a long one, dude.', 'Long Break Started')
    toggleTimer(Timer({
      pomodoroCount: 0,
      currentActivity: 'longBreak',
      endTime: newEndtime,
      timeLeft: newTimeLeft
    }), timerView.TimerView({
      title: 'Long Break',
      time: previousTimer.longBreak
    }))
  } else {
    // Using previousTimer.pomodoro so that changing input values doesn't change the timer while it's running
    let newEndtime = new Date().getTime() + (previousTimer.pomodoro * 1000)
    notify('Recharged a bit? Good! Pick something new and go get \'em!', 'Pomodoro Started')
    toggleTimer(Timer({ // timeLeft and currentActivity left out so that it uses the default value
      pomodoroCount: previousTimer.pomodoroCount,
      endTime: newEndtime
    }))
  }
}

export function notify (theBody, theTitle) {
  let options = {
    body: theBody
  }
  let n = new Notification(theTitle, options)
  // close the notification for browsers who don't close it automatically
  setTimeout(n.close.bind(n), 10000)

  n.onclick = function (event) {
    if (document.getElementById('alarm') !== null) {
      let alarm = document.getElementById('alarm')
      alarm.pause()
    }
  }
}
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Service.extend({
  sitemapEntryFilter: null,
  dynamicSegmentResolver: null,
  rootUrl: null,
  allRoutes: null,

  init() {
    this._super(...arguments);

    const envSettings = Ember.getOwner(this).resolveRegistration('config:environment');
    if (envSettings) {
      this.setSettings(envSettings.sitemap);
    }

    const router = Ember.getOwner(this).lookup('router:main');
    const allRoutes = router.get('_routerMicrolib.recognizer.names');
    if (allRoutes) {
      this.setRoutes(allRoutes);
    }
  },

  setSettings: function(settings) {
    if (settings) {
      if ('rootUrl' in settings) {
        this.set('rootUrl', settings.rootUrl);
      }
    }
  },

  setRoutes: function(allRoutes) {
    this.set('allRoutes', allRoutes);
  },

  setSitemapEntryFilter: function(sitemapEntryFilter) {
    this.set('sitemapEntryFilter', sitemapEntryFilter);
  },

  setDynamicSegmentResolver: function(dynamicSegmentResolver) {
    this.set('dynamicSegmentResolver', dynamicSegmentResolver);
  },

  getModel() {
    this._validate();

    const sitemapEntriesPromise = this._routesToSitemapEntries(this.get('allRoutes'));

    return sitemapEntriesPromise;
  },

  _validate() {
    if (!this.get('rootUrl')) {
      throw new Error(`sitemap.rootUrl is required`);
    }
    if (!this.get('allRoutes')) {
      throw new Error(`allRoutes are required`);
    }
  },

  _routesToSitemapEntries(routes) {
    const ignore = [
      'error',
      'loading',
      'application',
      'sitemap-txt',
      'sitemap-xml',
    ];

    let sitemapEntriesPromise = Promise.resolve([]);

    Object.keys(routes).forEach((key) => {
      if (ignore.find(ignoredKey => key.indexOf(ignoredKey) > -1)) {
        return;
      }

      const dynamicSegmentsKeys = this._routeToDynamicSegments(routes[key]);

      sitemapEntriesPromise = sitemapEntriesPromise.then((entries) => {
        if (dynamicSegmentsKeys.length === 0) { // No dynamic segments in route
          return this._filterSitemapEntry(
              { loc: this._routeToPath(routes[key]) },
              this._routeToSegments(routes[key])
            )
            .then(entry => entry ? [...entries, entry] : entries);
        } else {
          return this._dynamicSegmentsToPermutations(
            dynamicSegmentsKeys, this._routeToSegments(routes[key])
          ).then((permutations) => {
            let permutationsPromise = Promise.resolve(entries);

            permutations.forEach((permutation) => {
              permutationsPromise = permutationsPromise.then((entries) =>
                this._filterSitemapEntry(
                  { loc: this._routeToPath(routes[key], permutation) },
                  this._routeToSegments(routes[key]),
                  permutation
                )
                .then(entry => entry ? [...entries, entry] : entries)
              );
            });

            return permutationsPromise;
          });
        }
      });
    });

    return sitemapEntriesPromise
      .then(entries =>
        // Remove duplications caused by indexes
        this._removeDuplicateEntries(entries)
      )
      .then(entries =>
        // Map entry.loc from relative paths to absolute URLs
        entries.map((entry) => {
          entry.loc = this._relativeToAbsoluteUrl(entry.loc);
          return entry;
        })
      );
  },

  _filterSitemapEntry(entry, segments, dynamicSegments) {
    const sitemapEntryFilter = this.get('sitemapEntryFilter');

    const result = sitemapEntryFilter ? sitemapEntryFilter(entry, segments, dynamicSegments) : entry;

    return Promise.resolve(result);
  },

  _routeToSegments(route) {
    return route.segments
      .filter(segment => [0, 1].includes(segment.type))
      .map(({type, value}) => (type === 1) ? `:${value}` : value); // Prefix dynamic segments with colon
  },

  _relativeToAbsoluteUrl(relativeUrl) {
    return this.get('rootUrl') + relativeUrl;
  },

  _removeDuplicateEntries(entries) {
    const newEntries = [];
    entries.forEach((entry) => {
      if (!newEntries.find(newEntry => newEntry.loc === entry.loc)) {
        newEntries.push(entry);
      }
    });
    return newEntries;
  },

  _routeToPath(route, dynamicSegments) {
    return route.segments
      .filter(segment => segment.type === 0 || segment.type === 1)
      .map(segment => {
        if (segment.type === 0) { // static
          return segment.value;
        } else if (segment.type === 1) { // dynamic
          if (segment.value in dynamicSegments) {
            return dynamicSegments[segment.value];
          } else {
            throw new Error(`The value for dynamic segment '${segment.value}' is not set.`);
          }
        }
      })
      .join('/');
  },

  _routeToDynamicSegments(route) {
    return route.segments
      .filter(segment => segment.type === 1)
      .map(segment => segment.value);
  },

  _resolveDynamicSegment(dynamicSegmentKey, allSegments, otherDynamicSegments) {
    const dynamicSegmentResolver = this.get('dynamicSegmentResolver');

    if (!dynamicSegmentResolver) {
      throw new Error('dynamicSegmentResolver is required but is not set.');
    }

    const result = dynamicSegmentResolver(dynamicSegmentKey, allSegments, otherDynamicSegments);

    return Promise.resolve(result)
      .then(values => {
        if (!Array.isArray(values)) {
          throw new Error(`The dynamic segment resolver returned a '${typeof values}'` +
          ` instead of an array for '${dynamicSegmentKey}'.`);
        }

        return values;
      });
  },

  _dynamicSegmentsToPermutations(dynamicSegmentsKeys, segments, permutation = {}) {
    if (dynamicSegmentsKeys.length === 0) {
      return Promise.resolve([]);
    }

    const firstDynamicSegmentKey = dynamicSegmentsKeys[0];
    const remainingDynamicSegmentsKeys = dynamicSegmentsKeys.slice(1);

    return this._resolveDynamicSegment(firstDynamicSegmentKey, segments, permutation)
      .then((firstDynamicSegmentValues) => {
        const firstDynamicSegmentPermutations = firstDynamicSegmentValues.map(val => ({
          [firstDynamicSegmentKey]: val,
        }));

        let permutationsPromise = Promise.resolve([]);

        firstDynamicSegmentPermutations.forEach((firstDynamicSegmentPermutation) => {
          permutationsPromise = permutationsPromise.then(permutations => {
            if (remainingDynamicSegmentsKeys.length > 0) {
              return this._dynamicSegmentsToPermutations(
                remainingDynamicSegmentsKeys,
                segments,
                Object.assign({}, permutation, firstDynamicSegmentPermutation)
              ).then((remainingDynamicSegmentsPermutations) => {
                if (remainingDynamicSegmentsPermutations.length > 0) {
                  remainingDynamicSegmentsPermutations.forEach(remainingDynamicSegmentsPermutation => {
                    permutations.push(Object.assign({}, firstDynamicSegmentPermutation, remainingDynamicSegmentsPermutation));
                  });
                } else {
                  permutations = [];
                }
                return permutations;
              })
            } else {
              permutations.push(firstDynamicSegmentPermutation);
              return permutations;
            }
          })
        });

        return permutationsPromise;
      });
  },
});
<commit_msg>dynamicSegments should never be null in _filterSitemapEntry<commit_after>import Ember from 'ember';

export default Ember.Service.extend({
  sitemapEntryFilter: null,
  dynamicSegmentResolver: null,
  rootUrl: null,
  allRoutes: null,

  init() {
    this._super(...arguments);

    const envSettings = Ember.getOwner(this).resolveRegistration('config:environment');
    if (envSettings) {
      this.setSettings(envSettings.sitemap);
    }

    const router = Ember.getOwner(this).lookup('router:main');
    const allRoutes = router.get('_routerMicrolib.recognizer.names');
    if (allRoutes) {
      this.setRoutes(allRoutes);
    }
  },

  setSettings: function(settings) {
    if (settings) {
      if ('rootUrl' in settings) {
        this.set('rootUrl', settings.rootUrl);
      }
    }
  },

  setRoutes: function(allRoutes) {
    this.set('allRoutes', allRoutes);
  },

  setSitemapEntryFilter: function(sitemapEntryFilter) {
    this.set('sitemapEntryFilter', sitemapEntryFilter);
  },

  setDynamicSegmentResolver: function(dynamicSegmentResolver) {
    this.set('dynamicSegmentResolver', dynamicSegmentResolver);
  },

  getModel() {
    this._validate();

    const sitemapEntriesPromise = this._routesToSitemapEntries(this.get('allRoutes'));

    return sitemapEntriesPromise;
  },

  _validate() {
    if (!this.get('rootUrl')) {
      throw new Error(`sitemap.rootUrl is required`);
    }
    if (!this.get('allRoutes')) {
      throw new Error(`allRoutes are required`);
    }
  },

  _routesToSitemapEntries(routes) {
    const ignore = [
      'error',
      'loading',
      'application',
      'sitemap-txt',
      'sitemap-xml',
    ];

    let sitemapEntriesPromise = Promise.resolve([]);

    Object.keys(routes).forEach((key) => {
      if (ignore.find(ignoredKey => key.indexOf(ignoredKey) > -1)) {
        return;
      }

      const dynamicSegmentsKeys = this._routeToDynamicSegments(routes[key]);

      sitemapEntriesPromise = sitemapEntriesPromise.then((entries) => {
        if (dynamicSegmentsKeys.length === 0) { // No dynamic segments in route
          return this._filterSitemapEntry(
              { loc: this._routeToPath(routes[key]) },
              this._routeToSegments(routes[key])
            )
            .then(entry => entry ? [...entries, entry] : entries);
        } else {
          return this._dynamicSegmentsToPermutations(
            dynamicSegmentsKeys, this._routeToSegments(routes[key])
          ).then((permutations) => {
            let permutationsPromise = Promise.resolve(entries);

            permutations.forEach((permutation) => {
              permutationsPromise = permutationsPromise.then((entries) =>
                this._filterSitemapEntry(
                  { loc: this._routeToPath(routes[key], permutation) },
                  this._routeToSegments(routes[key]),
                  permutation
                )
                .then(entry => entry ? [...entries, entry] : entries)
              );
            });

            return permutationsPromise;
          });
        }
      });
    });

    return sitemapEntriesPromise
      .then(entries =>
        // Remove duplications caused by indexes
        this._removeDuplicateEntries(entries)
      )
      .then(entries =>
        // Map entry.loc from relative paths to absolute URLs
        entries.map((entry) => {
          entry.loc = this._relativeToAbsoluteUrl(entry.loc);
          return entry;
        })
      );
  },

  _filterSitemapEntry(entry, segments, dynamicSegments = {}) {
    const sitemapEntryFilter = this.get('sitemapEntryFilter');

    const result = sitemapEntryFilter ? sitemapEntryFilter(entry, segments, dynamicSegments) : entry;

    return Promise.resolve(result);
  },

  _routeToSegments(route) {
    return route.segments
      .filter(segment => [0, 1].includes(segment.type))
      .map(({type, value}) => (type === 1) ? `:${value}` : value); // Prefix dynamic segments with colon
  },

  _relativeToAbsoluteUrl(relativeUrl) {
    return this.get('rootUrl') + relativeUrl;
  },

  _removeDuplicateEntries(entries) {
    const newEntries = [];
    entries.forEach((entry) => {
      if (!newEntries.find(newEntry => newEntry.loc === entry.loc)) {
        newEntries.push(entry);
      }
    });
    return newEntries;
  },

  _routeToPath(route, dynamicSegments) {
    return route.segments
      .filter(segment => segment.type === 0 || segment.type === 1)
      .map(segment => {
        if (segment.type === 0) { // static
          return segment.value;
        } else if (segment.type === 1) { // dynamic
          if (segment.value in dynamicSegments) {
            return dynamicSegments[segment.value];
          } else {
            throw new Error(`The value for dynamic segment '${segment.value}' is not set.`);
          }
        }
      })
      .join('/');
  },

  _routeToDynamicSegments(route) {
    return route.segments
      .filter(segment => segment.type === 1)
      .map(segment => segment.value);
  },

  _resolveDynamicSegment(dynamicSegmentKey, allSegments, otherDynamicSegments) {
    const dynamicSegmentResolver = this.get('dynamicSegmentResolver');

    if (!dynamicSegmentResolver) {
      throw new Error('dynamicSegmentResolver is required but is not set.');
    }

    const result = dynamicSegmentResolver(dynamicSegmentKey, allSegments, otherDynamicSegments);

    return Promise.resolve(result)
      .then(values => {
        if (!Array.isArray(values)) {
          throw new Error(`The dynamic segment resolver returned a '${typeof values}'` +
          ` instead of an array for '${dynamicSegmentKey}'.`);
        }

        return values;
      });
  },

  _dynamicSegmentsToPermutations(dynamicSegmentsKeys, segments, permutation = {}) {
    if (dynamicSegmentsKeys.length === 0) {
      return Promise.resolve([]);
    }

    const firstDynamicSegmentKey = dynamicSegmentsKeys[0];
    const remainingDynamicSegmentsKeys = dynamicSegmentsKeys.slice(1);

    return this._resolveDynamicSegment(firstDynamicSegmentKey, segments, permutation)
      .then((firstDynamicSegmentValues) => {
        const firstDynamicSegmentPermutations = firstDynamicSegmentValues.map(val => ({
          [firstDynamicSegmentKey]: val,
        }));

        let permutationsPromise = Promise.resolve([]);

        firstDynamicSegmentPermutations.forEach((firstDynamicSegmentPermutation) => {
          permutationsPromise = permutationsPromise.then(permutations => {
            if (remainingDynamicSegmentsKeys.length > 0) {
              return this._dynamicSegmentsToPermutations(
                remainingDynamicSegmentsKeys,
                segments,
                Object.assign({}, permutation, firstDynamicSegmentPermutation)
              ).then((remainingDynamicSegmentsPermutations) => {
                if (remainingDynamicSegmentsPermutations.length > 0) {
                  remainingDynamicSegmentsPermutations.forEach(remainingDynamicSegmentsPermutation => {
                    permutations.push(Object.assign({}, firstDynamicSegmentPermutation, remainingDynamicSegmentsPermutation));
                  });
                } else {
                  permutations = [];
                }
                return permutations;
              })
            } else {
              permutations.push(firstDynamicSegmentPermutation);
              return permutations;
            }
          })
        });

        return permutationsPromise;
      });
  },
});
<|endoftext|>


<commit_before>o2.xDesktop.requireApp("process.Xform", "$Elinput", null, false);
/** @class Eldate 基于Element UI的日期选择组件。
 * @o2cn 日期选择
 * @example
 * //可以在脚本中获取该组件
 * //方法1：
 * var input = this.form.get("name"); //获取组件
 * //方法2
 * var input = this.target; //在组件事件脚本中获取
 * @extends MWF.xApplication.process.Xform.$Module
 * @o2category FormComponents
 * @o2range {Process|CMS|Portal}
 * @hideconstructor
 * @see {@link https://element.eleme.cn/#/zh-CN/component/date-picker|Element UI DatePicker 日期选择器}
 */
MWF.xApplication.process.Xform.Eldate = MWF.APPEldate =  new Class(
    /** @lends o2.xApplication.process.Xform.Eldate# */
    {
    Implements: [Events],
    Extends: MWF.APP$Elinput,
    options: {
        "moduleEvents": ["load", "queryLoad", "postLoad"],
        /**
         * 当 input 失去焦点时触发。this.event[0]指向组件实例
         * @event MWF.xApplication.process.Xform.Eldate#blur
         * @see {@link https://element.eleme.cn/#/zh-CN/component/date-picker|日期选择组件的Events章节}
         */
        /**
         * 当 input 获得焦点时触发。this.event[0]指向组件实例
         * @event MWF.xApplication.process.Xform.Eldate#focus
         * @see {@link https://element.eleme.cn/#/zh-CN/component/date-picker|日期选择组件的Events章节}
         */
        /**
         * 用户确认选定的值时触发。this.event[0]为组件绑定值；格式与绑定值一致，可受 value-format 控制
         * @event MWF.xApplication.process.Xform.Eldate#change
         * @see {@link https://element.eleme.cn/#/zh-CN/component/date-picker|日期选择组件的Events章节}
         */
        "elEvents": ["focus", "blur", "change"]
    },
    _queryLoaded: function(){
        var data = this._getBusinessData();
        if( ["monthrange","daterange"].contains(this.json.selectType) ) {
            if (typeOf(data) === "string") this._setBusinessData([data, ""]);
        }else if( ["dates"].contains(this.json.selectType) ){
            if (typeOf(data) === "string") this._setBusinessData([data]);
        }else{
            if( typeOf(data) === "array" )this._setBusinessData(data[0] || "");
        }
    },
    _appendVueData: function(){
        if (!this.json.isReadonly) this.json.isReadonly = false;
        if (!this.json.disabled) this.json.disabled = false;
        if (!this.json.clearable) this.json.clearable = false;
        if (!this.json.disabled) this.json.disabled = false;
        if (!this.json.editable) this.json.editable = false;
        if (!this.json.size) this.json.size = "";
        if (!this.json.prefixIcon) this.json.prefixIcon = "";
        if (!this.json.description) this.json.description = "";
        this.json.pickerOptions = {
            firstDayOfWeek: this.json.firstDayOfWeek.toInt()
        }
        if (this.json.disabledDate && this.json.disabledDate.code){
            this.json.pickerOptions.disabledDate = function(date){
                return this.form.Macro.fire(this.json.disabledDate.code, this, date);
            }.bind(this)
        }
    },
    _createElementHtml: function() {
        var html = "<el-date-picker";
        html += " v-model=\""+this.json.$id+"\"";
        html += " :type=\"selectType\"";
        html += " :readonly=\"isReadonly\"";
        html += " :disabled=\"disabled\"";
        html += " :editable=\"editable\"";
        html += " :clearable=\"clearable\"";
        html += " :size=\"size\"";
        html += " :prefix-icon=\"prefixIcon\"";
        html += " :range-separator=\"rangeSeparator\"";
        html += " :start-placeholder=\"startPlaceholder\"";
        html += " :end-placeholder=\"endPlaceholder\"";
        html += " :value-format=\"format\"";
        html += " :format=\"format\"";
        html += " :picker-options=\"pickerOptions\"";
        // html += " :picker-options=\"{" +
            // ":firstDayOfWeek=firstDayOfWeek," +
            // ":disabledDate=\"disabledDateFun\""+
            // "}\"";

        this.options.elEvents.forEach(function(k){
            html += " @"+k+"=\"$loadElEvent_"+k.camelCase()+"\"";
        });

        if (this.json.elProperties){
            Object.keys(this.json.elProperties).forEach(function(k){
                if (this.json.elProperties[k]) html += " "+k+"=\""+this.json.elProperties[k]+"\"";
            }, this);
        }

        if (this.json.elStyles) html += " :style=\"elStyles\"";

        html += ">";

        if (this.json.vueSlot) html += this.json.vueSlot;

        html += "</el-date-picker>";
        return html;
    }
});
<commit_msg>修复ElementUI的date组件bug<commit_after>o2.xDesktop.requireApp("process.Xform", "$Elinput", null, false);
/** @class Eldate 基于Element UI的日期选择组件。
 * @o2cn 日期选择
 * @example
 * //可以在脚本中获取该组件
 * //方法1：
 * var input = this.form.get("name"); //获取组件
 * //方法2
 * var input = this.target; //在组件事件脚本中获取
 * @extends MWF.xApplication.process.Xform.$Module
 * @o2category FormComponents
 * @o2range {Process|CMS|Portal}
 * @hideconstructor
 * @see {@link https://element.eleme.cn/#/zh-CN/component/date-picker|Element UI DatePicker 日期选择器}
 */
MWF.xApplication.process.Xform.Eldate = MWF.APPEldate =  new Class(
    /** @lends o2.xApplication.process.Xform.Eldate# */
    {
    Implements: [Events],
    Extends: MWF.APP$Elinput,
    options: {
        "moduleEvents": ["load", "queryLoad", "postLoad"],
        /**
         * 当 input 失去焦点时触发。this.event[0]指向组件实例
         * @event MWF.xApplication.process.Xform.Eldate#blur
         * @see {@link https://element.eleme.cn/#/zh-CN/component/date-picker|日期选择组件的Events章节}
         */
        /**
         * 当 input 获得焦点时触发。this.event[0]指向组件实例
         * @event MWF.xApplication.process.Xform.Eldate#focus
         * @see {@link https://element.eleme.cn/#/zh-CN/component/date-picker|日期选择组件的Events章节}
         */
        /**
         * 用户确认选定的值时触发。this.event[0]为组件绑定值；格式与绑定值一致，可受 value-format 控制
         * @event MWF.xApplication.process.Xform.Eldate#change
         * @see {@link https://element.eleme.cn/#/zh-CN/component/date-picker|日期选择组件的Events章节}
         */
        "elEvents": ["focus", "blur", "change"]
    },
    _queryLoaded: function(){
        var data = this._getBusinessData();
        if (data){
            if( ["monthrange","daterange"].contains(this.json.selectType) ) {
                if (typeOf(data) === "string") this._setBusinessData([data, ""]);
            }else if( ["dates"].contains(this.json.selectType) ){
                if (typeOf(data) === "string") this._setBusinessData([data]);
            }else{
                if( typeOf(data) === "array" )this._setBusinessData(data[0] || "");
            }
        }
    },
    _appendVueData: function(){
        if (!this.json.isReadonly) this.json.isReadonly = false;
        if (!this.json.disabled) this.json.disabled = false;
        if (!this.json.clearable) this.json.clearable = false;
        if (!this.json.disabled) this.json.disabled = false;
        if (!this.json.editable) this.json.editable = false;
        if (!this.json.size) this.json.size = "";
        if (!this.json.prefixIcon) this.json.prefixIcon = "";
        if (!this.json.description) this.json.description = "";
        this.json.pickerOptions = {
            firstDayOfWeek: this.json.firstDayOfWeek.toInt()
        }
        if (this.json.disabledDate && this.json.disabledDate.code){
            this.json.pickerOptions.disabledDate = function(date){
                return this.form.Macro.fire(this.json.disabledDate.code, this, date);
            }.bind(this)
        }
    },
    _createElementHtml: function() {
        var html = "<el-date-picker";
        html += " v-model=\""+this.json.$id+"\"";
        html += " :type=\"selectType\"";
        html += " :readonly=\"isReadonly\"";
        html += " :disabled=\"disabled\"";
        html += " :editable=\"editable\"";
        html += " :clearable=\"clearable\"";
        html += " :size=\"size\"";
        html += " :prefix-icon=\"prefixIcon\"";
        html += " :range-separator=\"rangeSeparator\"";
        html += " :start-placeholder=\"startPlaceholder\"";
        html += " :end-placeholder=\"endPlaceholder\"";
        html += " :value-format=\"format\"";
        html += " :format=\"format\"";
        html += " :picker-options=\"pickerOptions\"";
        // html += " :picker-options=\"{" +
            // ":firstDayOfWeek=firstDayOfWeek," +
            // ":disabledDate=\"disabledDateFun\""+
            // "}\"";

        this.options.elEvents.forEach(function(k){
            html += " @"+k+"=\"$loadElEvent_"+k.camelCase()+"\"";
        });

        if (this.json.elProperties){
            Object.keys(this.json.elProperties).forEach(function(k){
                if (this.json.elProperties[k]) html += " "+k+"=\""+this.json.elProperties[k]+"\"";
            }, this);
        }

        if (this.json.elStyles) html += " :style=\"elStyles\"";

        html += ">";

        if (this.json.vueSlot) html += this.json.vueSlot;

        html += "</el-date-picker>";
        return html;
    }
});
<|endoftext|>


<commit_before>'use strict';

var LoginPage = require('../pages/login_page.js');
var LogoutPage = require('../pages/logout_page.js');
var data = require('../fixtures/test_data.json');
var OrgPage = require('../pages/organization_page');
var UserSourcePage = require('../pages/user_source_page');

describe('OCL User Source Page', function () {
    var loginPage;
    var logoutPage;
    var orgPage;
    var usrSrcPage;
    var srcShortCode = '';

     beforeEach(function () {
        loginPage = new LoginPage();
        logoutPage = new LogoutPage();
         orgPage = new OrgPage();
         usrSrcPage = new UserSourcePage();
    });

    it('should login', function () {
        loginPage.visit();
        loginPage.login(data.username,data.password);

        expect((loginPage.loginStatus).getText()).toEqual('Successfully signed in as awadhwa1.');
    });

    it('should create source', function () {
        srcShortCode = orgPage.getRandomString(5);
        usrSrcPage.createNewUsrSource(data.src_code+srcShortCode,
            data.src_full_name,
            data.supported_locale
        );

        expect((orgPage.status).getText()).toEqual('Source created');
    });

    it('should create concept', function () {
        orgPage.createNewConcept( data.concept_id,
            data.concept_name,
            data.name_type
        );

        expect((orgPage.status).getText()).toEqual('Concept created.');

        element(by.linkText('  '+data.src_code+srcShortCode)).click();
    });

    it('should create source version', function () {
        orgPage.createNewSourceVersion(data.id,
            data.description
        );

        expect((orgPage.status).getText()).toEqual('Source version created!');
    });

    it('should logout', function () {
         logoutPage.logout();

        expect((loginPage.loginStatus).getText()).toEqual('You have signed out.');
    });
});
<commit_msg>Added e2e tests for release / un-release user source version<commit_after>'use strict';

var LoginPage = require('../pages/login_page.js');
var LogoutPage = require('../pages/logout_page.js');
var data = require('../fixtures/test_data.json');
var OrgPage = require('../pages/organization_page');
var UserSourcePage = require('../pages/user_source_page');

describe('OCL User Source Page', function () {
    var loginPage;
    var logoutPage;
    var orgPage;
    var usrSrcPage;
    var srcShortCode = '';

     beforeEach(function () {
        loginPage = new LoginPage();
        logoutPage = new LogoutPage();
         orgPage = new OrgPage();
         usrSrcPage = new UserSourcePage();
    });

    it('should login', function () {
        loginPage.visit();
        loginPage.login(data.username,data.password);

        expect((loginPage.loginStatus).getText()).toEqual('Successfully signed in as awadhwa1.');
    });

    it('should create source', function () {
        srcShortCode = orgPage.getRandomString(5);
        usrSrcPage.createNewUsrSource(data.src_code+srcShortCode,
            data.src_full_name,
            data.supported_locale
        );

        expect((orgPage.status).getText()).toEqual('Source created');
    });

    it('should create concept', function () {
        orgPage.createNewConcept( data.concept_id,
            data.concept_name,
            data.name_type
        );

        expect((orgPage.status).getText()).toEqual('Concept created.');

        element(by.linkText('  '+data.src_code+srcShortCode)).click();
    });

    it('should create source version', function () {
        orgPage.createNewSourceVersion(data.id,
            data.description
        );

        expect((orgPage.status).getText()).toEqual('Source version created!');
    });

    it('should release a user source version', function () {
        orgPage.releaseVersion();

        expect(orgPage.releaseLabel.getText()).toEqual('Released');
        expect(orgPage.message.getText()).toEqual('Successfully Released.');

        browser.sleep('500');
        orgPage.message.click();
        browser.sleep('750');
    });

    it('should un-release a user source version', function () {
        orgPage.releaseVersion();

        expect(orgPage.message.getText()).toEqual('Successfully Un-Released.');

        browser.sleep('500');
        orgPage.message.click();
        browser.sleep('500');
    });

    it('should logout', function () {
         logoutPage.logout();

        expect((loginPage.loginStatus).getText()).toEqual('You have signed out.');
    });
});
<|endoftext|>


<commit_before>function NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel) {
    var self = this;

    self.loginState = loginStateViewModel;
    self.appearance = appearanceViewModel;
    self.systemActions = settingsViewModel.system_actions;
    self.users = usersViewModel;

    self.triggerAction = function(action) {
        var callback = function() {
            $.ajax({
                url: AJAX_BASEURL + "system",
                type: "POST",
                dataType: "json",
                data: "action=" + action.action,
                success: function() {
                    $.pnotify({title: "Success", text: "The command \""+ action.name +"\" executed successfully", type: "success"});
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    $.pnotify({title: "Error", text: "
The command \"" + action.name + "\" could not be executed.

Reason:
" + jqXHR.responseText + "

", type: "error"});
                }
            })
        }
        if (action.confirm) {
            $("#confirmation_dialog .confirmation_dialog_message").text(action.confirm);
            $("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {e.preventDefault(); $("#confirmation_dialog").modal("hide"); callback(); });
            $("#confirmation_dialog").modal("show");
        } else {
            callback();
        }
    }
}

<commit_msg>Unbind old click handlers from confirmation dialog before use.<commit_after>function NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel) {
    var self = this;

    self.loginState = loginStateViewModel;
    self.appearance = appearanceViewModel;
    self.systemActions = settingsViewModel.system_actions;
    self.users = usersViewModel;

    self.triggerAction = function(action) {
        var callback = function() {
            $.ajax({
                url: AJAX_BASEURL + "system",
                type: "POST",
                dataType: "json",
                data: "action=" + action.action,
                success: function() {
                    $.pnotify({title: "Success", text: "The command \""+ action.name +"\" executed successfully", type: "success"});
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    $.pnotify({title: "Error", text: "
The command \"" + action.name + "\" could not be executed.

Reason:
" + jqXHR.responseText + "

", type: "error"});
                }
            })
        }
        if (action.confirm) {
            $("#confirmation_dialog .confirmation_dialog_message").text(action.confirm);
            $("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click");
            $("#confirmation_dialog .confirmation_dialog_acknowledge").bind("click", function(e) {
                e.preventDefault();
                $("#confirmation_dialog").modal("hide");
                callback();
            });
            $("#confirmation_dialog").modal("show");
        } else {
            callback();
        }
    }
}

<|endoftext|>


<commit_before>!function(root, name, make) {
  if (typeof module != 'undefined' && module.exports) module.exports = make()
  else root[name] = make()
}(this, 'cueing', function() {

  var model = cueing.prototype = Cueing.prototype = []

  /**
   * @param {number|{length:number}} pool items or length
   * @return {Cueing}
   */
  function cueing(pool) {
    return new Cueing(pool)
  }

  /**
   * @constructor
   * @param {number|{length:number}|Cueing} pool length or items
   */
  function Cueing(pool) {
    if (typeof pool == 'number') pool = new Array(pool)
    for (var i = 0, l = pool && pool.length; i < l;) this[i] = pool[i++]
    this.length = i || +pool || 0
    this._needle = 0
    this._recall = []
  }

  /**
   * @param {number|{length:number}} pool
   * @param {(number|Number|Cueing)=} current index (+/-)
   * @param {(number|Number|Cueing)=} next offset (+/-)
   * @return {number} index
   */
  cueing.cue = function(pool, current, next) {
    if (typeof pool != 'number') pool = +pool.length
    if (0 >= pool) return -1
    current = +current || 0
    if (0 > current) current += pool
    next = +next
    if (!next) return current
    next += current
    if (next >= pool) next = next % pool
    else if (0 > next) next = next % pool + pool
    return next === next ? next : -1
  }

  /**
   * @param {{length:number}} pool
   * @param {(number|Number|Cueing)=} current index (+/-)
   * @param {(number|Number|Cueing)=} next offset (+/-)
   * @return {*} value
   */
  cueing.seek = function(pool, current, next) {
    return pool[cueing.cue(pool, current, next)]
  }

  /**
   * @param {Array} array
   * @param {number} point
   * @return {Array}
   */
  cueing.store = function(array, point) {
    if (null == point) throw new TypeError
    if (array[array.length - 1] !== point) array.push(point)
    return array
  }

  /**
   * @this {Cueing} instance to clone
   * @return {Cueing} clone
   */
  model.clone = function() {
    var clone = cueing(this).needle(this._needle)
    clone.push.apply(clone._recall, this._recall)
    return clone
  }

  /**
   * @this {Cueing}
   * @param {(number|Number|Cueing)=} index to manually move the needle to
   * @return {Cueing} object with updated needle position
   */
  model.needle = function(index) {
    if (null != index) this._needle = +index || 0
    return this
  }

  /**
   * @this {Cueing} object with memory to store to
   * @return {Cueing}
   */
  model.store = function() {
    cueing.store(this._recall, this._needle)
    return this
  }

  /**
   * @this {Cueing} object with memory to clear
   * @return {Cueing} object with memory cleared
   */
  model.clear = function() {
    this._recall.length = 0
    return this
  }

  /**
   * @this {Cueing} object to recall from
   * @param {(number|Number|Cueing)=} index (+/-) of the cue point to recall
   * @return {Cueing} object at recalled state
   */
  model.recall = function(index) {
    if (null == index) return cueing(this._recall)
    return this.needle(cueing.seek(this._recall, index))
  }

  /**
   * @this {Cueing}
   * @param {(number|Number|Cueing)=} offset (+/-)
   * @return {Cueing} object cued to offset
   */
  model.cue = function(offset) {
    return this.needle(cueing.cue(this, this._needle, offset))
  }

  /**
   * @this {Cueing}
   * @param {(number|Number|Cueing)=} offset (+/-)
   * @return {*} value
   */
  model.seek = function(offset) {
    return this[this.cue(offset)]
  }

  /**
   * @this {Cueing}
   * @return {string} index
   */
  model.toString = function() {
    return '' + this._needle
  }

  return cueing
});
<commit_msg>precheck length<commit_after>!function(root, name, make) {
  if (typeof module != 'undefined' && module.exports) module.exports = make()
  else root[name] = make()
}(this, 'cueing', function() {

  var model = cueing.prototype = Cueing.prototype = []

  /**
   * @param {number|{length:number}} pool items or length
   * @return {Cueing}
   */
  function cueing(pool) {
    return new Cueing(pool)
  }

  /**
   * @constructor
   * @param {number|{length:number}|Cueing} pool length or items
   */
  function Cueing(pool) {
    if (typeof pool == 'number') pool = new Array(pool)
    for (var i = 0, l = pool && pool.length; i < l;) this[i] = pool[i++]
    this.length = i || +pool || 0
    this._needle = 0
    this._recall = []
  }

  /**
   * @param {number|{length:number}} pool
   * @param {(number|Number|Cueing)=} current index (+/-)
   * @param {(number|Number|Cueing)=} next offset (+/-)
   * @return {number} index
   */
  cueing.cue = function(pool, current, next) {
    if (typeof pool != 'number') pool = +pool.length
    if (0 >= pool) return -1
    current = +current || 0
    if (0 > current) current += pool
    next = +next
    if (!next) return current
    next += current
    if (next >= pool) next = next % pool
    else if (0 > next) next = next % pool + pool
    return next === next ? next : -1
  }

  /**
   * @param {{length:number}} pool
   * @param {(number|Number|Cueing)=} current index (+/-)
   * @param {(number|Number|Cueing)=} next offset (+/-)
   * @return {*} value
   */
  cueing.seek = function(pool, current, next) {
    return pool[cueing.cue(pool, current, next)]
  }

  /**
   * @param {Array} array
   * @param {number} point
   * @return {Array}
   */
  cueing.store = function(array, point) {
    if (null == point) throw new TypeError
    var length = array.length
    if (!length || array[length - 1] !== point) array.push(point)
    return array
  }

  /**
   * @this {Cueing} instance to clone
   * @return {Cueing} clone
   */
  model.clone = function() {
    var clone = cueing(this).needle(this._needle)
    clone.push.apply(clone._recall, this._recall)
    return clone
  }

  /**
   * @this {Cueing}
   * @param {(number|Number|Cueing)=} index to manually move the needle to
   * @return {Cueing} object with updated needle position
   */
  model.needle = function(index) {
    if (null != index) this._needle = +index || 0
    return this
  }

  /**
   * @this {Cueing} object with memory to store to
   * @return {Cueing}
   */
  model.store = function() {
    cueing.store(this._recall, this._needle)
    return this
  }

  /**
   * @this {Cueing} object with memory to clear
   * @return {Cueing} object with memory cleared
   */
  model.clear = function() {
    this._recall.length = 0
    return this
  }

  /**
   * @this {Cueing} object to recall from
   * @param {(number|Number|Cueing)=} index (+/-) of the cue point to recall
   * @return {Cueing} object at recalled state
   */
  model.recall = function(index) {
    if (null == index) return cueing(this._recall)
    return this.needle(cueing.seek(this._recall, index))
  }

  /**
   * @this {Cueing}
   * @param {(number|Number|Cueing)=} offset (+/-)
   * @return {Cueing} object cued to offset
   */
  model.cue = function(offset) {
    return this.needle(cueing.cue(this, this._needle, offset))
  }

  /**
   * @this {Cueing}
   * @param {(number|Number|Cueing)=} offset (+/-)
   * @return {*} value
   */
  model.seek = function(offset) {
    return this[this.cue(offset)]
  }

  /**
   * @this {Cueing}
   * @return {string} index
   */
  model.toString = function() {
    return '' + this._needle
  }

  return cueing
});
<|endoftext|>


<commit_before>var vmModule = require("./main-view-model");
var platformModule = require("platform");

function pageLoaded(args) {
    page = args.object;
    page.bindingContext = vmModule.mainViewModel;

    var placeholder = page.getViewById("bannerView");
    var bannerView;

    if(platformModule.device.os == "iOS") {
        bannerView = placeholder.ios;
        bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716";
        bannerView.strongDelegateRef = bannerView.delegate = GADBannerViewDelegateImpl.new().initWithOwner(this);
        bannerView.rootViewController = page.ios;
        var request = GADRequest.request();
        request.testDevices = [kGADSimulatorID];
        bannerView.loadRequest(request);
    }
    else {
		bannerView = placeholder.android;
		bannerView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");

		var MyAdListener = com.google.android.gms.ads.AdListener.extend(
		{
			onAdLeftApplication: function() {
				// do sth as the user is leaving the app, because of a clicked ad
				console.log("Leaving the app, bye bye!");
			}
		});
		var listener = new MyAdListener();
		bannerView.setAdListener(listener);

		var adRequest = new com.google.android.gms.ads.AdRequest.Builder();
		adRequest.addTestDevice(com.google.android.gms.ads.AdRequest.DEVICE_ID_EMULATOR);
		var requestBuild = adRequest.build();
		bannerView.loadAd(requestBuild);
	}
}

function creatingView(args) {
    if(platformModule.device.os == "iOS") {
        bannerView = GADBannerView.alloc().initWithAdSize(kGADAdSizeSmartBannerPortrait);
        args.view = bannerView;
    }
    else {
		bannerView = new com.google.android.gms.ads.AdView(args.object._context);
		bannerView.setAdSize(com.google.android.gms.ads.AdSize.SMART_BANNER);
		args.view = bannerView;
	}
}

if(platformModule.device.os == "iOS") {
    var GADBannerViewDelegateImpl = (function (_super) {
        __extends(GADBannerViewDelegateImpl, _super);
        function GADBannerViewDelegateImpl() {
            _super.apply(this, arguments);
        }
        GADBannerViewDelegateImpl.new = function () {
            return _super.new.call(this);
        };
        GADBannerViewDelegateImpl.prototype.initWithOwner = function (owner) {
            this._owner = owner;
            return this;
        };
        GADBannerViewDelegateImpl.prototype.adViewWillLeaveApplication = function (bannerView) {
            // do sth as the user is leaving the app, because of a clicked ad
            console.log("Leaving the app, bye bye!");
        };
        GADBannerViewDelegateImpl.ObjCProtocols = [GADBannerViewDelegate];
        return GADBannerViewDelegateImpl;
    })(NSObject);
}

exports.pageLoaded = pageLoaded;
exports.creatingView = creatingView;<commit_msg>update<commit_after>var vmModule = require("./main-view-model");
var platformModule = require("platform");

function pageLoaded(args) {
    var page = args.object;
    page.bindingContext = vmModule.mainViewModel;

    var placeholder = page.getViewById("bannerView");
    var bannerView;

    if(platformModule.device.os == "iOS") {
        bannerView = placeholder.ios;
        bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716";
        bannerView.strongDelegateRef = bannerView.delegate = GADBannerViewDelegateImpl.new().initWithOwner(this);
        bannerView.rootViewController = page.ios;
        var request = GADRequest.request();
        request.testDevices = [kGADSimulatorID];
        bannerView.loadRequest(request);
    }
    else {
		bannerView = placeholder.android;
		bannerView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");

		var MyAdListener = com.google.android.gms.ads.AdListener.extend(
		{
			onAdLeftApplication: function() {
				// do sth as the user is leaving the app, because of a clicked ad
				console.log("Leaving the app, bye bye!");
			}
		});
		var listener = new MyAdListener();
		bannerView.setAdListener(listener);

		var adRequest = new com.google.android.gms.ads.AdRequest.Builder();
		adRequest.addTestDevice(com.google.android.gms.ads.AdRequest.DEVICE_ID_EMULATOR);
		var requestBuild = adRequest.build();
		bannerView.loadAd(requestBuild);
	}
}

function creatingView(args) {
    if(platformModule.device.os == "iOS") {
        bannerView = GADBannerView.alloc().initWithAdSize(kGADAdSizeSmartBannerPortrait);
        args.view = bannerView;
    }
    else {
		var bannerView = new com.google.android.gms.ads.AdView(args.object._context);
		bannerView.setAdSize(com.google.android.gms.ads.AdSize.SMART_BANNER);
		args.view = bannerView;
	}
}

if(platformModule.device.os == "iOS") {
    var GADBannerViewDelegateImpl = (function (_super) {
        __extends(GADBannerViewDelegateImpl, _super);
        function GADBannerViewDelegateImpl() {
            _super.apply(this, arguments);
        }
        GADBannerViewDelegateImpl.new = function () {
            return _super.new.call(this);
        };
        GADBannerViewDelegateImpl.prototype.initWithOwner = function (owner) {
            this._owner = owner;
            return this;
        };
        GADBannerViewDelegateImpl.prototype.adViewWillLeaveApplication = function (bannerView) {
            // do sth as the user is leaving the app, because of a clicked ad
            console.log("Leaving the app, bye bye!");
        };
        GADBannerViewDelegateImpl.ObjCProtocols = [GADBannerViewDelegate];
        return GADBannerViewDelegateImpl;
    })(NSObject);
}

exports.pageLoaded = pageLoaded;
exports.creatingView = creatingView;<|endoftext|>


<commit_before>"use strict";

var fs = require("fs");

/** Loads the template. */
function get(filename, callback) {
    fs.readFile(filename, { encoding: "utf8" }, function(err, data) {
        if (err) callback(err, null);

        try {
            var compiled = compile(data);
        }
        catch (err) {
            callback(err, null);
        }

        var filenameCompiled = filename + ".js";

        fs.writeFile(filenameCompiled, compiled, function(err) {
            if (err) callback(err, null);

            // @todo change to non-blocking require
            var template = require(filenameCompiled);
            callback(null, template);
        });
    });
}

var TokenizerStatus = {
    ECHO: {},
    MAYBE_CONTROL: {},
    CONTROL: {},
    CONTROL_QUOTES_DOUBLE: {},
    CONTROL_QUOTES_SINGLE: {},
    CONTROL_IDENTFR_FIRST: {},
    CONTROL_IDENTFR_NEXT: {},
    CONTROL_IDENTFR_DOT: {},
    COMMENT: {},
    COMMENT_MAYBE_END: {}
};

var TokenType = {
    ECHO: { name: "echo" },
    CONTROL: { name: "control" }
};

/** Token object. */
function Token(type, content) {
    this.type = type;
    this.content = content;
}

/** Structure for parser data. */
function Tokenizer(template) {
    // @todo skip BOM
    var status = TokenizerStatus.ECHO;
    var pos = 0;
    var length = template.length;
    var tokenReturned = false;
    var tokenLength = 0;
    var tokenStart;

    // status variables for control token
    var braces = 0;
    var quotesEscape = false;
    var identifierStatus = 0;

    this.nextToken = function() {
        tokenStart = pos;

        while (pos < length + 1) {
            var c = pos < length ? template.charAt(pos++) : (pos++, -1);

            switch (status) {
            case TokenizerStatus.ECHO:
                if (c === -1) {
                    if (tokenLength) return new Token(TokenType.ECHO, template.substr(tokenStart, tokenLength));
                }

                // opening brace => could mean some dynamic content
                if (c === "{") status = TokenizerStatus.MAYBE_CONTROL;
                tokenLength++;
                break;

            case TokenizerStatus.MAYBE_CONTROL:
                if (c === -1) {
                    // always at least "{" character
                    return new Token(TokenType.ECHO, template.substr(tokenStart, tokenLength));
                }

                // whitespace or } => continue with static content
                if (c === " " || c === "\f" || c === "\n" || c === "\r" || c === "\t" || c === "}") {
                    status = TokenizerStatus.ECHO;
                    tokenLength++;
                }
                else { // start a control token or a comment
                    // return the previous echo token, if it isn't empty
                    if (tokenLength > 1) {
                        if (!tokenReturned) {
                            pos--; tokenReturned = true;
                            return new Token(TokenType.ECHO, template.substr(tokenStart, tokenLength - 1)); // without {
                        }
                        tokenReturned = false;
                    }

                    if (c !== "*") {
                        status = TokenizerStatus.CONTROL;

                        // include current character
                        tokenStart = pos - 1;
                        tokenLength = 1;

                        braces = (c === "{") ? 2 : 1;

                        if (c === "\"") status = TokenizerStatus.CONTROL_QUOTES_DOUBLE;
                        else if (c === "\'") status = TokenizerStatus.CONTROL_QUOTES_SINGLE;
                    }
                    else {
                        status = TokenizerStatus.COMMENT;
                    }
                }
                break;

            case TokenizerStatus.CONTROL:
                if (c === -1) {
                    throw {}; // @todo throw something better!
                }

                // closing brace => return the token
                if (c === "}" && braces === 1) {
                    if (!tokenReturned) {
                        pos--; tokenReturned = true;
                        return new Token(TokenType.CONTROL, template.substr(tokenStart, tokenLength));
                    }
                    tokenReturned = false;

                    status = TokenizerStatus.ECHO;
                    tokenStart++;
                    tokenLength = 0;
                    braces = 0;
                }
                else { // other characters => continue...
                    // @todo check for } in quotes
                    tokenLength++;
                    if (c === "{") braces++;
                    else if (c === "}") braces--;
                    else if (c === "\"") status = TokenizerStatus.CONTROL_QUOTES_DOUBLE;
                    else if (c === "\'") status = TokenizerStatus.CONTROL_QUOTES_SINGLE;
                }
                break;

            case TokenizerStatus.CONTROL_QUOTES_DOUBLE:
                if (c === -1) {
                    throw {}; // @todo throw something better!
                }

                tokenLength++;

                if (c === "\\") {
                    quotesEscape = !quotesEscape;
                }
                else {
                    if (c === "\"" && !quotesEscape) status = TokenizerStatus.CONTROL;
                    quotesEscape = false;
                }
                break;

            case TokenizerStatus.CONTROL_QUOTES_SINGLE:
                if (c === -1) {
                    throw {}; // @todo throw something better!
                }

                tokenLength++;

                if (c === "\\") {
                    quotesEscape = !quotesEscape;
                }
                else {
                    if (c === "'" && !quotesEscape) status = TokenizerStatus.CONTROL;
                    quotesEscape = false;
                }
                break;

            case TokenizerStatus.COMMENT:
                if (c === -1) return null;
                if (c === "*") status = TokenizerStatus.COMMENT_MAYBE_END;
                break;

            case TokenizerStatus.COMMENT_MAYBE_END:
                if (c === -1) return null;
                if (c === "}") {
                    status = TokenizerStatus.ECHO;
                    tokenStart = pos;
                    tokenLength = 0;
                }
                else if (c !== "*") status = Tokenizer.COMMENT;
                break;
            }
        }

        return null;
    }
}

/** Processes the token and transforms it somehow, if needed. */
Token.prototype.transform = function() {
    if (this.type == TokenType.ECHO) return this;

    // control token
    return this;
}

/** Compiles the template and returns JavaScript source code. */
function compile(template) {
    var js = "\"use strict\";\n";
    var tokenizer = new Tokenizer(template);

    var token;
    while (token = tokenizer.nextToken()) {
        // a control token can mean a lot of things (write, if, loop etc.)
        token = token.transform();
        console.log(token.type.name + ": " + token.content);
    }

    // @todo process the tokens and build .js

    return js;
}

module.exports.get = get;

<commit_msg>Tokenizer - remove unnecessary tokenizer states.<commit_after>"use strict";

var fs = require("fs");

/** Loads the template. */
function get(filename, callback) {
    fs.readFile(filename, { encoding: "utf8" }, function(err, data) {
        if (err) callback(err, null);

        try {
            var compiled = compile(data);
        }
        catch (err) {
            callback(err, null);
        }

        var filenameCompiled = filename + ".js";

        fs.writeFile(filenameCompiled, compiled, function(err) {
            if (err) callback(err, null);

            // @todo change to non-blocking require
            var template = require(filenameCompiled);
            callback(null, template);
        });
    });
}

var TokenizerStatus = {
    ECHO: {},
    MAYBE_CONTROL: {},
    CONTROL: {},
    CONTROL_QUOTES_DOUBLE: {},
    CONTROL_QUOTES_SINGLE: {},
    COMMENT: {},
    COMMENT_MAYBE_END: {}
};

var TokenType = {
    ECHO: { name: "echo" },
    CONTROL: { name: "control" }
};

/** Token object. */
function Token(type, content) {
    this.type = type;
    this.content = content;
}

/** Structure for parser data. */
function Tokenizer(template) {
    // @todo skip BOM
    var status = TokenizerStatus.ECHO;
    var pos = 0;
    var length = template.length;
    var tokenReturned = false;
    var tokenLength = 0;
    var tokenStart;

    // status variables for control token
    var braces = 0;
    var quotesEscape = false;
    var identifierStatus = 0;

    this.nextToken = function() {
        tokenStart = pos;

        while (pos < length + 1) {
            var c = pos < length ? template.charAt(pos++) : (pos++, -1);

            switch (status) {
            case TokenizerStatus.ECHO:
                if (c === -1) {
                    if (tokenLength) return new Token(TokenType.ECHO, template.substr(tokenStart, tokenLength));
                }

                // opening brace => could mean some dynamic content
                if (c === "{") status = TokenizerStatus.MAYBE_CONTROL;
                tokenLength++;
                break;

            case TokenizerStatus.MAYBE_CONTROL:
                if (c === -1) {
                    // always at least "{" character
                    return new Token(TokenType.ECHO, template.substr(tokenStart, tokenLength));
                }

                // whitespace or } => continue with static content
                if (c === " " || c === "\f" || c === "\n" || c === "\r" || c === "\t" || c === "}") {
                    status = TokenizerStatus.ECHO;
                    tokenLength++;
                }
                else { // start a control token or a comment
                    // return the previous echo token, if it isn't empty
                    if (tokenLength > 1) {
                        if (!tokenReturned) {
                            pos--; tokenReturned = true;
                            return new Token(TokenType.ECHO, template.substr(tokenStart, tokenLength - 1)); // without {
                        }
                        tokenReturned = false;
                    }

                    if (c !== "*") {
                        status = TokenizerStatus.CONTROL;

                        // include current character
                        tokenStart = pos - 1;
                        tokenLength = 1;

                        braces = (c === "{") ? 2 : 1;

                        if (c === "\"") status = TokenizerStatus.CONTROL_QUOTES_DOUBLE;
                        else if (c === "\'") status = TokenizerStatus.CONTROL_QUOTES_SINGLE;
                    }
                    else {
                        status = TokenizerStatus.COMMENT;
                    }
                }
                break;

            case TokenizerStatus.CONTROL:
                if (c === -1) {
                    throw {}; // @todo throw something better!
                }

                // closing brace => return the token
                if (c === "}" && braces === 1) {
                    if (!tokenReturned) {
                        pos--; tokenReturned = true;
                        return new Token(TokenType.CONTROL, template.substr(tokenStart, tokenLength));
                    }
                    tokenReturned = false;

                    status = TokenizerStatus.ECHO;
                    tokenStart++;
                    tokenLength = 0;
                    braces = 0;
                }
                else { // other characters => continue...
                    // @todo check for } in quotes
                    tokenLength++;
                    if (c === "{") braces++;
                    else if (c === "}") braces--;
                    else if (c === "\"") status = TokenizerStatus.CONTROL_QUOTES_DOUBLE;
                    else if (c === "\'") status = TokenizerStatus.CONTROL_QUOTES_SINGLE;
                }
                break;

            case TokenizerStatus.CONTROL_QUOTES_DOUBLE:
                if (c === -1) {
                    throw {}; // @todo throw something better!
                }

                tokenLength++;

                if (c === "\\") {
                    quotesEscape = !quotesEscape;
                }
                else {
                    if (c === "\"" && !quotesEscape) status = TokenizerStatus.CONTROL;
                    quotesEscape = false;
                }
                break;

            case TokenizerStatus.CONTROL_QUOTES_SINGLE:
                if (c === -1) {
                    throw {}; // @todo throw something better!
                }

                tokenLength++;

                if (c === "\\") {
                    quotesEscape = !quotesEscape;
                }
                else {
                    if (c === "'" && !quotesEscape) status = TokenizerStatus.CONTROL;
                    quotesEscape = false;
                }
                break;

            case TokenizerStatus.COMMENT:
                if (c === -1) return null;
                if (c === "*") status = TokenizerStatus.COMMENT_MAYBE_END;
                break;

            case TokenizerStatus.COMMENT_MAYBE_END:
                if (c === -1) return null;
                if (c === "}") {
                    status = TokenizerStatus.ECHO;
                    tokenStart = pos;
                    tokenLength = 0;
                }
                else if (c !== "*") status = Tokenizer.COMMENT;
                break;
            }
        }

        return null;
    }
}

/** Processes the token and transforms it somehow, if needed. */
Token.prototype.transform = function() {
    if (this.type == TokenType.ECHO) return this;

    // control token
    return this;
}

/** Compiles the template and returns JavaScript source code. */
function compile(template) {
    var js = "\"use strict\";\n";
    var tokenizer = new Tokenizer(template);

    var token;
    while (token = tokenizer.nextToken()) {
        // a control token can mean a lot of things (write, if, loop etc.)
        token = token.transform();
        console.log(token.type.name + ": " + token.content);
    }

    // @todo process the tokens and build .js

    return js;
}

module.exports.get = get;

<|endoftext|>


<commit_before>import { createElement as h, useState } from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'

import Headline from '../Headline'
import Text from '../Text'
import Updating from '../Updating'
import PresentationEmptyState, { ICON_LOADING, ICON_WARNING } from '../presentations/PresentationEmptyState'
import status from '../../utils/status'

const CardWidget = (props) => {

	const {
		isEmpty,
		isStale,
		isLoading
	} = status(props.widget.value, props.widget.fetching)

	const headline = typeof props.headline === 'function' ?
		props.headline(props.widget) :
		props.headline

	// Use thin space as initial value to avoid that the label changes the height once rendered
	const [ textLabel, setTextLabel ] = useState(' ')

	const presentation = (() => {
		if (isLoading === true) {
			return h(PresentationEmptyState, {
				icon: ICON_LOADING
			}, 'Loading data')
		}

		if (isEmpty === true) {
			h(PresentationEmptyState, {
				icon: ICON_WARNING
			}, 'No data')
		}

		return h(props.widget.Renderer, {
			widget: props.widget,
			setTextLabel
		})
	})()

	return (
		h('div', {
			className: classNames({
				'card': true,
				'card--wide': props.wide === true
			})
		},
			h('div', { className: 'card__inner' },
				h(Headline, {
					type: 'h2',
					size: 'medium',
					onClick: props.onMore
				}, headline),
				h(Text, {
					type: 'div',
					spacing: false
				}, isStale === true ? h(Updating) : textLabel),
				presentation
			)
		)
	)

}

CardWidget.propTypes = {
	wide: PropTypes.bool,
	headline: PropTypes.oneOfType([
		PropTypes.string,
		PropTypes.func
	]).isRequired,
	widget: PropTypes.object.isRequired,
	onMore: PropTypes.func
}

export default CardWidget<commit_msg>Headline must be a string<commit_after>import { createElement as h, useState } from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'

import Headline from '../Headline'
import Text from '../Text'
import Updating from '../Updating'
import PresentationEmptyState, { ICON_LOADING, ICON_WARNING } from '../presentations/PresentationEmptyState'
import status from '../../utils/status'

const CardWidget = (props) => {

	const {
		isEmpty,
		isStale,
		isLoading
	} = status(props.widget.value, props.widget.fetching)

	// Use thin space as initial value to avoid that the label changes the height once rendered
	const [ textLabel, setTextLabel ] = useState(' ')

	const presentation = (() => {
		if (isLoading === true) {
			return h(PresentationEmptyState, {
				icon: ICON_LOADING
			}, 'Loading data')
		}

		if (isEmpty === true) {
			h(PresentationEmptyState, {
				icon: ICON_WARNING
			}, 'No data')
		}

		return h(props.widget.Renderer, {
			widget: props.widget,
			setTextLabel
		})
	})()

	return (
		h('div', {
			className: classNames({
				'card': true,
				'card--wide': props.wide === true
			})
		},
			h('div', { className: 'card__inner' },
				h(Headline, {
					type: 'h2',
					size: 'medium',
					onClick: props.onMore
				}, props.headline),
				h(Text, {
					type: 'div',
					spacing: false
				}, isStale === true ? h(Updating) : textLabel),
				presentation
			)
		)
	)

}

CardWidget.propTypes = {
	wide: PropTypes.bool,
	headline: PropTypes.string.isRequired,
	widget: PropTypes.object.isRequired,
	onMore: PropTypes.func
}

export default CardWidget<|endoftext|>