<commit_before>import 'core-js';
import {RouteRecognizer} from 'aurelia-route-recognizer';
import {Container} from 'aurelia-dependency-injection';
import {History} from 'aurelia-history';
import {NavigationContext} from './navigation-context';
import {NavigationInstruction} from './navigation-instruction';
import {NavModel} from './nav-model';
import {RouterConfiguration} from './router-configuration';
import {
  _createRootedPath,
  _resolveUrl} from './util';
import {RouteConfig} from './interfaces';

/**
* The primary class responsible for handling routing and navigation.
*
* @class Router
* @constructor
*/
export class Router {
  container: Container;
  history: History;
  viewPorts: Object = {};
  routes: RouteConfig[] = [];

  /**
  * The [[Router]]'s current base URL, typically based on the [[Router.currentInstruction]].
  */
  baseUrl: string = '';

  /**
  * True if the [[Router]] has been configured.
  */
  isConfigured: boolean = false;

  /**
  * True if the [[Router]] is currently processing a navigation.
  */
  isNavigating: boolean = false;

  /**
  * The navigation models for routes that specified [[RouteConfig.nav]].
  */
  navigation: NavModel[] = [];

  /**
  * The currently active navigation instruction.
  */
  currentInstruction: NavigationInstruction;

  /**
  * The parent router, or null if this instance is not a child router.
  */
  parent: Router;

  _fallbackOrder: number = 100;
  _recognizer: RouteRecognizer = new RouteRecognizer();
  _childRecognizer: RouteRecognizer = new RouteRecognizer();

  /**
  * @param container The [[Container]] to use when child routers.
  * @param history The [[History]] implementation to delegate navigation requests to.
  */
  constructor(container: Container, history: History) {
    this.container = container;
    this.history = history;
    this.reset();
  }

  /**
  * Gets a valid indicating whether or not this [[Router]] is the root in the router tree. I.e., it has no parent.
  */
  get isRoot(): boolean {
    return !this.parent;
  }

  /**
  * Registers a viewPort to be used as a rendering target for activated routes.
  *
  * @param viewPort The viewPort.
  * @param name The name of the viewPort. 'default' if unspecified.
  */
  registerViewPort(viewPort: Object, name?: string): void {
    name = name || 'default';
    this.viewPorts[name] = viewPort;
  }

  /**
  * Returns a Promise that resolves when the router is configured.
  */
  ensureConfigured(): Promise<void> {
    return this._configuredPromise;
  }

  /**
  * Configures the router.
  *
  * @param callbackOrConfig The [[RouterConfiguration]] or a callback that takes a [[RouterConfiguration]].
  */
  configure(callbackOrConfig: RouterConfiguration|((config: RouterConfiguration) => RouterConfiguration)): Promise<void> {
    this.isConfigured = true;

    let result = callbackOrConfig;
    let config;
    if (typeof callbackOrConfig === 'function') {
      config = new RouterConfiguration();
      result = callbackOrConfig(config);
    }

    return Promise.resolve(result).then((c) => {
      if (c && c.exportToRouter) {
        config = c;
      }

      config.exportToRouter(this);
      this.isConfigured = true;
      this._resolveConfiguredPromise();
    });
  }

  /**
  * Navigates to a new location.
  *
  * @param fragment The URL fragment to use as the navigation destination.
  * @param options The navigation options.
  */
  navigate(fragment: string, options?: Object): boolean {
    if (!this.isConfigured && this.parent) {
      return this.parent.navigate(fragment, options);
    }

    return this.history.navigate(_resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options);
  }

  /**
  * Navigates to a new location corresponding to the route and params specified. Equivallent to [[Router.generate]] followed
  * by [[Router.navigate]].
  *
  * @param route The name of the route to use when generating the navigation location.
  * @param params The route parameters to be used when populating the route pattern.
  * @param options The navigation options.
  */
  navigateToRoute(route: string, params?: Object, options?: Object): boolean {
    let path = this.generate(route, params);
    return this.navigate(path, options);
  }

  /**
  * Navigates back to the most recent location in history.
  */
  navigateBack(): void {
    this.history.navigateBack();
  }

  /**
   * Creates a child router of the current router.
   *
   * @param container The [[Container]] to provide to the child router. Uses the current [[Router]]'s [[Container]] if unspecified.
   * @returns {Router} The new child Router.
   */
  createChild(container?: Container): Router {
    let childRouter = new Router(container || this.container.createChild(), this.history);
    childRouter.parent = this;
    return childRouter;
  }

  /**
  * Generates a URL fragment matching the specified route pattern.
  *
  * @param name The name of the route whose pattern should be used to generate the fragment.
  * @param params The route params to be used to populate the route pattern.
  * @returns {string} A string containing the generated URL fragment.
  */
  generate(name: string, params?: Object): string {
    let hasRoute = this._recognizer.hasRoute(name);
    if ((!this.isConfigured || !hasRoute) && this.parent) {
      return this.parent.generate(name, params);
    }

    if (!hasRoute) {
      throw new Error(`A route with name '${name}' could not be found. Check that \`name: '${name}'\` was specified in the route's config.`);
    }

    let path = this._recognizer.generate(name, params);
    return _createRootedPath(path, this.baseUrl, this.history._hasPushState);
  }

  /**
  * Creates a [[NavModel]] for the specified route config.
  *
  * @param config The route config.
  */
  createNavModel(config: RouteConfig): NavModel {
    let navModel = new NavModel(this, 'href' in config ? config.href : config.route);
    navModel.title = config.title;
    navModel.order = config.nav;
    navModel.href = config.href;
    navModel.settings = config.settings;
    navModel.config = config;

    return navModel;
  }

  /**
  * Registers a new route with the router.
  *
  * @param config The [[RouteConfig]].
  * @param navModel The [[NavModel]] to use for the route. May be omitted for single-pattern routes.
  */
  addRoute(config: RouteConfig, navModel?: NavModel): void {
    validateRouteConfig(config);

    if (!('viewPorts' in config) && !config.navigationStrategy) {
      config.viewPorts = {
        'default': {
          moduleId: config.moduleId,
          view: config.view
        }
      };
    }

    if (!navModel) {
      navModel = this.createNavModel(config);
    }

    this.routes.push(config);

    let path = config.route;
    if (path.charAt(0) === '/') {
      path = path.substr(1);
    }

    let state = this._recognizer.add({path: path, handler: config});

    if (path) {
      let settings = config.settings;
      delete config.settings;
      let withChild = JSON.parse(JSON.stringify(config));
      config.settings = settings;
      withChild.route = `${path}/*childRoute`;
      withChild.hasChildRouter = true;
      this._childRecognizer.add({
        path: withChild.route,
        handler: withChild
      });

      withChild.navModel = navModel;
      withChild.settings = config.settings;
    }

    config.navModel = navModel;

    if ((navModel.order || navModel.order === 0) && this.navigation.indexOf(navModel) === -1) {
      if ((!navModel.href && navModel.href !== '') && (state.types.dynamics || state.types.stars)) {
        throw new Error('Invalid route config: dynamic routes must specify an href to be included in the navigation model.');
      }

      if (typeof navModel.order !== 'number') {
        navModel.order = ++this._fallbackOrder;
      }

      this.navigation.push(navModel);
      this.navigation = this.navigation.sort((a, b) => a.order - b.order);
    }
  }

  /**
  * Gets a value indicating whether or not this [[Router]] or one of its ancestors has a route registered with the specified name.
  *
  * @param name The name of the route to check.
  */
  hasRoute(name: string): boolean {
    return !!(this._recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name));
  }

  /**
  * Gets a value indicating whether or not this [[Router]] has a route registered with the specified name.
  *
  * @param name The name of the route to check.
  */
  hasOwnRoute(name: string): boolean {
    return this._recognizer.hasRoute(name);
  }

  /**
  * Register a handler to use when the incoming URL fragment doesn't match any registered routes.
  *
  * @param config The moduleId, or a function that selects the moduleId, or a [[RouteConfig]].
  */
  handleUnknownRoutes(config?: string|Function|RouteConfig): void {
    if (!config) {
      throw new Error('Invalid unknown route handler');
    }

    this.catchAllHandler = instruction => {
      return this._createRouteConfig(config, instruction)
        .then(c => {
          instruction.config = c;
          return instruction;
        });
    };
  }

  /**
  * Updates the document title using the current navigation instruction.
  */
  updateTitle(): void {
    if (this.parent) {
      return this.parent.updateTitle();
    }

    this.currentInstruction.navigationContext.updateTitle();
  }

  /**
  * Resets the Router to its original unconfigured state.
  */
  reset(): void {
    this._fallbackOrder = 100;
    this._recognizer = new RouteRecognizer();
    this._childRecognizer = new RouteRecognizer();
    this.routes = [];
    this.isNavigating = false;
    this.navigation = [];

    if (this.isConfigured || !this._configuredPromise) {
      this._configuredPromise = new Promise(resolve => {
        this._resolveConfiguredPromise = resolve;
      });
    }

    this.isConfigured = false;
  }

  _refreshBaseUrl(): void {
    if (this.parent) {
      let baseUrl = this.parent.currentInstruction.getBaseUrl();
      this.baseUrl = this.parent.baseUrl + baseUrl;
    }
  }

  _refreshNavigation(): void {
    let nav = this.navigation;

    for (let i = 0, length = nav.length; i < length; i++) {
      let current = nav[i];
      if (!current.href) {
        current.href = _createRootedPath(current.relativeHref, this.baseUrl, this.history._hasPushState);
      }
    }
  }

  _createNavigationInstruction(url: string = '', parentInstruction: NavigationInstruction = null): Promise<NavigationInstruction> {
    let fragment = url;
    let queryString = '';

    let queryIndex = url.indexOf('?');
    if (queryIndex !== -1) {
      fragment = url.substr(0, queryIndex);
      queryString = url.substr(queryIndex + 1);
    }

    let results = this._recognizer.recognize(url);
    if (!results || !results.length) {
      results = this._childRecognizer.recognize(url);
    }

    if ((!results || !results.length) && this.catchAllHandler) {
      let params = { path: fragment };
      let instruction = new NavigationInstruction(
        fragment,
        queryString,
        params,
        results && results.queryParams,
        null, // config will be created by the catchAllHandler
        parentInstruction);

      return evaluateNavigationStrategy(instruction, this.catchAllHandler);
    }

    if (results && results.length) {
      let first = results[0];
      let instruction = new NavigationInstruction(
        fragment,
        queryString,
        first.params,
        first.queryParams || results.queryParams,
        first.config || first.handler,
        parentInstruction);

      if (typeof first.handler === 'function') {
        return evaluateNavigationStrategy(instruction, first.handler, first);
      } else if (first.handler && 'navigationStrategy' in first.handler) {
        return evaluateNavigationStrategy(instruction, first.handler.navigationStrategy, first.handler);
      }

      return Promise.resolve(instruction);
    }

    return Promise.reject(new Error(`Route not found: ${url}`));
  }

  _createNavigationContext(instruction: NavigationInstruction): NavigationContext {
    instruction.navigationContext = new NavigationContext(this, instruction);
    return instruction.navigationContext;
  }

  _createRouteConfig(config, instruction) {
    return Promise.resolve(config)
      .then(c => {
        if (typeof c === 'string') {
          return { moduleId: c };
        } else if (typeof c === 'function') {
          return c(instruction);
        }

        return c;
      })
      .then(c => typeof c === 'string' ? { moduleId: c } : c)
      .then(c => {
        c.route = instruction.params.path;
        validateRouteConfig(c);

        if (!c.navModel) {
          c.navModel = this.createNavModel(c);
        }

        return c;
      });
  }
}

function validateRouteConfig(config: Object): void {
  if (typeof config !== 'object') {
    throw new Error('Invalid Route Config');
  }

  if (typeof config.route !== 'string') {
    throw new Error('Invalid Route Config: You must specify a route pattern.');
  }

  if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) {
    throw new Error('Invalid Route Config: You must specify a moduleId, redirect, navigationStrategy, or viewPorts.');
  }
}

function evaluateNavigationStrategy(instruction: NavigationInstruction, evaluator: Function, context: Object): Promise<NavigationInstruction> {
  return Promise.resolve(evaluator.call(context, instruction)).then(() => {
    if (!('viewPorts' in instruction.config)) {
      instruction.config.viewPorts = {
        'default': {
          moduleId: instruction.config.moduleId
        }
      };
    }

    return instruction;
  });
}
<commit_msg>fix(router): fix typo in doc comment<commit_after>import 'core-js';
import {RouteRecognizer} from 'aurelia-route-recognizer';
import {Container} from 'aurelia-dependency-injection';
import {History} from 'aurelia-history';
import {NavigationContext} from './navigation-context';
import {NavigationInstruction} from './navigation-instruction';
import {NavModel} from './nav-model';
import {RouterConfiguration} from './router-configuration';
import {
  _createRootedPath,
  _resolveUrl} from './util';
import {RouteConfig} from './interfaces';

/**
* The primary class responsible for handling routing and navigation.
*
* @class Router
* @constructor
*/
export class Router {
  container: Container;
  history: History;
  viewPorts: Object = {};
  routes: RouteConfig[] = [];

  /**
  * The [[Router]]'s current base URL, typically based on the [[Router.currentInstruction]].
  */
  baseUrl: string = '';

  /**
  * True if the [[Router]] has been configured.
  */
  isConfigured: boolean = false;

  /**
  * True if the [[Router]] is currently processing a navigation.
  */
  isNavigating: boolean = false;

  /**
  * The navigation models for routes that specified [[RouteConfig.nav]].
  */
  navigation: NavModel[] = [];

  /**
  * The currently active navigation instruction.
  */
  currentInstruction: NavigationInstruction;

  /**
  * The parent router, or null if this instance is not a child router.
  */
  parent: Router;

  _fallbackOrder: number = 100;
  _recognizer: RouteRecognizer = new RouteRecognizer();
  _childRecognizer: RouteRecognizer = new RouteRecognizer();

  /**
  * @param container The [[Container]] to use when child routers.
  * @param history The [[History]] implementation to delegate navigation requests to.
  */
  constructor(container: Container, history: History) {
    this.container = container;
    this.history = history;
    this.reset();
  }

  /**
  * Gets a value indicating whether or not this [[Router]] is the root in the router tree. I.e., it has no parent.
  */
  get isRoot(): boolean {
    return !this.parent;
  }

  /**
  * Registers a viewPort to be used as a rendering target for activated routes.
  *
  * @param viewPort The viewPort.
  * @param name The name of the viewPort. 'default' if unspecified.
  */
  registerViewPort(viewPort: Object, name?: string): void {
    name = name || 'default';
    this.viewPorts[name] = viewPort;
  }

  /**
  * Returns a Promise that resolves when the router is configured.
  */
  ensureConfigured(): Promise<void> {
    return this._configuredPromise;
  }

  /**
  * Configures the router.
  *
  * @param callbackOrConfig The [[RouterConfiguration]] or a callback that takes a [[RouterConfiguration]].
  */
  configure(callbackOrConfig: RouterConfiguration|((config: RouterConfiguration) => RouterConfiguration)): Promise<void> {
    this.isConfigured = true;

    let result = callbackOrConfig;
    let config;
    if (typeof callbackOrConfig === 'function') {
      config = new RouterConfiguration();
      result = callbackOrConfig(config);
    }

    return Promise.resolve(result).then((c) => {
      if (c && c.exportToRouter) {
        config = c;
      }

      config.exportToRouter(this);
      this.isConfigured = true;
      this._resolveConfiguredPromise();
    });
  }

  /**
  * Navigates to a new location.
  *
  * @param fragment The URL fragment to use as the navigation destination.
  * @param options The navigation options.
  */
  navigate(fragment: string, options?: Object): boolean {
    if (!this.isConfigured && this.parent) {
      return this.parent.navigate(fragment, options);
    }

    return this.history.navigate(_resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options);
  }

  /**
  * Navigates to a new location corresponding to the route and params specified. Equivallent to [[Router.generate]] followed
  * by [[Router.navigate]].
  *
  * @param route The name of the route to use when generating the navigation location.
  * @param params The route parameters to be used when populating the route pattern.
  * @param options The navigation options.
  */
  navigateToRoute(route: string, params?: Object, options?: Object): boolean {
    let path = this.generate(route, params);
    return this.navigate(path, options);
  }

  /**
  * Navigates back to the most recent location in history.
  */
  navigateBack(): void {
    this.history.navigateBack();
  }

  /**
   * Creates a child router of the current router.
   *
   * @param container The [[Container]] to provide to the child router. Uses the current [[Router]]'s [[Container]] if unspecified.
   * @returns {Router} The new child Router.
   */
  createChild(container?: Container): Router {
    let childRouter = new Router(container || this.container.createChild(), this.history);
    childRouter.parent = this;
    return childRouter;
  }

  /**
  * Generates a URL fragment matching the specified route pattern.
  *
  * @param name The name of the route whose pattern should be used to generate the fragment.
  * @param params The route params to be used to populate the route pattern.
  * @returns {string} A string containing the generated URL fragment.
  */
  generate(name: string, params?: Object): string {
    let hasRoute = this._recognizer.hasRoute(name);
    if ((!this.isConfigured || !hasRoute) && this.parent) {
      return this.parent.generate(name, params);
    }

    if (!hasRoute) {
      throw new Error(`A route with name '${name}' could not be found. Check that \`name: '${name}'\` was specified in the route's config.`);
    }

    let path = this._recognizer.generate(name, params);
    return _createRootedPath(path, this.baseUrl, this.history._hasPushState);
  }

  /**
  * Creates a [[NavModel]] for the specified route config.
  *
  * @param config The route config.
  */
  createNavModel(config: RouteConfig): NavModel {
    let navModel = new NavModel(this, 'href' in config ? config.href : config.route);
    navModel.title = config.title;
    navModel.order = config.nav;
    navModel.href = config.href;
    navModel.settings = config.settings;
    navModel.config = config;

    return navModel;
  }

  /**
  * Registers a new route with the router.
  *
  * @param config The [[RouteConfig]].
  * @param navModel The [[NavModel]] to use for the route. May be omitted for single-pattern routes.
  */
  addRoute(config: RouteConfig, navModel?: NavModel): void {
    validateRouteConfig(config);

    if (!('viewPorts' in config) && !config.navigationStrategy) {
      config.viewPorts = {
        'default': {
          moduleId: config.moduleId,
          view: config.view
        }
      };
    }

    if (!navModel) {
      navModel = this.createNavModel(config);
    }

    this.routes.push(config);

    let path = config.route;
    if (path.charAt(0) === '/') {
      path = path.substr(1);
    }

    let state = this._recognizer.add({path: path, handler: config});

    if (path) {
      let settings = config.settings;
      delete config.settings;
      let withChild = JSON.parse(JSON.stringify(config));
      config.settings = settings;
      withChild.route = `${path}/*childRoute`;
      withChild.hasChildRouter = true;
      this._childRecognizer.add({
        path: withChild.route,
        handler: withChild
      });

      withChild.navModel = navModel;
      withChild.settings = config.settings;
    }

    config.navModel = navModel;

    if ((navModel.order || navModel.order === 0) && this.navigation.indexOf(navModel) === -1) {
      if ((!navModel.href && navModel.href !== '') && (state.types.dynamics || state.types.stars)) {
        throw new Error('Invalid route config: dynamic routes must specify an href to be included in the navigation model.');
      }

      if (typeof navModel.order !== 'number') {
        navModel.order = ++this._fallbackOrder;
      }

      this.navigation.push(navModel);
      this.navigation = this.navigation.sort((a, b) => a.order - b.order);
    }
  }

  /**
  * Gets a value indicating whether or not this [[Router]] or one of its ancestors has a route registered with the specified name.
  *
  * @param name The name of the route to check.
  */
  hasRoute(name: string): boolean {
    return !!(this._recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name));
  }

  /**
  * Gets a value indicating whether or not this [[Router]] has a route registered with the specified name.
  *
  * @param name The name of the route to check.
  */
  hasOwnRoute(name: string): boolean {
    return this._recognizer.hasRoute(name);
  }

  /**
  * Register a handler to use when the incoming URL fragment doesn't match any registered routes.
  *
  * @param config The moduleId, or a function that selects the moduleId, or a [[RouteConfig]].
  */
  handleUnknownRoutes(config?: string|Function|RouteConfig): void {
    if (!config) {
      throw new Error('Invalid unknown route handler');
    }

    this.catchAllHandler = instruction => {
      return this._createRouteConfig(config, instruction)
        .then(c => {
          instruction.config = c;
          return instruction;
        });
    };
  }

  /**
  * Updates the document title using the current navigation instruction.
  */
  updateTitle(): void {
    if (this.parent) {
      return this.parent.updateTitle();
    }

    this.currentInstruction.navigationContext.updateTitle();
  }

  /**
  * Resets the Router to its original unconfigured state.
  */
  reset(): void {
    this._fallbackOrder = 100;
    this._recognizer = new RouteRecognizer();
    this._childRecognizer = new RouteRecognizer();
    this.routes = [];
    this.isNavigating = false;
    this.navigation = [];

    if (this.isConfigured || !this._configuredPromise) {
      this._configuredPromise = new Promise(resolve => {
        this._resolveConfiguredPromise = resolve;
      });
    }

    this.isConfigured = false;
  }

  _refreshBaseUrl(): void {
    if (this.parent) {
      let baseUrl = this.parent.currentInstruction.getBaseUrl();
      this.baseUrl = this.parent.baseUrl + baseUrl;
    }
  }

  _refreshNavigation(): void {
    let nav = this.navigation;

    for (let i = 0, length = nav.length; i < length; i++) {
      let current = nav[i];
      if (!current.href) {
        current.href = _createRootedPath(current.relativeHref, this.baseUrl, this.history._hasPushState);
      }
    }
  }

  _createNavigationInstruction(url: string = '', parentInstruction: NavigationInstruction = null): Promise<NavigationInstruction> {
    let fragment = url;
    let queryString = '';

    let queryIndex = url.indexOf('?');
    if (queryIndex !== -1) {
      fragment = url.substr(0, queryIndex);
      queryString = url.substr(queryIndex + 1);
    }

    let results = this._recognizer.recognize(url);
    if (!results || !results.length) {
      results = this._childRecognizer.recognize(url);
    }

    if ((!results || !results.length) && this.catchAllHandler) {
      let params = { path: fragment };
      let instruction = new NavigationInstruction(
        fragment,
        queryString,
        params,
        results && results.queryParams,
        null, // config will be created by the catchAllHandler
        parentInstruction);

      return evaluateNavigationStrategy(instruction, this.catchAllHandler);
    }

    if (results && results.length) {
      let first = results[0];
      let instruction = new NavigationInstruction(
        fragment,
        queryString,
        first.params,
        first.queryParams || results.queryParams,
        first.config || first.handler,
        parentInstruction);

      if (typeof first.handler === 'function') {
        return evaluateNavigationStrategy(instruction, first.handler, first);
      } else if (first.handler && 'navigationStrategy' in first.handler) {
        return evaluateNavigationStrategy(instruction, first.handler.navigationStrategy, first.handler);
      }

      return Promise.resolve(instruction);
    }

    return Promise.reject(new Error(`Route not found: ${url}`));
  }

  _createNavigationContext(instruction: NavigationInstruction): NavigationContext {
    instruction.navigationContext = new NavigationContext(this, instruction);
    return instruction.navigationContext;
  }

  _createRouteConfig(config, instruction) {
    return Promise.resolve(config)
      .then(c => {
        if (typeof c === 'string') {
          return { moduleId: c };
        } else if (typeof c === 'function') {
          return c(instruction);
        }

        return c;
      })
      .then(c => typeof c === 'string' ? { moduleId: c } : c)
      .then(c => {
        c.route = instruction.params.path;
        validateRouteConfig(c);

        if (!c.navModel) {
          c.navModel = this.createNavModel(c);
        }

        return c;
      });
  }
}

function validateRouteConfig(config: Object): void {
  if (typeof config !== 'object') {
    throw new Error('Invalid Route Config');
  }

  if (typeof config.route !== 'string') {
    throw new Error('Invalid Route Config: You must specify a route pattern.');
  }

  if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) {
    throw new Error('Invalid Route Config: You must specify a moduleId, redirect, navigationStrategy, or viewPorts.');
  }
}

function evaluateNavigationStrategy(instruction: NavigationInstruction, evaluator: Function, context: Object): Promise<NavigationInstruction> {
  return Promise.resolve(evaluator.call(context, instruction)).then(() => {
    if (!('viewPorts' in instruction.config)) {
      instruction.config.viewPorts = {
        'default': {
          moduleId: instruction.config.moduleId
        }
      };
    }

    return instruction;
  });
}
<|endoftext|>


<commit_before>'use strict';

let cli        = require('..');
let util       = require('util');
let inflection = require('inflection');

/**
 * styledHeader logs in a consistent header style
 *
 * @example
 * styledHeader('MyApp') # Outputs === MyApp
 *
 * @param {header} header text
 * @returns {null}
 */
function styledHeader(header) {
  cli.log(`=== ${header}`);
}

/**
 * styledObject logs an object in a consistent columnar style
 *
 * @example
 * styledObject({name: "myapp", collaborators: ["user1@example.com", "user2@example.com"]})
 * Collaborators: user1@example.com
 *                user2@example.com
 * Name:          myapp
 *
 * @param {obj} object data to print
 * @param {keys} optional array of keys to sort/filter output
 * @returns {null}
 */
function styledObject(obj, keys) {
  let keyLengths = Object.keys(obj).map(function(key) { return key.toString().length; });
  let maxKeyLength = Math.max.apply(Math, keyLengths) + 2;
  function pp(obj) {
    if (typeof obj === 'string' || typeof obj === 'number') {
      return obj;
    } else if (typeof obj === 'object') {
      return Object.keys(obj).map(k => k + ': ' + util.inspect(obj[k])).join(', ');
    } else {
      return util.inspect(obj);
    }
  }
  function logKeyValue(key, value) {
    cli.log(inflection.titleize(key)+':'+' '.repeat(maxKeyLength - key.length-1)+pp(value));
  }
  for (var key of (keys || Object.keys(obj).sort())) {
    let value = obj[key];
    if (Array.isArray(value)) {
      if (value.length > 0) {
        logKeyValue(key, value[0]);
        for (var e of value.slice(1)) {
          cli.log(" ".repeat(maxKeyLength) + pp(e));
        }
      }
    } else if (value !== null && value !== undefined) {
      logKeyValue(key, value);
    }
  }
}

module.exports.styledHeader = styledHeader;
module.exports.styledObject = styledObject;
<commit_msg>header styling<commit_after>'use strict';

let cli        = require('..');
let util       = require('util');
let inflection = require('inflection');

/**
 * styledHeader logs in a consistent header style
 *
 * @example
 * styledHeader('MyApp') # Outputs === MyApp
 *
 * @param {header} header text
 * @returns {null}
 */
function styledHeader(header) {
  cli.log(cli.color.gray('=== ') + cli.color.bold(header));
}

/**
 * styledObject logs an object in a consistent columnar style
 *
 * @example
 * styledObject({name: "myapp", collaborators: ["user1@example.com", "user2@example.com"]})
 * Collaborators: user1@example.com
 *                user2@example.com
 * Name:          myapp
 *
 * @param {obj} object data to print
 * @param {keys} optional array of keys to sort/filter output
 * @returns {null}
 */
function styledObject(obj, keys) {
  let keyLengths = Object.keys(obj).map(function(key) { return key.toString().length; });
  let maxKeyLength = Math.max.apply(Math, keyLengths) + 2;
  function pp(obj) {
    if (typeof obj === 'string' || typeof obj === 'number') {
      return obj;
    } else if (typeof obj === 'object') {
      return Object.keys(obj).map(k => k + ': ' + util.inspect(obj[k])).join(', ');
    } else {
      return util.inspect(obj);
    }
  }
  function logKeyValue(key, value) {
    cli.log(inflection.titleize(key)+':'+' '.repeat(maxKeyLength - key.length-1)+pp(value));
  }
  for (var key of (keys || Object.keys(obj).sort())) {
    let value = obj[key];
    if (Array.isArray(value)) {
      if (value.length > 0) {
        logKeyValue(key, value[0]);
        for (var e of value.slice(1)) {
          cli.log(" ".repeat(maxKeyLength) + pp(e));
        }
      }
    } else if (value !== null && value !== undefined) {
      logKeyValue(key, value);
    }
  }
}

module.exports.styledHeader = styledHeader;
module.exports.styledObject = styledObject;
<|endoftext|>


<commit_before>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
    (document.documentMode == null || document.documentMode < 8);

  var Pos = CodeMirror.Pos;

  var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};

  function findMatchingBracket(cm, where, strict, config) {
    var line = cm.getLineHandle(where.line), pos = where.ch - 1;
    var match;
    var afterCursor;
    if (!config || config.afterCursor === undefined) {
      var paddedClassName = ' ' + cm.getWrapperElement().className + ' ';
      afterCursor = (paddedClassName.indexOf(' cm-fat-cursor ') > -1);
    } else {
      afterCursor = config.afterCursor;
    }

    // A cursor is defined as between two characters, but in in vim command mode
    // (i.e. not insert mode), the cursor is visually represented as a
    // highlighted box on top of the 2nd character. Otherwise, we allow matches
    // from before or after the cursor.
    if (afterCursor) {
      match = matching[line.text.charAt(++pos)];
    } else {
      match = (pos >= 0 && matching[line.text.charAt(pos)]) ||
              matching[line.text.charAt(++pos)];
    }
    if (!match) return null;
    var dir = match.charAt(1) == ">" ? 1 : -1;
    if (strict && (dir > 0) != (pos == where.ch)) return null;
    var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));

    var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
    if (found == null) return null;
    return {from: Pos(where.line, pos), to: found && found.pos,
            match: found && found.ch == match.charAt(0), forward: dir > 0};
  }

  // bracketRegex is used to specify which type of bracket to scan
  // should be a regexp, e.g. /[[\]]/
  //
  // Note: If "where" is on an open bracket, then this bracket is ignored.
  //
  // Returns false when no bracket was found, null when it reached
  // maxScanLines and gave up
  function scanForBracket(cm, where, dir, style, config) {
    var maxScanLen = (config && config.maxScanLineLength) || 10000;
    var maxScanLines = (config && config.maxScanLines) || 1000;

    var stack = [];
    var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\]]/;
    var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
                          : Math.max(cm.firstLine() - 1, where.line - maxScanLines);
    for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
      var line = cm.getLine(lineNo);
      if (!line) continue;
      var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
      if (line.length > maxScanLen) continue;
      if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
      for (; pos != end; pos += dir) {
        var ch = line.charAt(pos);
        if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
          var match = matching[ch];
          if ((match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
          else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
          else stack.pop();
        }
      }
    }
    return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
  }

  function matchBrackets(cm, autoclear, config) {
    // Disable brace matching in long lines, since it'll cause hugely slow updates
    var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
    var marks = [], ranges = cm.listSelections();
    for (var i = 0; i < ranges.length; i++) {
      var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, false, config);
      if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
        var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
        marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
        if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
          marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
      }
    }

    if (marks.length) {
      // Kludge to work around the IE bug from issue #1193, where text
      // input stops going to the textare whever this fires.
      if (ie_lt8 && cm.state.focused) cm.focus();

      var clear = function() {
        cm.operation(function() {
          for (var i = 0; i < marks.length; i++) marks[i].clear();
        });
      };
      if (autoclear) setTimeout(clear, 800);
      else return clear;
    }
  }

  var currentlyHighlighted = null;
  function doMatchBrackets(cm) {
    cm.operation(function() {
      if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
      currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
    });
  }

  CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
    if (old && old != CodeMirror.Init) {
      cm.off("cursorActivity", doMatchBrackets);
      if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
    }
    if (val) {
      cm.state.matchBrackets = typeof val == "object" ? val : {};
      cm.on("cursorActivity", doMatchBrackets);
    }
  });

  CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
  CodeMirror.defineExtension("findMatchingBracket", function(pos, strict, config){
    return findMatchingBracket(this, pos, strict, config);
  });
  CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
    return scanForBracket(this, pos, dir, style, config);
  });
});
<commit_msg>[matchbrackets addon] Simplify code a little<commit_after>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
    (document.documentMode == null || document.documentMode < 8);

  var Pos = CodeMirror.Pos;

  var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};

  function findMatchingBracket(cm, where, strict, config) {
    var line = cm.getLineHandle(where.line), pos = where.ch - 1;
    var afterCursor = config && config.afterCursor
    if (afterCursor == null)
      afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className)

    // A cursor is defined as between two characters, but in in vim command mode
    // (i.e. not insert mode), the cursor is visually represented as a
    // highlighted box on top of the 2nd character. Otherwise, we allow matches
    // from before or after the cursor.
    var match = (!afterCursor && pos >= 0 && matching[line.text.charAt(pos)]) ||
        matching[line.text.charAt(++pos)];
    if (!match) return null;
    var dir = match.charAt(1) == ">" ? 1 : -1;
    if (strict && (dir > 0) != (pos == where.ch)) return null;
    var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));

    var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
    if (found == null) return null;
    return {from: Pos(where.line, pos), to: found && found.pos,
            match: found && found.ch == match.charAt(0), forward: dir > 0};
  }

  // bracketRegex is used to specify which type of bracket to scan
  // should be a regexp, e.g. /[[\]]/
  //
  // Note: If "where" is on an open bracket, then this bracket is ignored.
  //
  // Returns false when no bracket was found, null when it reached
  // maxScanLines and gave up
  function scanForBracket(cm, where, dir, style, config) {
    var maxScanLen = (config && config.maxScanLineLength) || 10000;
    var maxScanLines = (config && config.maxScanLines) || 1000;

    var stack = [];
    var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\]]/;
    var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
                          : Math.max(cm.firstLine() - 1, where.line - maxScanLines);
    for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
      var line = cm.getLine(lineNo);
      if (!line) continue;
      var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
      if (line.length > maxScanLen) continue;
      if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
      for (; pos != end; pos += dir) {
        var ch = line.charAt(pos);
        if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
          var match = matching[ch];
          if ((match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
          else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
          else stack.pop();
        }
      }
    }
    return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
  }

  function matchBrackets(cm, autoclear, config) {
    // Disable brace matching in long lines, since it'll cause hugely slow updates
    var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
    var marks = [], ranges = cm.listSelections();
    for (var i = 0; i < ranges.length; i++) {
      var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, false, config);
      if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
        var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
        marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
        if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
          marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
      }
    }

    if (marks.length) {
      // Kludge to work around the IE bug from issue #1193, where text
      // input stops going to the textare whever this fires.
      if (ie_lt8 && cm.state.focused) cm.focus();

      var clear = function() {
        cm.operation(function() {
          for (var i = 0; i < marks.length; i++) marks[i].clear();
        });
      };
      if (autoclear) setTimeout(clear, 800);
      else return clear;
    }
  }

  var currentlyHighlighted = null;
  function doMatchBrackets(cm) {
    cm.operation(function() {
      if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
      currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
    });
  }

  CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
    if (old && old != CodeMirror.Init) {
      cm.off("cursorActivity", doMatchBrackets);
      if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
    }
    if (val) {
      cm.state.matchBrackets = typeof val == "object" ? val : {};
      cm.on("cursorActivity", doMatchBrackets);
    }
  });

  CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
  CodeMirror.defineExtension("findMatchingBracket", function(pos, strict, config){
    return findMatchingBracket(this, pos, strict, config);
  });
  CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
    return scanForBracket(this, pos, dir, style, config);
  });
});
<|endoftext|>


<commit_before>describe('ocTime', function () {
  var compile;
  var scope;
  var interval;
  var currentDate = new Date(2016, 7, 7, 10, 2, 3);

  beforeEach(function () {
    module('ocWebGui.shared.time');

    module(function ($provide) {
      $provide.service('CustomDate', function () {
        return {
          getDate: function () {
            return currentDate;
          }
        };
      });
    });

    inject(function ($compile, $rootScope, $interval) {
      compile = $compile;
      scope = $rootScope.$new();
      interval = $interval;
    });
  });

  function getCompiledElement() {
    var element = angular.element(
      '<oc-time seconds="mySeconds" class="my-class"></oc-time>'
    );
    var compiledElement = compile(element)(scope);
    scope.$digest();
    return compiledElement;
  }

  function getCompiledElementForDateObject() {
    var element = angular.element(
      '<oc-time dateobj="myDate" class="my-class"></oc-time>'
    );
    var compiledElement = compile(element)(scope);
    scope.$digest();
    return compiledElement;
  }

  describe('with date object', function () {
    var directiveElem;

    beforeEach(function () {
      scope.myDate = new Date(2016, 7, 7, 10, 0, 0);
      directiveElem = getCompiledElementForDateObject();
    });

    it('should have class', function () {
      expect(directiveElem.hasClass('my-class')).toBe(true);
    });

    it('should render initial time', function () {
      expect(directiveElem.text()).toBe('02:03');
    });

    it('should update time', function () {
      scope.myDate = new Date(2016, 7, 7, 9, 58, 43);
      scope.$digest();
      expect(directiveElem.text()).toBe('03:20');
    });

    it('should display hours if necessary', function () {
      scope.myDate = new Date(2016, 7, 7, 7, 58, 43);
      scope.$digest();
      expect(directiveElem.text()).toBe('02:03:20');
    });
  });

  describe('without update (use seconds)', function () {
    var directiveElem;

    beforeEach(function () {
      scope.mySeconds = 123;
      scope.myUpdate = false;
      directiveElem = getCompiledElement();
    });

    it('should have class', function () {
      expect(directiveElem.hasClass('my-class')).toBe(true);
    });

    it('should render initial time', function () {
      expect(directiveElem.text()).toBe('02:03');
    });

    it('should update time', function () {
      scope.mySeconds = 200;
      scope.$digest();
      expect(directiveElem.text()).toBe('03:20');
    });

    it('should not update time automatically', function () {
      interval.flush(5000);
      expect(directiveElem.text()).toBe('02:03');
    });

    it('should display hours if necessary', function () {
      scope.mySeconds = 3777;
      scope.$digest();
      expect(directiveElem.text()).toBe('01:02:57');
    });
  });
});
<commit_msg>add mock to timeDirective test<commit_after>describe('ocTime', function () {
  var compile;
  var scope;
  var interval;
  var currentDate = new Date(2016, 7, 7, 10, 2, 3);

  beforeEach(function () {
    module('ocWebGui.shared.time');

    module(function ($provide) {
      $provide.service('CustomDate', function () {
        return {
          getDate: function () {
            return currentDate;
          },

          pad2: function (value) {
            return (value < 10 ? '0' : '') + value;
          },

          secondsToHoursMinutesSeconds function (currentSeconds) {
            var seconds = currentSeconds % 60;
            var minutes = Math.floor(currentSeconds / 60);

            if (minutes >= 60) {
              minutes = Math.floor(currentSeconds / 60 % 60);
              var hours = Math.floor(currentSeconds / 60 / 60);
              return pad2(hours) + ':' + pad2(minutes) + ':' + pad2(seconds);
            }

            return pad2(minutes) + ':' + pad2(seconds);
          }
        };
      });
    });

    inject(function ($compile, $rootScope, $interval) {
      compile = $compile;
      scope = $rootScope.$new();
      interval = $interval;
    });
  });

  function getCompiledElement() {
    var element = angular.element(
      '<oc-time seconds="mySeconds" class="my-class"></oc-time>'
    );
    var compiledElement = compile(element)(scope);
    scope.$digest();
    return compiledElement;
  }

  function getCompiledElementForDateObject() {
    var element = angular.element(
      '<oc-time dateobj="myDate" class="my-class"></oc-time>'
    );
    var compiledElement = compile(element)(scope);
    scope.$digest();
    return compiledElement;
  }

  describe('with date object', function () {
    var directiveElem;

    beforeEach(function () {
      scope.myDate = new Date(2016, 7, 7, 10, 0, 0);
      directiveElem = getCompiledElementForDateObject();
    });

    it('should have class', function () {
      expect(directiveElem.hasClass('my-class')).toBe(true);
    });

    it('should render initial time', function () {
      expect(directiveElem.text()).toBe('02:03');
    });

    it('should update time', function () {
      scope.myDate = new Date(2016, 7, 7, 9, 58, 43);
      scope.$digest();
      expect(directiveElem.text()).toBe('03:20');
    });

    it('should display hours if necessary', function () {
      scope.myDate = new Date(2016, 7, 7, 7, 58, 43);
      scope.$digest();
      expect(directiveElem.text()).toBe('02:03:20');
    });
  });

  describe('without update (use seconds)', function () {
    var directiveElem;

    beforeEach(function () {
      scope.mySeconds = 123;
      scope.myUpdate = false;
      directiveElem = getCompiledElement();
    });

    it('should have class', function () {
      expect(directiveElem.hasClass('my-class')).toBe(true);
    });

    it('should render initial time', function () {
      expect(directiveElem.text()).toBe('02:03');
    });

    it('should update time', function () {
      scope.mySeconds = 200;
      scope.$digest();
      expect(directiveElem.text()).toBe('03:20');
    });

    it('should not update time automatically', function () {
      interval.flush(5000);
      expect(directiveElem.text()).toBe('02:03');
    });

    it('should display hours if necessary', function () {
      scope.mySeconds = 3777;
      scope.$digest();
      expect(directiveElem.text()).toBe('01:02:57');
    });
  });
});
<|endoftext|>


<commit_before>'use strict'

const Https = require('https')
const ParseString = require('xml2js').parseString

function run (msg, text) {
	// Make ajax request to deviant art random url
	var text = (msg.body.event && msg.body.event.text) || ''
	var url = 'https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?'
	console.log(url)
	Https.get(url, function(res) {
		res.setEncoding('utf8');
		let raw_data = '';
		res.on('data', (chunk) => { raw_data += chunk; });
		res.on('end', () => {
			try {
				ParseString(raw_data, function (err, result) {
					for (var prop in result.feed.entry[0].link)
					{
						if (result.feed.entry[0].link[prop]['$'].type == 'image/jpeg')
						{
							console.log(result.feed.entry[0].link[prop]['$']['href'])
							msg.say({
								text: 'Here is a random image, type what comes to mind when you see this image.',
								"attachments": [
								{
									"fallback": '',
									"color": "#36a64f",
									"pretext": "",
									"author_name": "",
									"author_link": "http://flickr.com/bobby/",
									"author_icon": "http://flickr.com/icons/bobby.jpg",
									"title": '',
									"title_link": "",
									"text": '',
									"image_url": result.feed.entry[0].link[prop]['$']['href'],
									"thumb_url": result.feed.entry[0].link[prop]['$']['href'],
								}
								]
							})
							.route('flickr_response')
						}
					}
				})
			} catch (e) {
				console.error(e.message);
			}
		});
	}).on('error', function(e) {
		console.log('Got error: ' + e.message)
	})
}

module.exports = {
	run: run,
}
<commit_msg>Remove console logs.<commit_after>'use strict'

const Https = require('https')
const ParseString = require('xml2js').parseString

function run (msg, text) {
	// Make ajax request to deviant art random url
	var text = (msg.body.event && msg.body.event.text) || ''
	var url = 'https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?'
	Https.get(url, function(res) {
		res.setEncoding('utf8');
		let raw_data = '';
		res.on('data', (chunk) => { raw_data += chunk; });
		res.on('end', () => {
			try {
				ParseString(raw_data, function (err, result) {
					for (var prop in result.feed.entry[0].link)
					{
						if (result.feed.entry[0].link[prop]['$'].type == 'image/jpeg')
						{
							msg.say({
								text: 'Here is a random image, type what comes to mind when you see this image.',
								"attachments": [
								{
									"fallback": '',
									"color": "#36a64f",
									"pretext": "",
									"author_name": "",
									"author_link": "http://flickr.com/bobby/",
									"author_icon": "http://flickr.com/icons/bobby.jpg",
									"title": '',
									"title_link": "",
									"text": '',
									"image_url": result.feed.entry[0].link[prop]['$']['href'],
									"thumb_url": result.feed.entry[0].link[prop]['$']['href'],
								}
								]
							})
							.route('flickr_response')
						}
					}
				})
			} catch (e) {
				console.error(e.message);
			}
		});
	}).on('error', function(e) {
		console.log('Got error: ' + e.message)
	})
}

module.exports = {
	run: run,
}
<|endoftext|>


<commit_before>module.exports = {
    siteMetadata: {
        title: "Hyppykeli",
    },
    proxy: {
        prefix: "/api",
        url: "http://localhost:" + (process.env.API_PORT || 32944),
    },
    plugins: [
        "gatsby-plugin-lodash",
        "gatsby-plugin-glamor",
        process.env.ANALYZE
            ? {
                  resolve: "gatsby-plugin-webpack-bundle-analyzer",
                  options: {
                      analyzerPort: 3000,
                      production: true,
                  },
              }
            : null,
        {
            resolve: "gatsby-source-graphql",
            options: {
                // This type will contain remote schema Query type
                typeName: "WP",
                // This is field under which it's accessible
                fieldName: "wp",
                // Url to query from
                url: "http://graphql.valudata-fi.test/graphql",
            },
        },
        {
            resolve: `gatsby-plugin-emotion`,
            options: {
                // Accepts all options defined by `babel-plugin-emotion` plugin.
            },
        },
        "gatsby-plugin-typescript",
        "gatsby-plugin-react-helmet",
        {
            resolve: "gatsby-source-filesystem",
            options: {
                name: "images",
                path: `${__dirname}/src/images`,
            },
        },
        "gatsby-transformer-sharp",
        "gatsby-plugin-sharp",
        {
            resolve: "gatsby-plugin-manifest",
            options: {
                name: "gatsby-starter-default",
                short_name: "starter",
                start_url: "/",
                background_color: "#663399",
                theme_color: "#663399",
                display: "minimal-ui",
                icon: "src/images/parachute-icon.png", // This path is relative to the root of the site.
            },
        },
        // this (optional) plugin enables Progressive Web App + Offline functionality
        // To learn more, visit: https://gatsby.app/offline
        // 'gatsby-plugin-offline',
    ].filter(Boolean),
};
<commit_msg>Fix manifest<commit_after>module.exports = {
    siteMetadata: {
        title: "Hyppykeli",
    },
    proxy: {
        prefix: "/api",
        url: "http://localhost:" + (process.env.API_PORT || 32944),
    },
    plugins: [
        "gatsby-plugin-lodash",
        "gatsby-plugin-glamor",
        process.env.ANALYZE
            ? {
                  resolve: "gatsby-plugin-webpack-bundle-analyzer",
                  options: {
                      analyzerPort: 3000,
                      production: true,
                  },
              }
            : null,
        {
            resolve: "gatsby-source-graphql",
            options: {
                // This type will contain remote schema Query type
                typeName: "WP",
                // This is field under which it's accessible
                fieldName: "wp",
                // Url to query from
                url: "http://graphql.valudata-fi.test/graphql",
            },
        },
        {
            resolve: `gatsby-plugin-emotion`,
            options: {
                // Accepts all options defined by `babel-plugin-emotion` plugin.
            },
        },
        "gatsby-plugin-typescript",
        "gatsby-plugin-react-helmet",
        {
            resolve: "gatsby-source-filesystem",
            options: {
                name: "images",
                path: `${__dirname}/src/images`,
            },
        },
        "gatsby-transformer-sharp",
        "gatsby-plugin-sharp",
        {
            resolve: "gatsby-plugin-manifest",
            options: {
                name: "Hyppykeli.fi",
                short_name: "Hyppykeli.fi",
                start_url: "/",
                background_color: "skyblue",
                theme_color: "skyblue",
                display: "minimal-ui",
                icon: "src/images/parachute-icon.png", // This path is relative to the root of the site.
            },
        },
        // this (optional) plugin enables Progressive Web App + Offline functionality
        // To learn more, visit: https://gatsby.app/offline
        // 'gatsby-plugin-offline',
    ].filter(Boolean),
};
<|endoftext|>


<commit_before>import React from 'react'
import { Route, IndexRoute } from 'react-router'
import { Home, LiveBroadcast } from './containers'
import { NotFound, About } from './components'

const App = (props) => <div>{props.children}</div>

const AppRouter = (
  <Route path="/" component={App}>
    <IndexRoute component={Home} />
    <Route path="liveBroadcast" component={LiveBroadcast} />
    <Route path="about" component={About} />
    <Route path="*" component={NotFound} status={404}/>
  </Route>
);

export default AppRouter;
<commit_msg>complete the other routing<commit_after>import React from 'react'
import { Route, IndexRoute } from 'react-router'
import { App, Home, LiveBroadcast, GameProduct, EduProduct, Advert, OtherApp } from './containers'
import { NotFound, About } from './components'

const AppRouter = (
  <Route path="/" component={App}>
    <IndexRoute component={Home} />
    <Route path="liveBroadcast" component={LiveBroadcast} />
    <Route path="gameProduct" component={GameProduct} />
    <Route path="eduProduct" component={EduProduct} />
    <Route path="otherApp" component={OtherApp} />
    <Route path="advert" component={Advert} />
    <Route path="*" component={NotFound} status={404}/>
  </Route>
);

export default AppRouter;
<|endoftext|>


<commit_before>var map = null;
var overArea = null;
var clickedArea = null;
var marker = null;
var gonzo1, gonzo2, gongo3, gonzo4;

var activeGonzo = null;

var defaultNamespaces = [];

var geoOverlay = {
		type: "FeatureCollection",
		properties: { },
		features: [ {
			strokeColor: "#000000",
			strokeOpacity: 0.8,
			strokeWeight: 2,
			strokeWidth: 2,
			fillColor: "#FFC0C0",
			fillOpacity: 0.2,
		    type: "Feature",
		    properties: {},
		    geometry: {type:"MultiPolygon", coordinates:[]}
		} ]
	};

var searchGonzo = null;

// area data
var comments = {};
var dbpediateComments = {};
var statistics = {};

$(document).ready(function(){
    var latlng = new google.maps.LatLng(60.1662735988013, 24.93207843548);

	// get namespaces from SPARQL endpoint
	var query = "SELECT ?ns ?prefix WHERE { ?ns <http://data.mysema.com/schemas/meta#nsPrefix> ?prefix }";
	$.ajax({
		url: "sparql",
		data: { "query": query, "type": "json"},
		datatype: "json",
		beforeSend : function (xhr) {
    		xhr.setRequestHeader('Accept', 'application/sparql-results+json');
		},
		error: function(xhr, textStatus, errorThrown){
			$("#results").html(xhr.responseText);
		},
		success: function(data){
			var bindings = data.results.bindings;
			for (var i = 0; i < bindings.length; i++){
				var binding = bindings[i];
				defaultNamespaces.push("PREFIX ", binding["prefix"].value, ": <", binding["ns"].value, ">\n");
			}
			defaultNamespaces = defaultNamespaces.join("");
		}
	});

    // create map
    map = new google.maps.Map(
    		document.getElementById("map"),
    		{ zoom: 11,
    		  center: latlng,
    		  mapTypeId: google.maps.MapTypeId.ROADMAP
    		});

    // switch overlay on zoom
	google.maps.event.addListener(map, 'zoom_changed', function(){
		if (searchGonzo){
			searchGonzo.setMap(null);
		}
		var zoom = map.getZoom();
		if (zoom < 10){
			gonzo1.setMap(null);
			gonzo2.setMap(null);
			gonzo3.setMap(null);
			gonzo4.setMap(map);
			activeGonzo = gonzo4;

		}else if (zoom < 11){
			gonzo1.setMap(null);
			gonzo2.setMap(null);
			gonzo3.setMap(map);
			gonzo4.setMap(null);
			activeGonzo = gonzo3;

		}else if (zoom < 13){
			gonzo1.setMap(null);
			gonzo2.setMap(map);
			gonzo3.setMap(null);
			gonzo4.setMap(null);
			activeGonzo = gonzo2;

		}else{
			gonzo1.setMap(map);
			gonzo2.setMap(null);
			gonzo3.setMap(null);
			gonzo4.setMap(null);
			activeGonzo = gonzo1;
		}
	});

	// init tabs
	//$(".tab_content").hide(); //Hide all content
	//$("ul.tabs li:first").addClass("active").show(); //Activate first tab
	//$(".tab_content:first").show(); //Show first tab content

	//On Click Event
	$("ul.tabs li").live("click", function() {
		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content

		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active ID content
		return false;
	});

	// get comments
	initNamespaces("sparql", function(){
		var query = prefixes + "SELECT ?area ?comment WHERE { ?area rdf:type dimension:Alue ; dc:description ?comment . }";
		querySparql("sparql", query, function(data){
			var bindings = data.results.bindings;
			for (var i = 0; i < bindings.length; i++){
				var binding = bindings[i];
				var area = getReadableURI(binding["area"].value);
				comments[area.substring(area.indexOf(":")+1)] = binding["comment"].value;
			}
		});
	});
	// get DBpedia comments
	initNamespaces("sparql", function(){
		var query = prefixes + "SELECT ?area ?comment WHERE { ?area owl:sameAs ?area2 . ?area2 rdfs:comment ?comment }";
		querySparql("sparql", query, function(data){
			var bindings = data.results.bindings;
			for (var i = 0; i < bindings.length; i++){
				var binding = bindings[i];
				var area = getReadableURI(binding["area"].value);
				dbpediateComments[area.substring(area.indexOf(":")+1)] = binding["comment"].value;
			}
		});
	});

	// get level 1 polygons
	$.ajax({
		url: "areas", data: {level: "1"}, datatype: "json",
		success: function(geo){
			gonzo1 = createOverlay(geo);
		}
	});

	// get level 2 polygons
	$.ajax({
		url: "areas", data: {level: "2"}, datatype: "json",
		success: function(geo){
			gonzo2 = createOverlay(geo);
		}
	});

	// get level 3 polygons
	$.ajax({
		url: "areas", data: {level: "3"}, datatype: "json",
		success: function(geo){
			gonzo3 = createOverlay(geo);
			gonzo3.setMap(map);
			activeGonzo = gonzo3;
		}
	});

	// get level 4 polygons
	$.ajax({
		url: "areas", data: {level: "4"}, datatype: "json",
		success: function(geo){
			gonzo4 = createOverlay(geo);
		}
	});
});

function createOverlay(geo){
	var length = geo.features.length;
	for (var i = 0; i < length; i++){
		var feature = geo.features[i];
		feature.strokeColor = "#000000";
		feature.strokeOpacity = 0.8;
		feature.strokeWeight = 1;
		feature.strokeWidth = 1;
		feature.fillColor = "#FFC0C0";
		feature.fillOpacity = 0.1;
	}
	return new PolyGonzo.PgOverlay({
		map: map,
		geo: geo,
		events: {
			mousemove: mouseOverFeature,
			click: clickOnFeature
		}
	});
}

function mouseOverFeature(event, where) {
	var feature = where && where.feature;
	if( feature ) {
		if (feature.properties.code != overArea){
			overArea = feature.properties.code;
			var centroid = feature.properties.center;
			var latlng = new google.maps.LatLng( centroid[1], centroid[0] );
			if (marker) marker.setMap(null);

			/*marker = new google.maps.Marker( {
				position: latlng,
				map: map,
				title: feature.properties.name } );*/

			marker = new MarkerWithLabel({
			    position: latlng,
			    map: map,
			    icon: null,
			    labelAnchor: new google.maps.Point(22, 0),
			    labelContent: feature.properties.name,
			    labelClass: "label",
			});

			google.maps.event.addListener(marker, 'click', function(){
				clickOnFeature(null, {feature: feature});
			});

			// set coordinates to that of selected feature
			geoOverlay.features[0].properties = feature.properties;
			geoOverlay.features[0].geometry = feature.geometry;

			if (!searchGonzo){
				searchGonzo = new PolyGonzo.PgOverlay({
					map: map,
					geo: geoOverlay,
					events: {
						mousemove: mouseOverFeature,
						click: clickOnFeature
					}
				});
			}
			searchGonzo.setMap(map);
		}
	}else{
		if (marker) marker.setMap(null);
		if (searchGonzo){
			searchGonzo.setMap(null);
		}
	}
}

function clickOnFeature(event, where) {
	var feature = where && where.feature;
	if (feature){
		var props = feature.properties;
		var code = props.code;
		clickedArea = code;
		if (!statistics[code]){
			// initial display

			var qry = [];
			qry.push(defaultNamespaces)
			qry.push("SELECT ?ikl ?val WHERE {\n");
		    qry.push("  ?item scv:dimension vuosi:_2009 , alue:",code," , ?ik ; rdf:value ?val .\n");
		    qry.push("  ?ik rdf:type dimension:Ikäryhmä ; dc:title ?ikl . \n");
		    qry.push("}\n");
		    qry = qry.join("");

			updateInfo(props, null);
			$.ajax({
				url: "sparql",
				data: { "query": qry, "type": "json"},
				datatype: "json",
				beforeSend : function (xhr) {
		    		xhr.setRequestHeader('Accept', 'application/sparql-results+json');
				},
				success: function(sparqlResults){
					var data = [];
					var bindings = sparqlResults.results.bindings;
					for (var i = 0; i < bindings.length; i++){
						var binding = bindings[i];
						var val = binding["val"].value;
						if (val == '..' || val == '.') {
							binding["val"].value = '0';
						}
						data.push( { label: binding["ikl"].value, value:  parseInt(binding["val"].value) } );
					}
					statistics[code] = data;
					if (code == clickedArea){
						updateInfo(props, data);
					}
				}
			});
		}else{
			updateInfo(props, statistics[code]);
		}
	}
}

function updateInfo(props, areaData){
	var content = [];
	content.push("
"+props.name+"
");

	// tabs
	content.push("
");
	if (areaData){
		content.push("
Tilastot
");
	}
	if (comments[props.code]){
		content.push("
Kuvaus
");
	}
	if (dbpediateComments[props.code]){
		content.push("
DBpedia
");
	}
	content.push("
");

	// tab container
	content.push("
");
	if (areaData){
		// calculate max
		var length = areaData.length;
		var max = 0;
		for (var i = 1; i < length; i++){
			var entry = areaData[i];
			if (entry.value > max){
				max = entry.value;
			}
		}

		// render table
		content.push("
");
		content.push("
Väestö ikärymittäin (2009)
");
		if (max > 0) {
			content.push("
");
			for (var i = 1; i < length; i++){
				var entry = areaData[i];
				content.push("
");
				content.push("", entry.label, "	");
				content.push("", entry.value, "	");
				content.push("

	");
				content.push("
");
			}
			content.push("
Yhteensä	", max, "
");
			content.push("
");
		}else{
			content.push("
Ei tietoa
");
		}
		content.push("
");
	}
	if (comments[props.code]){
		content.push("
");
		content.push(comments[props.code]);
		content.push("
");
	}
	if (dbpediateComments[props.code]){
		content.push("
");
		content.push(dbpediateComments[props.code]);
		content.push("
");
	}

	content.push("
");

	$("#info").html(content.join(""));
}
<commit_msg>Fixed sum<commit_after>var map = null;
var overArea = null;
var clickedArea = null;
var marker = null;
var gonzo1, gonzo2, gongo3, gonzo4;

var activeGonzo = null;

var defaultNamespaces = [];

var geoOverlay = {
		type: "FeatureCollection",
		properties: { },
		features: [ {
			strokeColor: "#000000",
			strokeOpacity: 0.8,
			strokeWeight: 2,
			strokeWidth: 2,
			fillColor: "#FFC0C0",
			fillOpacity: 0.2,
		    type: "Feature",
		    properties: {},
		    geometry: {type:"MultiPolygon", coordinates:[]}
		} ]
	};

var searchGonzo = null;

// area data
var comments = {};
var dbpediateComments = {};
var statistics = {};

$(document).ready(function(){
    var latlng = new google.maps.LatLng(60.1662735988013, 24.93207843548);

	// get namespaces from SPARQL endpoint
	var query = "SELECT ?ns ?prefix WHERE { ?ns <http://data.mysema.com/schemas/meta#nsPrefix> ?prefix }";
	$.ajax({
		url: "sparql",
		data: { "query": query, "type": "json"},
		datatype: "json",
		beforeSend : function (xhr) {
    		xhr.setRequestHeader('Accept', 'application/sparql-results+json');
		},
		error: function(xhr, textStatus, errorThrown){
			$("#results").html(xhr.responseText);
		},
		success: function(data){
			var bindings = data.results.bindings;
			for (var i = 0; i < bindings.length; i++){
				var binding = bindings[i];
				defaultNamespaces.push("PREFIX ", binding["prefix"].value, ": <", binding["ns"].value, ">\n");
			}
			defaultNamespaces = defaultNamespaces.join("");
		}
	});

    // create map
    map = new google.maps.Map(
    		document.getElementById("map"),
    		{ zoom: 11,
    		  center: latlng,
    		  mapTypeId: google.maps.MapTypeId.ROADMAP
    		});

    // switch overlay on zoom
	google.maps.event.addListener(map, 'zoom_changed', function(){
		if (searchGonzo){
			searchGonzo.setMap(null);
		}
		var zoom = map.getZoom();
		if (zoom < 10){
			gonzo1.setMap(null);
			gonzo2.setMap(null);
			gonzo3.setMap(null);
			gonzo4.setMap(map);
			activeGonzo = gonzo4;

		}else if (zoom < 11){
			gonzo1.setMap(null);
			gonzo2.setMap(null);
			gonzo3.setMap(map);
			gonzo4.setMap(null);
			activeGonzo = gonzo3;

		}else if (zoom < 13){
			gonzo1.setMap(null);
			gonzo2.setMap(map);
			gonzo3.setMap(null);
			gonzo4.setMap(null);
			activeGonzo = gonzo2;

		}else{
			gonzo1.setMap(map);
			gonzo2.setMap(null);
			gonzo3.setMap(null);
			gonzo4.setMap(null);
			activeGonzo = gonzo1;
		}
	});

	// init tabs
	//$(".tab_content").hide(); //Hide all content
	//$("ul.tabs li:first").addClass("active").show(); //Activate first tab
	//$(".tab_content:first").show(); //Show first tab content

	//On Click Event
	$("ul.tabs li").live("click", function() {
		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content

		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active ID content
		return false;
	});

	// get comments
	initNamespaces("sparql", function(){
		var query = prefixes + "SELECT ?area ?comment WHERE { ?area rdf:type dimension:Alue ; dc:description ?comment . }";
		querySparql("sparql", query, function(data){
			var bindings = data.results.bindings;
			for (var i = 0; i < bindings.length; i++){
				var binding = bindings[i];
				var area = getReadableURI(binding["area"].value);
				comments[area.substring(area.indexOf(":")+1)] = binding["comment"].value;
			}
		});
	});
	// get DBpedia comments
	initNamespaces("sparql", function(){
		var query = prefixes + "SELECT ?area ?comment WHERE { ?area owl:sameAs ?area2 . ?area2 rdfs:comment ?comment }";
		querySparql("sparql", query, function(data){
			var bindings = data.results.bindings;
			for (var i = 0; i < bindings.length; i++){
				var binding = bindings[i];
				var area = getReadableURI(binding["area"].value);
				dbpediateComments[area.substring(area.indexOf(":")+1)] = binding["comment"].value;
			}
		});
	});

	// get level 1 polygons
	$.ajax({
		url: "areas", data: {level: "1"}, datatype: "json",
		success: function(geo){
			gonzo1 = createOverlay(geo);
		}
	});

	// get level 2 polygons
	$.ajax({
		url: "areas", data: {level: "2"}, datatype: "json",
		success: function(geo){
			gonzo2 = createOverlay(geo);
		}
	});

	// get level 3 polygons
	$.ajax({
		url: "areas", data: {level: "3"}, datatype: "json",
		success: function(geo){
			gonzo3 = createOverlay(geo);
			gonzo3.setMap(map);
			activeGonzo = gonzo3;
		}
	});

	// get level 4 polygons
	$.ajax({
		url: "areas", data: {level: "4"}, datatype: "json",
		success: function(geo){
			gonzo4 = createOverlay(geo);
		}
	});
});

function createOverlay(geo){
	var length = geo.features.length;
	for (var i = 0; i < length; i++){
		var feature = geo.features[i];
		feature.strokeColor = "#000000";
		feature.strokeOpacity = 0.8;
		feature.strokeWeight = 1;
		feature.strokeWidth = 1;
		feature.fillColor = "#FFC0C0";
		feature.fillOpacity = 0.1;
	}
	return new PolyGonzo.PgOverlay({
		map: map,
		geo: geo,
		events: {
			mousemove: mouseOverFeature,
			click: clickOnFeature
		}
	});
}

function mouseOverFeature(event, where) {
	var feature = where && where.feature;
	if( feature ) {
		if (feature.properties.code != overArea){
			overArea = feature.properties.code;
			var centroid = feature.properties.center;
			var latlng = new google.maps.LatLng( centroid[1], centroid[0] );
			if (marker) marker.setMap(null);

			/*marker = new google.maps.Marker( {
				position: latlng,
				map: map,
				title: feature.properties.name } );*/

			marker = new MarkerWithLabel({
			    position: latlng,
			    map: map,
			    icon: null,
			    labelAnchor: new google.maps.Point(22, 0),
			    labelContent: feature.properties.name,
			    labelClass: "label",
			});

			google.maps.event.addListener(marker, 'click', function(){
				clickOnFeature(null, {feature: feature});
			});

			// set coordinates to that of selected feature
			geoOverlay.features[0].properties = feature.properties;
			geoOverlay.features[0].geometry = feature.geometry;

			if (!searchGonzo){
				searchGonzo = new PolyGonzo.PgOverlay({
					map: map,
					geo: geoOverlay,
					events: {
						mousemove: mouseOverFeature,
						click: clickOnFeature
					}
				});
			}
			searchGonzo.setMap(map);
		}
	}else{
		if (marker) marker.setMap(null);
		if (searchGonzo){
			searchGonzo.setMap(null);
		}
	}
}

function clickOnFeature(event, where) {
	var feature = where && where.feature;
	if (feature){
		var props = feature.properties;
		var code = props.code;
		clickedArea = code;
		if (!statistics[code]){
			// initial display

			var qry = [];
			qry.push(defaultNamespaces)
			qry.push("SELECT ?ikl ?val WHERE {\n");
		    qry.push("  ?item scv:dimension vuosi:_2009 , alue:",code," , ?ik ; rdf:value ?val .\n");
		    qry.push("  ?ik rdf:type dimension:Ikäryhmä ; dc:title ?ikl . \n");
		    qry.push("}\n");
		    qry = qry.join("");

			updateInfo(props, null);
			$.ajax({
				url: "sparql",
				data: { "query": qry, "type": "json"},
				datatype: "json",
				beforeSend : function (xhr) {
		    		xhr.setRequestHeader('Accept', 'application/sparql-results+json');
				},
				success: function(sparqlResults){
					var data = [];
					var bindings = sparqlResults.results.bindings;
					for (var i = 0; i < bindings.length; i++){
						var binding = bindings[i];
						var val = binding["val"].value;
						if (val == '..' || val == '.') {
							binding["val"].value = '0';
						}
						data.push( { label: binding["ikl"].value, value:  parseInt(binding["val"].value) } );
					}
					statistics[code] = data;
					if (code == clickedArea){
						updateInfo(props, data);
					}
				}
			});
		}else{
			updateInfo(props, statistics[code]);
		}
	}
}

function updateInfo(props, areaData){
	var content = [];
	content.push("
"+props.name+"
");

	// tabs
	content.push("
");
	if (areaData){
		content.push("
Tilastot
");
	}
	if (comments[props.code]){
		content.push("
Kuvaus
");
	}
	if (dbpediateComments[props.code]){
		content.push("
DBpedia
");
	}
	content.push("
");

	// tab container
	content.push("
");
	if (areaData){
		// calculate max
		var length = areaData.length;
		var max = 0;
		var sum = 0;
		for (var i = 0; i < length; i++){
			var entry = areaData[i];
			if (entry.label == "Väestö yhteensä"){
				sum = entry.value;
			} else if (entry.value > max){
				max = entry.value;
			}
		}

		// render table
		content.push("
");
		content.push("
Väestö ikäryhmittäin (2009)
");
		if (max > 0) {
			content.push("
");
			for (var i = 0; i < length; i++){
				var entry = areaData[i];
				if (entry.label != "Väestö yhteensä"){
					content.push("
");
					content.push("", entry.label, "	");
					content.push("", entry.value, "	");
					content.push("

	");
					content.push("
");
				}
			}
			content.push("
Yhteensä	", sum, "
");
			content.push("
");
		}else{
			content.push("
Ei tietoa
");
		}
		content.push("
");
	}
	if (comments[props.code]){
		content.push("
");
		content.push(comments[props.code]);
		content.push("
");
	}
	if (dbpediateComments[props.code]){
		content.push("
");
		content.push(dbpediateComments[props.code]);
		content.push("
");
	}

	content.push("
");

	$("#info").html(content.join(""));
}
<|endoftext|>


<commit_before>/* Visualisation types for which we don't load the whole dataset, but only request aggregated
** data from the backend */
const aggregationOnlyVisualisationTypes = [
  'pivot table',
  'pie',
  'donut',
  'map',
  'line',
  'area',
  'bar',
  'scatter',
  'bubble',
];

export default aggregationOnlyVisualisationTypes;

<commit_msg>#1854 polararea doesnt appear on dashboard<commit_after>/* Visualisation types for which we don't load the whole dataset, but only request aggregated
** data from the backend */
const aggregationOnlyVisualisationTypes = [
  'pivot table',
  'pie',
  'donut',
  'map',
  'line',
  'area',
  'bar',
  'scatter',
  'bubble',
  'polararea',
];

export default aggregationOnlyVisualisationTypes;

<|endoftext|>


<commit_before>const paramsProc = require('n-params-processor');
const logger = require('./_common/utils/logger');

module.exports = (app) => {
  require('./users/routes')(app);

  app.use((req, res) => {
    res.status(404).send({ message: 'Invalid end point' });
  });

  // eslint-disable-next-line max-params, no-unused-vars
  app.use((err, req, res, next) => {
    if (err instanceof paramsProc.ParamsProcessorError) {
      return res.status(422).send({ reason: err.message });
    }
    if (err.statusCode < 500) {
      return res.status(err.statusCode).send({
        reason: err.message,
        info: err.info
      });
    }

    // istanbul ignore next
    switch (process.env.NODE_ENV) {
      case 'test':
      case 'development':
        logger.error('Unexpected server error', err, err.stack);
        break;
      case 'production':
        logger.error('Unexpected server error', err);
        break;
    }
    res.status(err.statusCode || 500).send({ message: 'Unexpected server error' });
  });
};
<commit_msg>return error.message instead of error.reason<commit_after>const paramsProc = require('n-params-processor');
const logger = require('./_common/utils/logger');

module.exports = (app) => {
  require('./users/routes')(app);

  app.use((req, res) => {
    res.status(404).send({ message: 'Invalid end point' });
  });

  // eslint-disable-next-line max-params, no-unused-vars
  app.use((err, req, res, next) => {
    if (err instanceof paramsProc.ParamsProcessorError) {
      return res.status(422).send({ message: err.message });
    }
    if (err.statusCode < 500) {
      return res.status(err.statusCode).send({
        message: err.message,
        info: err.info
      });
    }

    // istanbul ignore next
    switch (process.env.NODE_ENV) {
      case 'test':
      case 'development':
        logger.error('Unexpected server error', err, err.stack);
        break;
      case 'production':
        logger.error('Unexpected server error', err);
        break;
    }
    res.status(err.statusCode || 500).send({ message: 'Unexpected server error' });
  });
};
<|endoftext|>


<commit_before>define([
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/array',
    'dojo/topic',
    'dojo/aspect',

    'jimu/WidgetManager',
    'jimu/ConfigManager',
    'jimu/MapManager',
    'jimu/utils',
    'jimu/LayerInfos/LayerInfos',

    'dojo/i18n!jimu/nls/main',

    'config/wabapp-config'

], function (
    declare,
    lang,
    array,
    topic,
    aspect,

    WidgetManager,
    ConfigManager,
    MapManager,
    jimuUtils,
    LayerInfos,

    mainBundle,

    wabConfig
) {

    return declare(null, {

        wabWidgetManager: null,

        startup: function () {
            this.inherited(arguments);
            if (this.mapDeferred) {
                this.mapDeferred.then(lang.hitch(this, '_configureWAB'));
            }
            aspect.after(this, '_setWidgetOptions', function (options) {
                if (options.widgetManager && this.wabWidgetManager) {
                    options.widgetManager = this.wabWidgetManager;
                }
                return options;
            });
        },

        _configureWAB: function () {
            //minimal configuration of global vars
            // polluting the global namespace is bad! ;)
            window.jimuConfig = {
                layoutId: this.config.layout.map || 'mapCenter',
                breakPoints: [0]
            };
            window.jimuNls = mainBundle;
            window.isRTL = wabConfig.isRTL;

            var pathparts = window.location.pathname.split('/');
            pathparts.pop();
            window.appInfo = {
                appPath: pathparts.join('/') + '/'
            };

            // make the map look like a "webmap"
            if (!this.map.itemInfo) {
                this._createMapItemInfo();
            }
            LayerInfos.getInstance(this.map, this.map.itemInfo);

            //wabConfig.map.layers = this.getOperationalLayers();
            wabConfig.map.mapOptions = this.config.mapOptions;

            // create a minimal configuration
            var appConfig = this._createAppConfig();

            var mm = MapManager.getInstance({
                appConfig: appConfig
            });
            mm.map = this.map;

            this.wabWidgetManager = WidgetManager.getInstance();
            this.wabWidgetManager.map = this.map;
            this.wabWidgetManager.appConfig = appConfig;

            // tap into the map's infoWindowOnClick method
            if (this.mapClickMode.defaultMode === 'identify') {
                aspect.after(this.map, 'setInfoWindowOnClick', lang.hitch(this, function () {
                    var enabled = this.map._params.showInfoWindowOnClick;
                    if (enabled) {
                        topic.publish('mapClickMode/setDefault');
                    } else {
                        topic.publish('mapClickMode/setCurrent', 'none');
                    }
                }));
            }
        },

        _createAppConfig: function () {
            var cm = new ConfigManager();
            var appConfig = cm._addDefaultValues(wabConfig);
            appConfig.getConfigElementById = lang.hitch(cm, function (id) {
                return jimuUtils.getConfigElementById(this, id);
            });

            appConfig.getConfigElementsByName = lang.hitch(cm, function (name) {
                return jimuUtils.getConfigElementsByName(this, name);
            });

            appConfig.visitElement = lang.hitch(cm, function (cb) {
                jimuUtils.visitElement(this, cb);
            });
            cm.appConfig = appConfig;

            return appConfig;
        },

        _createMapItemInfo: function () {
            var basemap = this.map.getBasemap();
            this.map.itemInfo = {
                item: {
                    title: '',
                    description: ''
                },
                itemData: {
                    baseMap: {
                        baseMapLayers: this._getBaseMapLayers(),
                        title: basemap
                    },
                    operationLayers: this._getOperationalLayers(),
                    bookmarks: []
                }
            };
        },

        // get all the operational layers
        _getOperationalLayers: function () {
            var layers = [], layer;
            array.forEach(this.config.operationalLayers, lang.hitch(this, function (opLayer) {
                layer = this.map.getLayer(opLayer.options.id);
                if (layer) {
                    layers.push({
                        id: layer.id,
                        opacity: layer.opacity,
                        title: opLayer.title,
                        url: layer.url,
                        visibility: layer.visibility
                    });
                }
            }));
            return layers;
        },

        // get the basemap layer(s)
        _getBaseMapLayers: function () {
            var layers = [], layer;
            array.forEach(this.map.basemapLayerIds, lang.hitch(this, function (layerId) {
                layer = this.map.getLayer(layerId);
                if (layer) {
                    layers.push({
                        id: layer.id,
                        opacity: layer.opacity,
                        url: layer.url,
                        visibility: layer.visibility
                    });
                }
            }));
            return layers;
        }
    });
});<commit_msg>Add the appConfig as a global window variable<commit_after>define([
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/array',
    'dojo/topic',
    'dojo/aspect',

    'jimu/WidgetManager',
    'jimu/ConfigManager',
    'jimu/MapManager',
    'jimu/utils',
    'jimu/LayerInfos/LayerInfos',

    'dojo/i18n!jimu/nls/main',

    'config/wabapp-config'

], function (
    declare,
    lang,
    array,
    topic,
    aspect,

    WidgetManager,
    ConfigManager,
    MapManager,
    jimuUtils,
    LayerInfos,

    mainBundle,

    wabConfig
) {

    return declare(null, {

        wabWidgetManager: null,

        startup: function () {
            this.inherited(arguments);
            if (this.mapDeferred) {
                this.mapDeferred.then(lang.hitch(this, '_configureWAB'));
            }
            aspect.after(this, '_setWidgetOptions', function (options) {
                if (options.widgetManager && this.wabWidgetManager) {
                    options.widgetManager = this.wabWidgetManager;
                }
                return options;
            });
        },

        _configureWAB: function () {
            //minimal configuration of global vars
            // polluting the global namespace is bad! ;)
            window.jimuConfig = {
                layoutId: this.config.layout.map || 'mapCenter',
                breakPoints: [0]
            };
            window.jimuNls = mainBundle;
            window.isRTL = wabConfig.isRTL;

            var pathparts = window.location.pathname.split('/');
            pathparts.pop();
            window.appInfo = {
                appPath: pathparts.join('/') + '/'
            };

            // make the map look like a "webmap"
            if (!this.map.itemInfo) {
                this._createMapItemInfo();
            }
            LayerInfos.getInstance(this.map, this.map.itemInfo);

            //wabConfig.map.layers = this.getOperationalLayers();
            wabConfig.map.mapOptions = this.config.mapOptions;

            // create a minimal configuration
            var appConfig = this._createAppConfig();

            var mm = MapManager.getInstance({
                appConfig: appConfig
            });
            mm.map = this.map;

            this.wabWidgetManager = WidgetManager.getInstance();
            this.wabWidgetManager.map = this.map;
            this.wabWidgetManager.appConfig = appConfig;

            // tap into the map's infoWindowOnClick method
            if (this.mapClickMode.defaultMode === 'identify') {
                aspect.after(this.map, 'setInfoWindowOnClick', lang.hitch(this, function () {
                    var enabled = this.map._params.showInfoWindowOnClick;
                    if (enabled) {
                        topic.publish('mapClickMode/setDefault');
                    } else {
                        topic.publish('mapClickMode/setCurrent', 'none');
                    }
                }));
            }
        },

        _createAppConfig: function () {
            var cm = new ConfigManager();
            var appConfig = cm._addDefaultValues(wabConfig);
            appConfig.getConfigElementById = lang.hitch(cm, function (id) {
                return jimuUtils.getConfigElementById(this, id);
            });

            appConfig.getConfigElementsByName = lang.hitch(cm, function (name) {
                return jimuUtils.getConfigElementsByName(this, name);
            });

            appConfig.visitElement = lang.hitch(cm, function (cb) {
                jimuUtils.visitElement(this, cb);
            });
            cm.appConfig = appConfig;

            window.appConfig = appConfig;

            return appConfig;
        },

        _createMapItemInfo: function () {
            var basemap = this.map.getBasemap();
            this.map.itemInfo = {
                item: {
                    title: '',
                    description: ''
                },
                itemData: {
                    baseMap: {
                        baseMapLayers: this._getBaseMapLayers(),
                        title: basemap
                    },
                    operationLayers: this._getOperationalLayers(),
                    bookmarks: []
                }
            };
        },

        // get all the operational layers
        _getOperationalLayers: function () {
            var layers = [], layer;
            array.forEach(this.config.operationalLayers, lang.hitch(this, function (opLayer) {
                layer = this.map.getLayer(opLayer.options.id);
                if (layer) {
                    layers.push({
                        id: layer.id,
                        opacity: layer.opacity,
                        title: opLayer.title,
                        url: layer.url,
                        visibility: layer.visibility
                    });
                }
            }));
            return layers;
        },

        // get the basemap layer(s)
        _getBaseMapLayers: function () {
            var layers = [], layer;
            array.forEach(this.map.basemapLayerIds, lang.hitch(this, function (layerId) {
                layer = this.map.getLayer(layerId);
                if (layer) {
                    layers.push({
                        id: layer.id,
                        opacity: layer.opacity,
                        url: layer.url,
                        visibility: layer.visibility
                    });
                }
            }));
            return layers;
        }
    });
});<|endoftext|>


<commit_before>describe("About Arrays", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should create arrays", function() {
    var emptyArray = [];
    expect(typeof(emptyArray)).toBe('object'); //A mistake? - http://javascript.crockford.com/remedial.html
    expect(emptyArray.length).toBe(0);

    var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]];
    expect(multiTypeArray[0]).toBe(0);
    expect(multiTypeArray[2]).toBe("two");
    expect(multiTypeArray[3]()).toBe(3);
    expect(multiTypeArray[4].value1).toBe(4);
    expect(multiTypeArray[4]["value2"]).toBe(5);
    expect(multiTypeArray[5][0]).toBe(6);
  });

  it("should understand array literals", function () {
    var array = [];
    expect(array).toEqual([]);

    array[0] = 1;
    expect(array).toEqual([1]);

    array[1] = 2;
    expect(array).toEqual([1,2]);

    array.push(3);
    expect(array).toEqual([1,2,3]);
  });

  it("should understand array length", function () {
    var fourNumberArray = [1, 2, 3, 4];

    expect(fourNumberArray.length).toBe(4);
    fourNumberArray.push(5, 6);
    expect(fourNumberArray.length).toBe(6);

    var tenEmptyElementArray = new Array(10);
    expect(tenEmptyElementArray.length).toBe(10);

    tenEmptyElementArray.length = 5;
    expect(tenEmptyElementArray.length).toBe(5);
  });

  it("should slice arrays", function () {
    var array = ["peanut", "butter", "and", "jelly"];

    expect(array.slice(0, 1)).toEqual(FILL_ME_IN);
    expect(array.slice(0, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 2)).toEqual(FILL_ME_IN);
    expect(array.slice(2, 20)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 0)).toEqual(FILL_ME_IN);
    expect(array.slice(3, 100)).toEqual(FILL_ME_IN);
    expect(array.slice(5, 1)).toEqual(FILL_ME_IN);
  });

  it("should know array references", function () {
    var array = [ "zero", "one", "two", "three", "four", "five" ];

    function passedByReference(refArray) {
        refArray[1] = "changed in function";
    }
    passedByReference(array);
    expect(array[1]).toBe(FILL_ME_IN);

    var assignedArray = array;
    assignedArray[5] = "changed in assignedArray";
    expect(array[5]).toBe(FILL_ME_IN);

    var copyOfArray = array.slice();
    copyOfArray[3] = "changed in copyOfArray";
    expect(array[3]).toBe(FILL_ME_IN);
  });

  it("should push and pop", function () {
    var array = [1, 2];
    array.push(3);

    expect(array).toEqual(FILL_ME_IN);

    var poppedValue = array.pop();
    expect(poppedValue).toBe(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should know about shifting arrays", function () {
    var array = [1, 2];

    array.unshift(3);
    expect(array).toEqual(FILL_ME_IN);

    var shiftedValue = array.shift();
    expect(shiftedValue).toEqual(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });
});
<commit_msg>need sleep<commit_after>describe("About Arrays", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should create arrays", function() {
    var emptyArray = [];
    expect(typeof(emptyArray)).toBe('object'); //A mistake? - http://javascript.crockford.com/remedial.html
    expect(emptyArray.length).toBe(0);

    var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]];
    expect(multiTypeArray[0]).toBe(0);
    expect(multiTypeArray[2]).toBe("two");
    expect(multiTypeArray[3]()).toBe(3);
    expect(multiTypeArray[4].value1).toBe(4);
    expect(multiTypeArray[4]["value2"]).toBe(5);
    expect(multiTypeArray[5][0]).toBe(6);
  });

  it("should understand array literals", function () {
    var array = [];
    expect(array).toEqual([]);

    array[0] = 1;
    expect(array).toEqual([1]);

    array[1] = 2;
    expect(array).toEqual([1,2]);

    array.push(3);
    expect(array).toEqual([1,2,3]);
  });

  it("should understand array length", function () {
    var fourNumberArray = [1, 2, 3, 4];

    expect(fourNumberArray.length).toBe(4);
    fourNumberArray.push(5, 6);
    expect(fourNumberArray.length).toBe(6);

    var tenEmptyElementArray = new Array(10);
    expect(tenEmptyElementArray.length).toBe(10);

    tenEmptyElementArray.length = 5;
    expect(tenEmptyElementArray.length).toBe(5);
  });

  it("should slice arrays", function () {
    var array = ["peanut", "butter", "and", "jelly"];

    expect(array.slice(0, 1)).toEqual(['peanut']);
    expect(array.slice(0, 2)).toEqual(['peanut', "butter"]);
    expect(array.slice(2, 2)).toEqual([]);
    expect(array.slice(2, 20)).toEqual(['and', 'jelly']);
    expect(array.slice(3, 0)).toEqual([]);
    expect(array.slice(3, 100)).toEqual(['jelly']);
    expect(array.slice(5, 1)).toEqual([]);
  });

  it("should know array references", function () {
    var array = [ "zero", "one", "two", "three", "four", "five" ];

    function passedByReference(refArray) {
        refArray[1] = "changed in function";
    }
    passedByReference(array);
    expect(array[1]).toBe(FILL_ME_IN);

    var assignedArray = array;
    assignedArray[5] = "changed in assignedArray";
    expect(array[5]).toBe(FILL_ME_IN);

    var copyOfArray = array.slice();
    copyOfArray[3] = "changed in copyOfArray";
    expect(array[3]).toBe(FILL_ME_IN);
  });

  it("should push and pop", function () {
    var array = [1, 2];
    array.push(3);

    expect(array).toEqual(FILL_ME_IN);

    var poppedValue = array.pop();
    expect(poppedValue).toBe(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });

  it("should know about shifting arrays", function () {
    var array = [1, 2];

    array.unshift(3);
    expect(array).toEqual(FILL_ME_IN);

    var shiftedValue = array.shift();
    expect(shiftedValue).toEqual(FILL_ME_IN);
    expect(array).toEqual(FILL_ME_IN);
  });
});
<|endoftext|>