<commit_before>// This file is part of the Shapy project.
// Licensing information can be found in the LICENSE file.
// (C) 2015 The Shapy Team. All rights reserved.
goog.provide('shapy.editor.Viewport');

goog.require('goog.math.Rect');
goog.require('goog.math.Vec2');
goog.require('goog.vec.Quaternion');

/**
 * A single viewport, our eye into the world.
 *
 * @constructor
 *
 * @param {string}                      name Name of the viewport.
 * @param {!shapy.editor.Viewport.Type} type Type of the viewport.
 */
shapy.editor.Viewport = function(name, type) {
  /**
   * @public {!shapy.editor.Viewport.Type}
   * @const
   */
  this.type = type;

  /**
   * The name of the viewport.
   * @public {string}
   * @const
   */
  this.name = name;

  /**
   * Flag indicating if the viewport is active, i.e. it is highlighted.
   * @public {boolean}
   */
  this.active = false;

  /**
   * Group select rectangle.
   * @public {goog.math.Rect}
   */
  this.group = null;

  /**
   * Last mouse click position.
   * @private {!goog.math.Vec2}
   */
  this.lastClick_ = new goog.math.Vec2(0, 0);

  /**
   * The size and position of the viewport.
   * @public {!goog.math.Size}
   * @const
   */
  this.rect = new goog.math.Rect(0, 0, 0, 0);

  /**
   * Current position of the mouse.
   * @private {!goog.math.Vec2}
   */
  this.currMousePos_ = new goog.math.Vec2(0, 0);

  /**
   * Last position of the mouse.
   * @private {!goog.math.Vec2}
   */
  this.lastMousePos_ = new goog.math.Vec2(0, 0);
};

/**
 * Resizes the viewport, specifying a new position and size.
 *
 * @param {number} x
 * @param {number} y
 * @param {number} w
 * @param {number} h
 */
shapy.editor.Viewport.prototype.resize = function(x, y, w, h) {
  this.rect.x = x;
  this.rect.y = y;
  this.rect.w = w;
  this.rect.h = h;
};

/**
 * Handles a mouse motion event.
 *
 * @param {number} x Mouse X coordinate.
 * @param {number} y Mouse Y coordinate.
 *
 * @return {boolean}
 */
shapy.editor.Viewport.prototype.mouseMove = function(x, y) {
  this.currMousePos_.x = x;
  this.currMousePos_.y = y;

  if (!this.group) {
    return false;
  }

  if (x > this.lastClick_.x) {
    this.group.width = x - this.lastClick_.x;
  } else {
    this.group.width = this.lastClick_.x - x;
    this.group.left = x;
  }

  if (y > this.lastClick_.y) {
    this.group.height = y - this.lastClick_.y;
  } else {
    this.group.height = this.lastClick_.y - y;
    this.group.top = y;
  }

  return this.group.width > 3 && this.group.height > 3;
};

/**
 * Handles a mouse enter event.
 *
 * @param {number} x Mouse X coordinate.
 * @param {number} y Mouse Y coordinate.
 */
shapy.editor.Viewport.prototype.mouseEnter = function(x, y) {
  this.group = null;
};

/**
 * Handles a mouse leave event.
 */
shapy.editor.Viewport.prototype.mouseLeave = function() {
  this.group = null;
};

/**
 * Handles a mouse press event.
 *
 * @param {number} x      Mouse X coordinate.
 * @param {number} y      Mouse Y coordinate.
 * @param {number} button Mouse button that was clicked.
 */
shapy.editor.Viewport.prototype.mouseDown = function(x, y, button) {
  this.lastClick_.x = x;
  this.lastClick_.y = y;
  this.currMousePos_.x = x;
  this.currMousePos_.y = y;
  this.lastMousePos_.x = x;
  this.lastMousePos_.y = y;

  if (button == 1) {
    this.group = new goog.math.Rect(x, y, 0, 0);
  }
};

/**
 * Handles a mouse release event.
 *
 * @param {number} x Mouse X coordinate.
 * @param {number} y Mouse Y coordinate.
 */
shapy.editor.Viewport.prototype.mouseUp = function(x, y) {
  this.group = null;
};

/**
 * Handles a mouse wheel event.
 *
 * @param {number} delta Mouse wheel delta value.
 */
shapy.editor.Viewport.prototype.mouseWheel = goog.abstractMethod;

/**
 * Recomputes the positions & sizes of all viewports.
 *
 * @param {number} kc Keycode
 */
shapy.editor.Viewport.prototype.keyDown = goog.abstractMethod;

/**
 * Destroys the viewport.
 */
shapy.editor.Viewport.prototype.destroy = function() {
};

/**
 * Enumeration of viewport types.
 * @enum {string}
 */
shapy.editor.Viewport.Type = {
  UV: 'uv',
  EDIT: 'edit'
};
<commit_msg>Empty implementation for keyDown.<commit_after>// This file is part of the Shapy project.
// Licensing information can be found in the LICENSE file.
// (C) 2015 The Shapy Team. All rights reserved.
goog.provide('shapy.editor.Viewport');

goog.require('goog.math.Rect');
goog.require('goog.math.Vec2');
goog.require('goog.vec.Quaternion');

/**
 * A single viewport, our eye into the world.
 *
 * @constructor
 *
 * @param {string}                      name Name of the viewport.
 * @param {!shapy.editor.Viewport.Type} type Type of the viewport.
 */
shapy.editor.Viewport = function(name, type) {
  /**
   * @public {!shapy.editor.Viewport.Type}
   * @const
   */
  this.type = type;

  /**
   * The name of the viewport.
   * @public {string}
   * @const
   */
  this.name = name;

  /**
   * Flag indicating if the viewport is active, i.e. it is highlighted.
   * @public {boolean}
   */
  this.active = false;

  /**
   * Group select rectangle.
   * @public {goog.math.Rect}
   */
  this.group = null;

  /**
   * Last mouse click position.
   * @private {!goog.math.Vec2}
   */
  this.lastClick_ = new goog.math.Vec2(0, 0);

  /**
   * The size and position of the viewport.
   * @public {!goog.math.Size}
   * @const
   */
  this.rect = new goog.math.Rect(0, 0, 0, 0);

  /**
   * Current position of the mouse.
   * @private {!goog.math.Vec2}
   */
  this.currMousePos_ = new goog.math.Vec2(0, 0);

  /**
   * Last position of the mouse.
   * @private {!goog.math.Vec2}
   */
  this.lastMousePos_ = new goog.math.Vec2(0, 0);
};

/**
 * Resizes the viewport, specifying a new position and size.
 *
 * @param {number} x
 * @param {number} y
 * @param {number} w
 * @param {number} h
 */
shapy.editor.Viewport.prototype.resize = function(x, y, w, h) {
  this.rect.x = x;
  this.rect.y = y;
  this.rect.w = w;
  this.rect.h = h;
};

/**
 * Handles a mouse motion event.
 *
 * @param {number} x Mouse X coordinate.
 * @param {number} y Mouse Y coordinate.
 *
 * @return {boolean}
 */
shapy.editor.Viewport.prototype.mouseMove = function(x, y) {
  this.currMousePos_.x = x;
  this.currMousePos_.y = y;

  if (!this.group) {
    return false;
  }

  if (x > this.lastClick_.x) {
    this.group.width = x - this.lastClick_.x;
  } else {
    this.group.width = this.lastClick_.x - x;
    this.group.left = x;
  }

  if (y > this.lastClick_.y) {
    this.group.height = y - this.lastClick_.y;
  } else {
    this.group.height = this.lastClick_.y - y;
    this.group.top = y;
  }

  return this.group.width > 3 && this.group.height > 3;
};

/**
 * Handles a mouse enter event.
 *
 * @param {number} x Mouse X coordinate.
 * @param {number} y Mouse Y coordinate.
 */
shapy.editor.Viewport.prototype.mouseEnter = function(x, y) {
  this.group = null;
};

/**
 * Handles a mouse leave event.
 */
shapy.editor.Viewport.prototype.mouseLeave = function() {
  this.group = null;
};

/**
 * Handles a mouse press event.
 *
 * @param {number} x      Mouse X coordinate.
 * @param {number} y      Mouse Y coordinate.
 * @param {number} button Mouse button that was clicked.
 */
shapy.editor.Viewport.prototype.mouseDown = function(x, y, button) {
  this.lastClick_.x = x;
  this.lastClick_.y = y;
  this.currMousePos_.x = x;
  this.currMousePos_.y = y;
  this.lastMousePos_.x = x;
  this.lastMousePos_.y = y;

  if (button == 1) {
    this.group = new goog.math.Rect(x, y, 0, 0);
  }
};

/**
 * Handles a mouse release event.
 *
 * @param {number} x Mouse X coordinate.
 * @param {number} y Mouse Y coordinate.
 */
shapy.editor.Viewport.prototype.mouseUp = function(x, y) {
  this.group = null;
};

/**
 * Handles a mouse wheel event.
 *
 * @param {number} delta Mouse wheel delta value.
 */
shapy.editor.Viewport.prototype.mouseWheel = goog.abstractMethod;

/**
 * Recomputes the positions & sizes of all viewports.
 *
 * @param {number} kc Keycode
 */
shapy.editor.Viewport.prototype.keyDown = function() {
};

/**
 * Destroys the viewport.
 */
shapy.editor.Viewport.prototype.destroy = function() {
};

/**
 * Enumeration of viewport types.
 * @enum {string}
 */
shapy.editor.Viewport.Type = {
  UV: 'uv',
  EDIT: 'edit'
};
<|endoftext|>


<commit_before>import PropTypes from 'proptypes'

export default {
  any: {
    options: {
      of: PropTypes.array.isRequired
    },
    parse(options, typeBuilders, schema) {
      const containsTypes = options.of.map(typeDef => {
        const typeBuilder = typeBuilders[typeDef.type]
        if (!typeBuilder) {
          throw new Error(`Invalid type: ${typeDef.type}.`)
        }
        return typeBuilder(typeDef, typeBuilders, schema)
      })
      return {of: containsTypes}
    }
  },
  reference: {
    primitive: 'string',
    options: {
      title: PropTypes.string,
      to: PropTypes.oneOfType([
        PropTypes.object,
        PropTypes.array
      ]).isRequired
    },
    parse(options, typeBuilders, schema) {
      const toTypeDefs = Array.isArray(options.to) ? options.to : [options.to]
      const toTypes = toTypeDefs.map(typeDef => {
        const typeBuilder = typeBuilders[typeDef.type]
        if (!typeBuilder) {
          throw new Error(
            `Missing type builder for ${typeDef.type}. Did you forget to declare the type "${typeDef.type}" in the schema?`
          )
        }
        return typeBuilder(typeDef, typeBuilders, schema)
      })
      return {to: toTypes}
    }
  },
  text: {
    primitive: 'string',
    options: {
      title: PropTypes.string,
      format: PropTypes.oneOf(['markdown', 'html', 'plain']),
      maxLength: PropTypes.number
    },
    defaultOptions: {
      format: 'plain'
    }
  }
}
<commit_msg>Add url, email and telephone to bundled types<commit_after>import PropTypes from 'proptypes'

export default {
  any: {
    options: {
      of: PropTypes.array.isRequired
    },
    parse(options, typeBuilders, schema) {
      const containsTypes = options.of.map(typeDef => {
        const typeBuilder = typeBuilders[typeDef.type]
        if (!typeBuilder) {
          throw new Error(`Invalid type: ${typeDef.type}.`)
        }
        return typeBuilder(typeDef, typeBuilders, schema)
      })
      return {of: containsTypes}
    }
  },
  reference: {
    primitive: 'string',
    options: {
      title: PropTypes.string,
      to: PropTypes.oneOfType([
        PropTypes.object,
        PropTypes.array
      ]).isRequired
    },
    parse(options, typeBuilders, schema) {
      const toTypeDefs = Array.isArray(options.to) ? options.to : [options.to]
      const toTypes = toTypeDefs.map(typeDef => {
        const typeBuilder = typeBuilders[typeDef.type]
        if (!typeBuilder) {
          throw new Error(
            `Missing type builder for ${typeDef.type}. Did you forget to declare the type "${typeDef.type}" in the schema?`
          )
        }
        return typeBuilder(typeDef, typeBuilders, schema)
      })
      return {to: toTypes}
    }
  },
  text: {
    primitive: 'string',
    options: {
      title: PropTypes.string,
      format: PropTypes.oneOf(['markdown', 'html', 'plain']),
      maxLength: PropTypes.number
    },
    defaultOptions: {
      format: 'plain'
    }
  },
  url: {
    primitive: 'string',
    options: {
      title: PropTypes.string
    }
  },
  email: {
    primitive: 'string',
    options: {
      title: PropTypes.string
    }
  },
  telephone: {
    primitive: 'string',
    options: {
      title: PropTypes.string
    }
  }
}
<|endoftext|>


<commit_before>import _ from 'lodash';

const parseValue = (column, value) => {
  if (typeof value !== 'object') return value;

  const properties = Object.keys(value);

  let parsed = '';
  for (let i = 0; i < properties.length; i += 1) {
    const property = properties[i];
    let compare = '=';

    if (property === '$ne') compare = '<>';
    if (property === '$gt') compare = '>';
    if (property === '$gte') compare = '>=';
    if (property === '$lt') compare = '<';
    if (property === '$lte') compare = '<=';

    const element = (typeof value[property] === 'string') ? `'${value[property]}'` : value[property];
    parsed += `${column} ${compare} ${element}`;

    if (i !== properties.length - 1) {
      parsed += ' AND ';
    }
  }
  return parsed;
};

const parseWhere = (where) => {
  if (typeof where === 'string') return `WHERE ${where}`;

  const properties = Object.keys(where);

  if (properties.length === 0) return 'WHERE TRUE';

  const conditions = [];
  for (let i = 0; i < properties.length; i += 1) {
    const property = properties[i];

    // TODO check if type validation is neeeded;
    const element = (typeof where[property] === 'string') ? `'${where[property]}'` : parseValue(property, where[property]);
    conditions.push(`\`${property}\` = ${element}`);

    if (i !== properties.length - 1) {
      conditions.push('AND');
    }
  }

  return `WHERE ${conditions.join(' ')}`;
};

const parseLimit = limit => `LIMIT ${limit}`;

const parseOffset = offset => `OFFSET ${offset}`;

const parseOrderBy = (orderBy) => {
  const properties = Object.keys(orderBy);

  const conditions = [];
  for (let i = 0; i < properties.length; i += 1) {
    const property = properties[i];
    const order = orderBy[property] ? 'ASC' : 'DESC';
    conditions.push(`\`${property}\` ${order}`);
  }

  return `ORDER BY ${conditions.join(', ')} `;
};

const parseColumns = (columns) => {
  const properties = Object.keys(columns);

  if (properties.length === 0) return '*';

  const columnsArray = [];
  for (let i = 0; i < properties.length; i += 1) {
    const property = properties[i];

    if (columns[property]) {
      columnsArray.push(`\`${property}\``);
    }
  }

  return `${columnsArray.join(',')}`;
};

const parseProperties = (properties) => {
  const keys = [];
  const values = [];

  const props = Object.keys(properties);

  for (let i = 0; i < props.length; i += 1) {
    const property = props[i];

    keys.push(`\`${property}\``);
    values.push((typeof properties[property] === 'string')
      ? `'${properties[property]}'`
      : properties[property]);
  }

  keys.push('createdAt');
  values.push('current_timestamp()');

  keys.push('updatedAt');
  values.push('current_timestamp()');

  return {
    keys: `(${keys.join(', ')})`,
    values: `(${values.join(', ')})`,
  };
};

const parseSet = (set) => {
  const setArray = [];
  const properties = Object.keys(set);

  properties.forEach((prop) => {
    const data = (typeof set[prop] === 'string')
    ? `'${set[prop]}'`
    : set[prop];

    setArray.push(`\`${prop}\` = ${data}`);
  });

  setArray.push('updatedAt = current_timestamp()');

  return `SET ${setArray.join(', ')}`;
};

const parseJoin = (source, target, inner = []) => {
  const onClause = _.map(inner, (plainElement) => {
    const splits = plainElement.split(':');
    return `${source}.${splits[0]} = ${target}.${splits[1]}`;
  }).join(' AND ');

  return `JOIN ${target} ON ${onClause}`;
};

export {
  parseJoin,
};

export default (query) => {
  const sql = {};

  if (query.columns) sql.columns = parseColumns(query.columns);
  if (query.where) sql.where = parseWhere(query.where);
  if (query.order) sql.order = parseOrderBy(query.order);
  if (query.limit) sql.limit = parseLimit(query.limit);
  if (query.offset) sql.offset = parseOffset(query.offset);
  if (query.properties) sql.properties = parseProperties(query.properties);
  if (query.set) sql.set = parseSet(query.set);

  return sql;
};
<commit_msg>Fix value parser<commit_after>import _ from 'lodash';

const parseValue = (column, value) => {
  if (typeof value !== 'object') return value;

  const properties = Object.keys(value);

  let parsed = '';
  for (let i = 0; i < properties.length; i += 1) {
    const property = properties[i];
    let compare = '=';

    if (property === '$ne') compare = '<>';
    if (property === '$gt') compare = '>';
    if (property === '$gte') compare = '>=';
    if (property === '$lt') compare = '<';
    if (property === '$lte') compare = '<=';

    const element = (typeof value[property] === 'string') ? `'${value[property]}'` : value[property];
    if (i === 0) {
      parsed += ` ${compare} ${element}`;
    } else {
      parsed += `\`${column}\` ${compare} ${element}`;
    }

    if (i !== properties.length - 1) {
      parsed += ' AND ';
    }
  }
  return parsed;
};

const parseWhere = (where) => {
  if (typeof where === 'string') return `WHERE ${where}`;

  const properties = Object.keys(where);

  if (properties.length === 0) return 'WHERE TRUE';

  const conditions = [];
  for (let i = 0; i < properties.length; i += 1) {
    const property = properties[i];

    // TODO check if type validation is neeeded;
    const element = (typeof where[property] === 'string') ? `'${where[property]}'` : parseValue(property, where[property]);
    conditions.push(`\`${property}\` = ${element}`);

    if (i !== properties.length - 1) {
      conditions.push('AND');
    }
  }

  return `WHERE ${conditions.join(' ')}`;
};

const parseLimit = limit => `LIMIT ${limit}`;

const parseOffset = offset => `OFFSET ${offset}`;

const parseOrderBy = (orderBy) => {
  const properties = Object.keys(orderBy);

  const conditions = [];
  for (let i = 0; i < properties.length; i += 1) {
    const property = properties[i];
    const order = orderBy[property] ? 'ASC' : 'DESC';
    conditions.push(`\`${property}\` ${order}`);
  }

  return `ORDER BY ${conditions.join(', ')} `;
};

const parseColumns = (columns) => {
  const properties = Object.keys(columns);

  if (properties.length === 0) return '*';

  const columnsArray = [];
  for (let i = 0; i < properties.length; i += 1) {
    const property = properties[i];

    if (columns[property]) {
      columnsArray.push(`\`${property}\``);
    }
  }

  return `${columnsArray.join(',')}`;
};

const parseProperties = (properties) => {
  const keys = [];
  const values = [];

  const props = Object.keys(properties);

  for (let i = 0; i < props.length; i += 1) {
    const property = props[i];

    keys.push(`\`${property}\``);
    values.push((typeof properties[property] === 'string')
      ? `'${properties[property]}'`
      : properties[property]);
  }

  keys.push('createdAt');
  values.push('current_timestamp()');

  keys.push('updatedAt');
  values.push('current_timestamp()');

  return {
    keys: `(${keys.join(', ')})`,
    values: `(${values.join(', ')})`,
  };
};

const parseSet = (set) => {
  const setArray = [];
  const properties = Object.keys(set);

  properties.forEach((prop) => {
    const data = (typeof set[prop] === 'string')
    ? `'${set[prop]}'`
    : set[prop];

    setArray.push(`\`${prop}\` = ${data}`);
  });

  setArray.push('updatedAt = current_timestamp()');

  return `SET ${setArray.join(', ')}`;
};

const parseJoin = (source, target, inner = []) => {
  const onClause = _.map(inner, (plainElement) => {
    const splits = plainElement.split(':');
    return `${source}.${splits[0]} = ${target}.${splits[1]}`;
  }).join(' AND ');

  return `JOIN ${target} ON ${onClause}`;
};

export {
  parseJoin,
};

export default (query) => {
  const sql = {};

  if (query.columns) sql.columns = parseColumns(query.columns);
  if (query.where) sql.where = parseWhere(query.where);
  if (query.order) sql.order = parseOrderBy(query.order);
  if (query.limit) sql.limit = parseLimit(query.limit);
  if (query.offset) sql.offset = parseOffset(query.offset);
  if (query.properties) sql.properties = parseProperties(query.properties);
  if (query.set) sql.set = parseSet(query.set);

  return sql;
};
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import moment from 'moment'
import Chart from 'chart.js'
import { Bar } from 'react-chartjs'

Chart.defaults.global.responsive = true

class MonitoringChart extends Component {

  componentWillMount() {
    this.props.onGetNet()
  }

  renderMonitoringChart() {
    let MonitoringChartRender, tmpChartStore = {}, chartData = {}
    let { dashGet } = this.props

    chartData.labels = []
    chartData.datasets = []

    if(dashGet.payload) {
      dashGet.payload.map((item) => {
        chartData.labels.push(moment(item.created_at).format('D MMM YYYY HH:mm:ss'))

        for(let key in item) {
          if(_.isUndefined(tmpChartStore[key])) tmpChartStore[key] = []
          if (_.isObject(tmpChartStore[key])) tmpChartStore[key].push(item[key])
        }
      })

      for (let key in tmpChartStore) {
        if (tmpChartStore.hasOwnProperty(key)) {
          let element = tmpChartStore[key]
          let randomRGBA = () => {
            let randomColorRGBA = `rgba(${(Math.floor(Math.random() * 256))}, ${(Math.floor(Math.random() * 256))}, ${(Math.floor(Math.random() * 256))}, alpha)`

            return (alpha) => randomColorRGBA.replace('alpha', alpha)
          }

          if((key !== 'created_at') && (key !== 'id')) {
            let randomColorString = randomRGBA()
            chartData.datasets.push({
              label: _.startCase(key),
              fillColor: randomColorString(0.5),
              strokeColor: 'rgba(220, 220, 220, 0.8)',
              highlightFill: randomColorString(0.75),
              highlightStroke: 'rgba(220, 220, 220, 1)',
              data: element
            })
          }
        }
      }

      MonitoringChartRender = <Bar data={chartData} ref='chart'/>
      _.defer(() => {
        this.props.onChartLegend(this.refs.chart.getChart().generateLegend())
      })
    }

    return MonitoringChartRender
  }

  render() {
    return (

        {this.renderMonitoringChart()}

    )
  }
}

export default MonitoringChart<commit_msg>fix bug with undefined<commit_after>import React, { Component } from 'react'
import moment from 'moment'
import Chart from 'chart.js'
import { Bar } from 'react-chartjs'

Chart.defaults.global.responsive = true

class MonitoringChart extends Component {

  componentWillMount() {
    this.props.onGetNet()
  }

  renderMonitoringChart() {
    let MonitoringChartRender, tmpChartStore = {}, chartData = {}
    let { dashGet } = this.props

    chartData.labels = []
    chartData.datasets = []

    if(dashGet.payload) {
      dashGet.payload.map((item) => {
        chartData.labels.push(moment(item.created_at).format('D MMM YYYY HH:mm:ss'))

        for(let key in item) {
          if(_.isUndefined(tmpChartStore[key])) tmpChartStore[key] = []
          if (_.isObject(tmpChartStore[key])) tmpChartStore[key].push(item[key])
        }
      })

      for (let key in tmpChartStore) {
        if (tmpChartStore.hasOwnProperty(key)) {
          let element = tmpChartStore[key]
          let randomRGBA = () => {
            let randomColorRGBA = `rgba(${(Math.floor(Math.random() * 256))}, ${(Math.floor(Math.random() * 256))}, ${(Math.floor(Math.random() * 256))}, alpha)`

            return (alpha) => randomColorRGBA.replace('alpha', alpha)
          }

          if((key !== 'created_at') && (key !== 'id')) {
            let randomColorString = randomRGBA()
            chartData.datasets.push({
              label: _.startCase(key),
              fillColor: randomColorString(0.5),
              strokeColor: 'rgba(220, 220, 220, 0.8)',
              highlightFill: randomColorString(0.75),
              highlightStroke: 'rgba(220, 220, 220, 1)',
              data: element
            })
          }
        }
      }

      MonitoringChartRender = <Bar data={chartData} ref='chart'/>
      _.defer(() => {
        let generatedLegendHtml = !_.isUndefined(this.refs.chart) ? this.refs.chart.getChart().generateLegend() : ''
        this.props.onChartLegend(generatedLegendHtml)
      })
    }

    return MonitoringChartRender
  }

  render() {
    return (

        {this.renderMonitoringChart()}

    )
  }
}

export default MonitoringChart<|endoftext|>


<commit_before>import Bacon from 'baconjs'
import {isServer} from '../utils'
import {concat, filter, isEmpty, whereEq, uniqBy, pipe, forEach} from 'ramda'
import {addUrlParameter, removeUrlParameter, sendEmail} from '../pages/browserUtils'

const createAppState = (reducer, initialState) => {
  const bus = Bacon.Bus()
  const store = bus.scan(initialState, (state, action) => reducer(state, action))
  store.dispatch = (action) => {
    bus.push(action)
  }
  store.currentState = initialState
  store.onValue((state) => {
    store.currentState = state
  })
  return store
}

const initial = isServer ? {} : window.STATE

const promiseMiddleware = (event) => {
  if (event && event.type && event.promise) {
    const {type, promise} = event
    const SUCCESS = `${type}_SUCCESS`
    promise
      .then((data) => appState.dispatch({type: SUCCESS, data}))
  }
}

const updateUrlParams = (selectedCourses) => {
  pipe(
    uniqBy((c) => c.course_code),
    forEach((c) => addUrlParameter(c.course_code, c.group_name))
  )(selectedCourses)
}

function rootReducer(previousState, action) {
  let state = previousState   // eslint-disable-line
  promiseMiddleware(action)
  switch (action.type) {
    case 'LOAD_COURSES_BY_DEPARTMENT_SUCCESS':
      const {data, department} = action.data
      state.departmentCourses = data ? data : []
      state.department = department ? department : 'TITE'
      break
    case 'LOAD_COURSES_SUCCESS':
      if (action.data.length > 0) {
        state.selectedCourses = action.data
      } else if (state.selectedCourses.length > 0) {
        updateUrlParams(state.selectedCourses)
      }
      break
    case 'LOAD_COURSE_BY_CODE':
      state.selectedCourses = concat(state.selectedCourses, action.course)
      updateUrlParams(action.course)
      break
    case 'REMOVE_COURSE_BY_ID':
      const coursesLeft = filter((c) => c.course_id !== action.courses[0].course_id, state.selectedCourses)
      if (isEmpty(filter(whereEq({course_code: action.courses[0].course_code}), coursesLeft))) {
        removeUrlParameter(action.courses[0].course_code)
      }
      state.selectedCourses = coursesLeft
      break
    case 'REMOVE_COURSE':
      removeUrlParameter(action.course_code)
      state.selectedCourses = state.selectedCourses.filter((e) => e.course_code !== action.course_code)
      break
    case 'ADD_COURSE':
      state.selectedCourses = concat(state.selectedCourses, action.selectedCourses)
      addUrlParameter(action.selectedCourses[0].course_code, action.selectedCourses[0].group_name)
      break
    case 'SAVE_MODAL':
      state.isModalOpen = action.isModalOpen
      break
    case 'SEND_EMAIL':
      state.waitingAjax = action.waitingAjax
      sendEmail(action.email)
    case 'EMAIL_SEND_DONE':
      state.waitingAjax = action.waitingAjax
      state.isModalOpen = false
      break
    case 'EMAIL_SEND_FAILED':
      state.waitingAjax = action.waitingAjax
      state.isModalOpen = false
      break
  }
  if (!isServer) {
    console.log(action.type, state)     // eslint-disable-line
  }
  return state
}

export const appState = createAppState(rootReducer, initial)
<commit_msg>Remove debug logging<commit_after>import Bacon from 'baconjs'
import {isServer} from '../utils'
import {concat, filter, isEmpty, whereEq, uniqBy, pipe, forEach} from 'ramda'
import {addUrlParameter, removeUrlParameter, sendEmail} from '../pages/browserUtils'

const createAppState = (reducer, initialState) => {
  const bus = Bacon.Bus()
  const store = bus.scan(initialState, (state, action) => reducer(state, action))
  store.dispatch = (action) => {
    bus.push(action)
  }
  store.currentState = initialState
  store.onValue((state) => {
    store.currentState = state
  })
  return store
}

const initial = isServer ? {} : window.STATE

const promiseMiddleware = (event) => {
  if (event && event.type && event.promise) {
    const {type, promise} = event
    const SUCCESS = `${type}_SUCCESS`
    promise
      .then((data) => appState.dispatch({type: SUCCESS, data}))
  }
}

const updateUrlParams = (selectedCourses) => {
  pipe(
    uniqBy((c) => c.course_code),
    forEach((c) => addUrlParameter(c.course_code, c.group_name))
  )(selectedCourses)
}

function rootReducer(previousState, action) {
  let state = previousState   // eslint-disable-line
  promiseMiddleware(action)
  switch (action.type) {
    case 'LOAD_COURSES_BY_DEPARTMENT_SUCCESS':
      const {data, department} = action.data
      state.departmentCourses = data ? data : []
      state.department = department ? department : 'TITE'
      break
    case 'LOAD_COURSES_SUCCESS':
      if (action.data.length > 0) {
        state.selectedCourses = action.data
      } else if (state.selectedCourses.length > 0) {
        updateUrlParams(state.selectedCourses)
      }
      break
    case 'LOAD_COURSE_BY_CODE':
      state.selectedCourses = concat(state.selectedCourses, action.course)
      updateUrlParams(action.course)
      break
    case 'REMOVE_COURSE_BY_ID':
      const coursesLeft = filter((c) => c.course_id !== action.courses[0].course_id, state.selectedCourses)
      if (isEmpty(filter(whereEq({course_code: action.courses[0].course_code}), coursesLeft))) {
        removeUrlParameter(action.courses[0].course_code)
      }
      state.selectedCourses = coursesLeft
      break
    case 'REMOVE_COURSE':
      removeUrlParameter(action.course_code)
      state.selectedCourses = state.selectedCourses.filter((e) => e.course_code !== action.course_code)
      break
    case 'ADD_COURSE':
      state.selectedCourses = concat(state.selectedCourses, action.selectedCourses)
      addUrlParameter(action.selectedCourses[0].course_code, action.selectedCourses[0].group_name)
      break
    case 'SAVE_MODAL':
      state.isModalOpen = action.isModalOpen
      break
    case 'SEND_EMAIL':
      state.waitingAjax = action.waitingAjax
      sendEmail(action.email)
    case 'EMAIL_SEND_DONE':
      state.waitingAjax = action.waitingAjax
      state.isModalOpen = false
      break
    case 'EMAIL_SEND_FAILED':
      state.waitingAjax = action.waitingAjax
      state.isModalOpen = false
      break
  }
  return state
}

export const appState = createAppState(rootReducer, initial)
<|endoftext|>


<commit_before>var util = require('util'),
    events = require('events'),
    child_process = require('child_process');

var Encoder = exports.Encoder = function(){
    events.EventEmitter.call(this);

}
util.inherits(Encoder, events.EventEmitter);

Encoder.prototype.default_options = {
    foreground_color: '#000000',
    background_color: '#FFFFFF',
    dot_size: 3, // default 3x3px per dot
    margin: 4, // default 4 dots for the margin
    level: 'L', // valid args (lowest to highest): L, M, Q, H
    case_sensitive: true, // case sensitive,
    version: 1 // default version 1
};

/**
 * Converts a string value to QR Code PNG data, and optionally saves to a file
 *
 * @param String value      The value to be encoded
 * @param String path       Where to save the PNG file (optional)
 * @param Object options    A hash of options (optional)
 * @return void
 */
Encoder.prototype.encode = function(value, path, options)
{
    // preserve scope in callbacks with self
    var self = this,
        cmd_options, qrencode_args, stdout, stderr, qrencode, exitcode;

    try {
        // check for undefined value
        if(value == undefined) {
            throw new Error('No value specified for encode method');
        }

        // create new buffer for value
        value = new Buffer(value);

        // if options are given, override defaults
        cmd_options = {};
        if(options == null) options = {};
        for(var key in this.default_options) {
            cmd_options[key] = (options[key] == undefined) ?
                this.default_options[key]
                : options[key];
        }

        // remove # symbol from color codes because qrencoder does not like it
        cmd_options.foreground_color.replace('#', '');
        cmd_options.background_color.replace('#', '');

        // start with base set of args that we'll always pass
        qrencode_args = [
            '-s', cmd_options.dot_size,
            '-m', cmd_options.margin,
            '-l', cmd_options.level,
            '-v', cmd_options.version,
            '--foreground=' + cmd_options.foreground_color,
            '--background=' + cmd_options.background_color
        ];

        // if case-sensitivity is disabled, add flag
        if(!cmd_options.case_sensitive) qrencode_args.push('-i');

        // if we have a path, write to the path
        // otherwise, it will write to stdout
        qrencode_args.push('-o');
        if(path != null) {
            qrencode_args.push(path);
        } else {
            qrencode_args.push('-');
        }

        // add the value to be encoded
        qrencode_args.push(value);

        // spawn the child process
        qrencode = child_process.spawn(
            'qrencode',
            qrencode_args
        );

        // add event listener for stdout data and populate stdout var
        // in the event no path was given
        qrencode.stdout.on('data', function(data) {
            stdout = data;
        });

        // add event listener for stderr
        qrencode.stderr.on('data', function(data) {
            stderr = data;
        });

        // add listener for process exit and save exit code
        qrencode.on('exit', function(code) {
            exitcode = code;
        });

        // add listener for filehandle close and emit end or error event
        // depending on exit code
        qrencode.on('close', function() {
            if(exitcode !== 0) {
                self.emit('error', new Error(stderr));
            } else {
                self.emit('end', stdout);
            }
        });

    } catch(err) {
        this.emit('error', err);
    }
}
<commit_msg>fix bug<commit_after>var util = require('util'),
    events = require('events'),
    child_process = require('child_process');

var Encoder = exports.Encoder = function(){
    events.EventEmitter.call(this);

}
util.inherits(Encoder, events.EventEmitter);

Encoder.prototype.default_options = {
    foreground_color: '#000000',
    background_color: '#FFFFFF',
    dot_size: 3, // default 3x3px per dot
    margin: 4, // default 4 dots for the margin
    level: 'L', // valid args (lowest to highest): L, M, Q, H
    case_sensitive: true, // case sensitive,
    version: 1 // default version 1
};

/**
 * Converts a string value to QR Code PNG data, and optionally saves to a file
 *
 * @param String value      The value to be encoded
 * @param String path       Where to save the PNG file (optional)
 * @param Object options    A hash of options (optional)
 * @return void
 */
Encoder.prototype.encode = function(value, path, options)
{
    // preserve scope in callbacks with self
    var self = this,
        cmd_options, qrencode_args, stdout, stderr, qrencode, exitcode;

    try {
        // check for undefined value
        if(value == undefined) {
            throw new Error('No value specified for encode method');
        }

        // create new buffer for value
        value = new Buffer(value);

        // if options are given, override defaults
        cmd_options = {};
        if(options == null) options = {};
        for(var key in this.default_options) {
            cmd_options[key] = (options[key] == undefined) ?
                this.default_options[key]
                : options[key];
        }

        // remove # symbol from color codes because qrencoder does not like it
        cmd_options.foreground_color = cmd_options.foreground_color.replace('#', '');
        cmd_options.background_color = cmd_options.background_color.replace('#', '');

        // start with base set of args that we'll always pass
        qrencode_args = [
            '-s', cmd_options.dot_size,
            '-m', cmd_options.margin,
            '-l', cmd_options.level,
            '-v', cmd_options.version,
            '--foreground=' + cmd_options.foreground_color,
            '--background=' + cmd_options.background_color
        ];

        // if case-sensitivity is disabled, add flag
        if(!cmd_options.case_sensitive) qrencode_args.push('-i');

        // if we have a path, write to the path
        // otherwise, it will write to stdout
        qrencode_args.push('-o');
        if(path != null) {
            qrencode_args.push(path);
        } else {
            qrencode_args.push('-');
        }

        // add the value to be encoded
        qrencode_args.push(value);

        // spawn the child process
        qrencode = child_process.spawn(
            'qrencode',
            qrencode_args
        );

        // add event listener for stdout data and populate stdout var
        // in the event no path was given
        qrencode.stdout.on('data', function(data) {
            stdout = data;
        });

        // add event listener for stderr
        qrencode.stderr.on('data', function(data) {
            stderr = data;
        });

        // add listener for process exit and save exit code
        qrencode.on('exit', function(code) {
            exitcode = code;
        });

        // add listener for filehandle close and emit end or error event
        // depending on exit code
        qrencode.on('close', function() {
            if(exitcode !== 0) {
                self.emit('error', new Error(stderr));
            } else {
                self.emit('end', stdout);
            }
        });

    } catch(err) {
        this.emit('error', err);
    }
}
<|endoftext|>


<commit_before>var config = require('config');
var FeedbackModal = require('feedback-modal');
var FilterView = require('filter-view');
var HelpMeChoose = require('help-me-choose-view');
var LeafletTransitiveLayer = require('Leaflet.TransitiveLayer');
var LocationsView = require('locations-view');
var log = require('./client/log')('planner-page');
var showMapView = require('map-view');
var OptionsView = require('options-view');
var PlannerNav = require('planner-nav');
var querystring = require('querystring');
var scrollbarSize = require('scrollbar-size');
var scrolling = require('scrolling');
var session = require('session');
var textModal = require('text-modal');
//var transitive = require('transitive');
var ua = require('user-agent');
var view = require('view');
var showWelcomeWizard = require('welcome-flow');
var showPlannerWalkthrough = require('planner-walkthrough');
var geocode = require('geocode');

var FROM = config.geocode().start_address;
var TO = config.geocode().end_address;
var isMobile = window.innerWidth <= 480;
var center = config.geocode().center.split(',').map(parseFloat);

var View = view(require('./template.html'), function(view, model) {
  view.scrollable = view.find('.scrollable');
  view.panelFooter = view.find('.footer');

  if (scrollbarSize > 0) {
    if (ua.os.name === 'Windows' || ua.browser.name !== 'Chrome')
      view.scrollable.style.marginRight = -scrollbarSize + 'px';

    // Scrollbars are fun and implemented the same on every OS/Browser...right
    if (ua.os.name === 'Windows' && ua.browser.name === 'Chrome')
      view.scrollable.style.paddingRight = scrollbarSize + 'px';
  }
});

/**
 * Expose `render`
 */

module.exports = function(ctx, next) {
  log('render');

  var plan = ctx.plan;
  var query = querystring.parse(window.location.search);

  // Set up the views
  var views = {
    'filter-view': new FilterView(plan),
    'locations-view': new LocationsView(plan),
    'options-view': new OptionsView(plan),
    'planner-nav': new PlannerNav(session)
  };

  ctx.view = new View(views);
  ctx.view.on('rendered', function() {
    // Set plan to loading
    plan.loading(true);

    for (var key in views) {
      views[key].emit('rendered', views[key]);
    }

    // Show the map
    var map = showMapView(ctx.view.find('.MapView'));

    console.log("map ->", map);

    // Create the transitive layer
    //var transitiveLayer = new LeafletTransitiveLayer(transitive);

    // Set the transitive layer
    //map.addLayer(transitiveLayer);

    // Update map on plan change
    updateMapOnPlanChange(plan, map);

    map.on('click', function (e) {
          var from = plan.from_ll();
          var to = plan.to_ll();
          if (!plan.coordinateIsValid(from)) {
            plan.journey({
          places: [
            {
              place_id: 'from',
             place_lat: e.latlng.lat,
              place_lon: e.latlng.lng,
              place_name: 'From'
           },
            {
              place_id: 'to',
             place_lat: (plan.to_ll() ? plan.to_ll().lat : 0),
              place_lon: (plan.to_ll() ? plan.to_ll().lng : 0),
              place_name: 'To'
            }
          ]
        });
        plan.setAddress('from', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
            plan.updateRoutes();
        });
          } else if (!plan.coordinateIsValid(to)) {
        plan.journey({
          places: [
            {
              place_id: 'from',
              place_lat: plan.from_ll().lat,
             place_lon: plan.from_ll().lng,
              place_name: 'From'
            },
           {
              place_id: 'to',
              place_lat: e.latlng.lat,
              place_lon: e.latlng.lng,
              place_name: 'To'
            }
          ]
        });
        plan.setAddress('to', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
            plan.updateRoutes();
        });
          }
    });

    // Clear plan & cookies for now, plan will re-save automatically on save
      var from = plan.from_ll();
      var to = plan.to_ll();
      //plan.clearStore();

    // If it's a shared URL or welcome is complete skip the welcome screen
    console.log("query ->", query);
    if ((query.from && query.to)) {
      showQuery(query);
    } else {
      console.log("plan.coordinateIsValid(from)", plan.coordinateIsValid(from));
      console.log("plan.coordinateIsValid(to)", plan.coordinateIsValid(to));

      if (plan.coordinateIsValid(from) && plan.coordinateIsValid(to)) {
          plan.setAddresses(
            from.lng + ',' + from.lat, // from
            to.lng + ',' + to.lat, // to
            function (err, res) {
              plan.updateRoutes();
              console.log("aqui la data del plan 4 ->", plan.dataplan);
            }
          );
          plan.updateRoutes();
          console.log("aqui la data del plan 3 ->", plan.dataplan);
      } else {
          console.log(from);
          console.log(to);
          plan.loading(false);
      }
    }
  });

  plan.on('updating options', function() {
    ctx.view.panelFooter.classList.add('hidden');
  });

  plan.on('updating options complete', function(res) {
    if (res && !res.err) ctx.view.panelFooter.classList.remove('hidden');
  });

  next();
};

/**
 * Reverse Commute
 */

View.prototype.reverseCommute = function(e) {
  e.preventDefault();
  var plan = session.plan();
  plan.set({
    from: plan.to(),
    from_id: plan.to_id(),
    from_ll: plan.to_ll(),
    to: plan.from(),
    to_id: plan.from_id(),
    to_ll: plan.from_ll()
  });

  plan.updateRoutes();

  console.log("aqui la data del plan 5 ->", plan.dataplan);
};

/**
 * Scroll
 */

View.prototype.scroll = function(e) {
  e.preventDefault();
  this.scrollable.scrollTop += (this.scrollable.scrollHeight / 5);
};

/**
 * On submit
 */

View.prototype.onsubmit = function(e) {
  e.preventDefault();
};

/**
 * Help Me Choose
 */

View.prototype.helpMeChoose = function(e) {
  HelpMeChoose(session.plan().options()).show();
};

/**
 * Show feedback modal
 */
View.prototype.feedback = function(e) {
  e.preventDefault();
  FeedbackModal().show();
};

/**
 * Hide Side Panel
 */

View.prototype.hideSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(' + width + 'px, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding': '0'
  });

  setTimeout(function () {
    map.invalidateSize();
  }, 2100)
};

/**
 * Show Side Panel
 */

View.prototype.showSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(0, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding-right': '320px'
  });

  setTimeout(function () {
    var plan = session.plan();
    map.invalidateSize();

    plan = session.plan();
    plan.updateRoutes();
    //transitive.updateData(plan.journey());

    plan.journey();

  }, 2100)
};

/**
 * Show Journey
 */

function showQuery(query) {
  var plan = session.plan();
  // If no querystring, see if we have them in the plan already
  var from = query.from || plan.from() || FROM;
  var to = query.to || plan.to() || TO;
  var sameAddresses = from === plan.from() && to === plan.to();

  // Set plan from querystring
  if (query.modes) plan.setModes(query.modes);
  if (query.start_time !== undefined) plan.start_time(parseInt(query.start_time, 10));
  if (query.end_time !== undefined) plan.end_time(parseInt(query.end_time, 10));
  if (query.days !== undefined) plan.days(query.days);

  // If has valid coordinates, load
  if (plan.validCoordinates() && sameAddresses) {
    plan.journey({
      places: plan.generatePlaces()
    });
    plan.updateRoutes();

    console.log("aqui la data del plan 1 ->", plan.dataplan);
  } else {
      if (!plan.validCoordinates()) {
	  plan.loading(false);
	  return;
      } else {
    // Set addresses and update the routes
    plan.setAddresses(from, to, function(err) {
      if (err) {
        log.error('%e', err);
      } else {
        plan.journey({
          places: plan.generatePlaces()
        });
        plan.updateRoutes();

        console.log("aqui la data del plan 2 ->", plan.dataplan);
      }
    });
}
  }
}

/**
 * Update Map on plan change
 */

function updateMapOnPlanChange(plan, map) {
  // Register plan update events
    /*
    for (i in map._layers) {
        if (map._layers[i].options.format == undefined) {
            try {
                map.removeLayer(map._layers[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }
        }
    }
    */

    //map.removeLayer(polyline);
/*

  for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }

  }
  */

  plan.on('change journey', function(journey) {

  showMapView.cleanPolyline();
  showMapView.cleanMarker();

    if (journey && !isMobile) {
      try {

        log('updating data');

        var datajourney = journey;
        if (!(plan.dataplan.plan === undefined)) {
            var new_plan = plan.dataplan.plan;
            var itineraries = new_plan.itineraries;
            console.log("plan actual", plan);
            var patterns = plan.dataplan.patterns;
            var routes = plan.dataplan.routes;
            console.log("patterns", patterns);
            console.log("routes", routes);
            console.log("itineraries", itineraries);
            showMapView.marker_map([new_plan.from.lat,new_plan.from.lon],[new_plan.to.lat,new_plan.to.lon], map);
            for (i = 0; i < itineraries.length; i++) {
                for (ii=0; ii < itineraries[i].legs.length; ii++) {
                  //console.log("itineraries[i].legs[ii]", itineraries[i].legs[ii]);
                  var circle = [itineraries[i].legs[ii].to.lat, itineraries[i].legs[ii].to.lon, itineraries[i].legs[ii].to.name];
                  //console.log("circle", circle);

                  showMapView.marker_map_point(circle, map);
                  //
                  console.log("itineraries[i].legs[ii].steps.length", itineraries[i].legs[ii].steps.length);
                  console.log("---------------------");
                  //for (i = 0; i < itineraries[i].legs[ii].steps.length; i++) {
                  //     var circle2 = [itineraries[i].legs[ii].steps[i].lat, itineraries[i].legs[ii].steps[i].lon, ''];
                  //
                  //     //showMapView.marker_map_point(circle2, map);
                  //}
                  showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points, itineraries[i].legs[ii].mode);
                }
            }

            for (var k = 0; k < patterns.length; k++) {
              var route_id = patterns[k].routeId;
              var route_id_split = route_id.split(":");
              var agency = route_id_split[0].toLowerCase();
              var line = route_id_split[1].toLowerCase();
              var routeId = route_id_split[0] + ':' + route_id_split[1];
              console.log("agency ->", agency, "line ->", line, "routeId ->", routeId);

            }

            for (var n = 0; n < routes.length; n++) {
              var route_short_name = routes[n].shortName;
              var route_long_name = routes[n].longName.toUpperCase();
              console.log("route_short_name ->", route_short_name, "route_long_name ->", route_long_name);

            }
          console.log("entre if ")
        }else{
            console.log("ejecuta storage");
            var sesion_plan = JSON.parse(localStorage.getItem('dataplan'));
            if(!(sesion_plan === null)) {
                var itineraries = sesion_plan.itineraries;

                showMapView.marker_map([sesion_plan.from.lat,sesion_plan.from.lon],[sesion_plan.to.lat,sesion_plan.to.lon], map);

                for (i = 0; i < itineraries.length; i++) {
                    for (ii=0; ii < itineraries[i].legs.length; ii++) {
                      var circle = [itineraries[i].legs[ii].to.lat, itineraries[i].legs[ii].to.lon, itineraries[i].legs[ii].to.name];
                      //console.log("circle", circle);
                      showMapView.marker_map_point(circle, map);
                      showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points, itineraries[i].legs[ii].mode);
                    }
                }
            }

        }
      } catch (e) {
        console.log("entre cath")
	    map.setView([center[1], center[0]], config.geocode().zoom);
      }

    }
  });
}

/////////////function test circle maps  ////

function getRouteId(patternId, patterns) {
  for (var i = 0; i < patterns.length; i++) {
    var pattern = patterns[i];
    if (pattern.pattern_id === patternId) return pattern.route_id;
  }
}

function getRoute(routeId, routes) {
  for (var i = 0; i < routes.length; i++) {
    var route = routes[i];
    if (route.route_id === routeId) return route;
  }
}

function getRouteShield(agency, route) {
  if (agency === 'dc' && route.route_type === 1) return 'M';
  return route.route_short_name || route.route_long_name.toUpperCase();
}
<commit_msg>adding console<commit_after>var config = require('config');
var FeedbackModal = require('feedback-modal');
var FilterView = require('filter-view');
var HelpMeChoose = require('help-me-choose-view');
var LeafletTransitiveLayer = require('Leaflet.TransitiveLayer');
var LocationsView = require('locations-view');
var log = require('./client/log')('planner-page');
var showMapView = require('map-view');
var OptionsView = require('options-view');
var PlannerNav = require('planner-nav');
var querystring = require('querystring');
var scrollbarSize = require('scrollbar-size');
var scrolling = require('scrolling');
var session = require('session');
var textModal = require('text-modal');
//var transitive = require('transitive');
var ua = require('user-agent');
var view = require('view');
var showWelcomeWizard = require('welcome-flow');
var showPlannerWalkthrough = require('planner-walkthrough');
var geocode = require('geocode');

var FROM = config.geocode().start_address;
var TO = config.geocode().end_address;
var isMobile = window.innerWidth <= 480;
var center = config.geocode().center.split(',').map(parseFloat);

var View = view(require('./template.html'), function(view, model) {
  view.scrollable = view.find('.scrollable');
  view.panelFooter = view.find('.footer');

  if (scrollbarSize > 0) {
    if (ua.os.name === 'Windows' || ua.browser.name !== 'Chrome')
      view.scrollable.style.marginRight = -scrollbarSize + 'px';

    // Scrollbars are fun and implemented the same on every OS/Browser...right
    if (ua.os.name === 'Windows' && ua.browser.name === 'Chrome')
      view.scrollable.style.paddingRight = scrollbarSize + 'px';
  }
});

/**
 * Expose `render`
 */

module.exports = function(ctx, next) {
  log('render');

  var plan = ctx.plan;
  var query = querystring.parse(window.location.search);

  // Set up the views
  var views = {
    'filter-view': new FilterView(plan),
    'locations-view': new LocationsView(plan),
    'options-view': new OptionsView(plan),
    'planner-nav': new PlannerNav(session)
  };

  ctx.view = new View(views);
  ctx.view.on('rendered', function() {
    // Set plan to loading
    plan.loading(true);

    for (var key in views) {
      views[key].emit('rendered', views[key]);
    }

    // Show the map
    var map = showMapView(ctx.view.find('.MapView'));

    console.log("map ->", map);

    // Create the transitive layer
    //var transitiveLayer = new LeafletTransitiveLayer(transitive);

    // Set the transitive layer
    //map.addLayer(transitiveLayer);

    // Update map on plan change
    updateMapOnPlanChange(plan, map);

    map.on('click', function (e) {
          var from = plan.from_ll();
          var to = plan.to_ll();
          if (!plan.coordinateIsValid(from)) {
            plan.journey({
          places: [
            {
              place_id: 'from',
             place_lat: e.latlng.lat,
              place_lon: e.latlng.lng,
              place_name: 'From'
           },
            {
              place_id: 'to',
             place_lat: (plan.to_ll() ? plan.to_ll().lat : 0),
              place_lon: (plan.to_ll() ? plan.to_ll().lng : 0),
              place_name: 'To'
            }
          ]
        });
        plan.setAddress('from', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
            plan.updateRoutes();
        });
          } else if (!plan.coordinateIsValid(to)) {
        plan.journey({
          places: [
            {
              place_id: 'from',
              place_lat: plan.from_ll().lat,
             place_lon: plan.from_ll().lng,
              place_name: 'From'
            },
           {
              place_id: 'to',
              place_lat: e.latlng.lat,
              place_lon: e.latlng.lng,
              place_name: 'To'
            }
          ]
        });
        plan.setAddress('to', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
            plan.updateRoutes();
        });
          }
    });

    // Clear plan & cookies for now, plan will re-save automatically on save
      var from = plan.from_ll();
      var to = plan.to_ll();
      //plan.clearStore();

    // If it's a shared URL or welcome is complete skip the welcome screen
    console.log("query ->", query);
    if ((query.from && query.to)) {
      showQuery(query);
    } else {
      console.log("plan.coordinateIsValid(from)", plan.coordinateIsValid(from));
      console.log("plan.coordinateIsValid(to)", plan.coordinateIsValid(to));

      if (plan.coordinateIsValid(from) && plan.coordinateIsValid(to)) {
          plan.setAddresses(
            from.lng + ',' + from.lat, // from
            to.lng + ',' + to.lat, // to
            function (err, res) {
              plan.updateRoutes();
              console.log("aqui la data del plan 4 ->", plan.dataplan);
            }
          );
          plan.updateRoutes();
          console.log("aqui la data del plan 3 ->", plan.dataplan);
      } else {
          console.log(from);
          console.log(to);
          plan.loading(false);
      }
    }
  });

  plan.on('updating options', function() {
    ctx.view.panelFooter.classList.add('hidden');
  });

  plan.on('updating options complete', function(res) {
    if (res && !res.err) ctx.view.panelFooter.classList.remove('hidden');
  });

  next();
};

/**
 * Reverse Commute
 */

View.prototype.reverseCommute = function(e) {
  e.preventDefault();
  var plan = session.plan();
  plan.set({
    from: plan.to(),
    from_id: plan.to_id(),
    from_ll: plan.to_ll(),
    to: plan.from(),
    to_id: plan.from_id(),
    to_ll: plan.from_ll()
  });

  plan.updateRoutes();

  console.log("aqui la data del plan 5 ->", plan.dataplan);
};

/**
 * Scroll
 */

View.prototype.scroll = function(e) {
  e.preventDefault();
  this.scrollable.scrollTop += (this.scrollable.scrollHeight / 5);
};

/**
 * On submit
 */

View.prototype.onsubmit = function(e) {
  e.preventDefault();
};

/**
 * Help Me Choose
 */

View.prototype.helpMeChoose = function(e) {
  HelpMeChoose(session.plan().options()).show();
};

/**
 * Show feedback modal
 */
View.prototype.feedback = function(e) {
  e.preventDefault();
  FeedbackModal().show();
};

/**
 * Hide Side Panel
 */

View.prototype.hideSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(' + width + 'px, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding': '0'
  });

  setTimeout(function () {
    map.invalidateSize();
  }, 2100)
};

/**
 * Show Side Panel
 */

View.prototype.showSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(0, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding-right': '320px'
  });

  setTimeout(function () {
    var plan = session.plan();
    map.invalidateSize();

    plan = session.plan();
    plan.updateRoutes();
    //transitive.updateData(plan.journey());

    plan.journey();

  }, 2100)
};

/**
 * Show Journey
 */

function showQuery(query) {
  var plan = session.plan();
  // If no querystring, see if we have them in the plan already
  var from = query.from || plan.from() || FROM;
  var to = query.to || plan.to() || TO;
  var sameAddresses = from === plan.from() && to === plan.to();

  // Set plan from querystring
  if (query.modes) plan.setModes(query.modes);
  if (query.start_time !== undefined) plan.start_time(parseInt(query.start_time, 10));
  if (query.end_time !== undefined) plan.end_time(parseInt(query.end_time, 10));
  if (query.days !== undefined) plan.days(query.days);

  // If has valid coordinates, load
  if (plan.validCoordinates() && sameAddresses) {
    plan.journey({
      places: plan.generatePlaces()
    });
    plan.updateRoutes();

    console.log("aqui la data del plan 1 ->", plan.dataplan);
  } else {
      if (!plan.validCoordinates()) {
	  plan.loading(false);
	  return;
      } else {
    // Set addresses and update the routes
    plan.setAddresses(from, to, function(err) {
      if (err) {
        log.error('%e', err);
      } else {
        plan.journey({
          places: plan.generatePlaces()
        });
        plan.updateRoutes();

        console.log("aqui la data del plan 2 ->", plan.dataplan);
      }
    });
}
  }
}

/**
 * Update Map on plan change
 */

function updateMapOnPlanChange(plan, map) {
  // Register plan update events
    /*
    for (i in map._layers) {
        if (map._layers[i].options.format == undefined) {
            try {
                map.removeLayer(map._layers[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }
        }
    }
    */

    //map.removeLayer(polyline);
/*

  for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }

  }
  */

  plan.on('change journey', function(journey) {

  showMapView.cleanPolyline();
  showMapView.cleanMarker();

    if (journey && !isMobile) {
      try {

        log('updating data');

        var datajourney = journey;
        if (!(plan.dataplan.plan === undefined)) {
            var new_plan = plan.dataplan.plan;
            var itineraries = new_plan.itineraries;
            console.log("plan actual", plan);
            var patterns = plan.dataplan.patterns;
            var routes = plan.dataplan.routes;
            console.log("patterns", patterns);
            console.log("routes", routes);
            console.log("itineraries", itineraries);
            showMapView.marker_map([new_plan.from.lat,new_plan.from.lon],[new_plan.to.lat,new_plan.to.lon], map);
            for (i = 0; i < itineraries.length; i++) {
                for (ii=0; ii < itineraries[i].legs.length; ii++) {
                  //console.log("itineraries[i].legs[ii]", itineraries[i].legs[ii]);
                  var circle = [itineraries[i].legs[ii].to.lat, itineraries[i].legs[ii].to.lon, itineraries[i].legs[ii].to.name];
                  //console.log("circle", circle);

                  showMapView.marker_map_point(circle, map);
                  //
                  if (itineraries[i].legs[ii].steps.length > 0){
                     console.log("itineraries[i].legs[ii].steps.length", itineraries[i].legs[ii].steps.length);
                     var step_count = itineraries[i].legs[ii].steps.length;
                     var step_div = parseFloat(step_count / 2);
                     var current_step = Math.ceil(step_div)
                      console.log("step_count ->", step_count, "step_div ->", step_div, "current_step ->", current_step);
                      console.log("---------------------");
                  }

                  //for (i = 0; i < itineraries[i].legs[ii].steps.length; i++) {
                  //     var circle2 = [itineraries[i].legs[ii].steps[i].lat, itineraries[i].legs[ii].steps[i].lon, ''];
                  //
                  //     //showMapView.marker_map_point(circle2, map);
                  //}
                  showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points, itineraries[i].legs[ii].mode);
                }
            }

            for (var k = 0; k < patterns.length; k++) {
              var route_id = patterns[k].routeId;
              var route_id_split = route_id.split(":");
              var agency = route_id_split[0].toLowerCase();
              var line = route_id_split[1].toLowerCase();
              var routeId = route_id_split[0] + ':' + route_id_split[1];
              console.log("agency ->", agency, "line ->", line, "routeId ->", routeId);

            }

            for (var n = 0; n < routes.length; n++) {
              var route_short_name = routes[n].shortName;
              var route_long_name = routes[n].longName.toUpperCase();
              console.log("route_short_name ->", route_short_name, "route_long_name ->", route_long_name);

            }
          console.log("entre if ")
        }else{
            console.log("ejecuta storage");
            var sesion_plan = JSON.parse(localStorage.getItem('dataplan'));
            if(!(sesion_plan === null)) {
                var itineraries = sesion_plan.itineraries;

                showMapView.marker_map([sesion_plan.from.lat,sesion_plan.from.lon],[sesion_plan.to.lat,sesion_plan.to.lon], map);

                for (i = 0; i < itineraries.length; i++) {
                    for (ii=0; ii < itineraries[i].legs.length; ii++) {
                      var circle = [itineraries[i].legs[ii].to.lat, itineraries[i].legs[ii].to.lon, itineraries[i].legs[ii].to.name];
                      //console.log("circle", circle);
                      showMapView.marker_map_point(circle, map);
                      showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points, itineraries[i].legs[ii].mode);
                    }
                }
            }

        }
      } catch (e) {
        console.log("entre cath")
	    map.setView([center[1], center[0]], config.geocode().zoom);
      }

    }
  });
}

/////////////function test circle maps  ////

function getRouteId(patternId, patterns) {
  for (var i = 0; i < patterns.length; i++) {
    var pattern = patterns[i];
    if (pattern.pattern_id === patternId) return pattern.route_id;
  }
}

function getRoute(routeId, routes) {
  for (var i = 0; i < routes.length; i++) {
    var route = routes[i];
    if (route.route_id === routeId) return route;
  }
}

function getRouteShield(agency, route) {
  if (agency === 'dc' && route.route_type === 1) return 'M';
  return route.route_short_name || route.route_long_name.toUpperCase();
}
<|endoftext|>


<commit_before>var _ = require('lodash');

function Encoder2() {
    var COMPONENT_SEPARATOR, SUBCOMPONENT_SEPARATOR, REPEAT_SEPARATOR, DEFAULT_SEPARATORS, FIELD_SEPARATOR, NEW_LINE;

    FIELD_SEPARATOR = '|';
    COMPONENT_SEPARATOR = '^';
    SUBCOMPONENT_SEPARATOR = '&';
    REPEAT_SEPARATOR = '~';
    NEW_LINE = '\r';
    DEFAULT_SEPARATORS = "" + COMPONENT_SEPARATOR + REPEAT_SEPARATOR + "\\" + SUBCOMPONENT_SEPARATOR;

    function Encoder2(options) {
        if (options != null ? options.NEW_LINE : void 0) {
            NEW_LINE = options.NEW_LINE;
        }
    }

    var encode = function(message) {
        var encodedMessage, segments;
        segments = encodeAllObjectPropertiesAsSegments(message);
        encodedMessage = segments.join(NEW_LINE);
        return encodedMessage;
    };

    var encodeAllObjectPropertiesAsSegments = function(object) {
        var segmentName, value, _results;
        _results = [];
        for (segmentName in object) {
            if (segmentName === '$'){
                continue;
            }
            if (!_.isArray(object[segmentName])){
                object[segmentName] = [object[segmentName]];
            }
            _.each(object[segmentName], function(value){
                _results.push(encodeSegment(segmentName, value));
            });
        }
        return _results;
    };

    var encodeSegment = function(name, segment) {
        if (name === 'MSH') {
            if (!segment['MSH.2']) {
                segment['MSH.2'] = DEFAULT_SEPARATORS;
            }
            return name + joinAllFieldsInSparseArrayIntoASingleLine(segment, name);
        }else{
            return name + FIELD_SEPARATOR + joinAllFieldsInSparseArrayIntoASingleLine(segment, name);
        }
    };

    var joinAllFieldsInSparseArrayIntoASingleLine = function(fields, name) {
        if (_.isString(fields)){
            return fields;
        }

        var len = _(fields).keys().max(function (k){ return parseInt(k.split('.').pop(), 10);});
        len = parseInt((len+"").split('.').pop(),10);
        var result = '';
        if (!len || len < 2) {
            return result;
        }

        for (var i = 1; i <= len; i++){
            result += encodeField(fields[name + '.' + i], name + '.' + i);
            result += FIELD_SEPARATOR;
        }
        return result;
    };

    var encodeField = function(value, name) {
        var result = [];
        if (!value) {
            return '';
        }
        if (_.isString(value)) {
            return value;
        }else{
            _.each(value, function (val){
                console.log(val);
                var len = _(val).keys().max(function (k){ return parseInt(k.split('.').pop(), 10);});
                len = parseInt((len+"").split('.').pop(),10);
                var components = [];

                for (var i = 1; i <= len; i++) {
                    if (_.isString(val[name + '.' + i]) || !val[name + '.' + i]){
                        components.push(val[name + '.' + i] || "");
                    }else{
                        components.push(_.map(val[name + '.' + i], function (subvalue){
                            return subvalue;
                        }).join(SUBCOMPONENT_SEPARATOR));
                    }
                }
                result.push(components.join(COMPONENT_SEPARATOR));

            });
            return result.join(REPEAT_SEPARATOR);
        }
    };

    return {
        encode: encode,
        encodeSegment: encodeSegment,
        encodeField: encodeField
    };

};

module.exports = Encoder2;
<commit_msg>special characters<commit_after>var _ = require('lodash');

function Encoder2() {
    var COMPONENT_SEPARATOR, SUBCOMPONENT_SEPARATOR, REPEAT_SEPARATOR, DEFAULT_SEPARATORS, FIELD_SEPARATOR, NEW_LINE;

    FIELD_SEPARATOR = '|';
    COMPONENT_SEPARATOR = '^';
    SUBCOMPONENT_SEPARATOR = '&';
    REPEAT_SEPARATOR = '~';
    NEW_LINE = '\r';
    DEFAULT_SEPARATORS = "" + COMPONENT_SEPARATOR + REPEAT_SEPARATOR + "\\" + SUBCOMPONENT_SEPARATOR;

    function Encoder2(options) {
        if (options != null ? options.NEW_LINE : void 0) {
            NEW_LINE = options.NEW_LINE;
        }
    }

    var encode = function(message) {
        var encodedMessage, segments;
        segments = encodeAllObjectPropertiesAsSegments(message);
        encodedMessage = String.fromCharCode(11) + segments.join(NEW_LINE) + String.fromCharCode(28,13);
        return encodedMessage;
    };

    var encodeAllObjectPropertiesAsSegments = function(object) {
        var segmentName, value, _results;
        _results = [];
        for (segmentName in object) {
            if (segmentName === '$'){
                continue;
            }
            if (!_.isArray(object[segmentName])){
                object[segmentName] = [object[segmentName]];
            }
            _.each(object[segmentName], function(value){
                _results.push(encodeSegment(segmentName, value));
            });
        }
        return _results;
    };

    var encodeSegment = function(name, segment) {
        if (name === 'MSH') {
            if (!segment['MSH.2']) {
                segment['MSH.2'] = DEFAULT_SEPARATORS;
            }
            return name + joinAllFieldsInSparseArrayIntoASingleLine(segment, name);
        }else{
            return name + FIELD_SEPARATOR + joinAllFieldsInSparseArrayIntoASingleLine(segment, name);
        }
    };

    var joinAllFieldsInSparseArrayIntoASingleLine = function(fields, name) {
        if (_.isString(fields)){
            return fields;
        }

        var len = _(fields).keys().max(function (k){ return parseInt(k.split('.').pop(), 10);});
        len = parseInt((len+"").split('.').pop(),10);
        var result = '';
        if (!len || len < 2) {
            return result;
        }

        for (var i = 1; i <= len; i++){
            result += encodeField(fields[name + '.' + i], name + '.' + i);
            result += FIELD_SEPARATOR;
        }
        return result;
    };

    var encodeField = function(value, name) {
        var result = [];
        if (!value) {
            return '';
        }
        if (_.isString(value)) {
            return value;
        }else{
            _.each(value, function (val){
                var len = _(val).keys().max(function (k){ return parseInt(k.split('.').pop(), 10);});
                len = parseInt((len+"").split('.').pop(),10);
                var components = [];

                for (var i = 1; i <= len; i++) {
                    if (_.isString(val[name + '.' + i]) || !val[name + '.' + i]){
                        components.push(val[name + '.' + i] || "");
                    }else{
                        components.push(_.map(val[name + '.' + i], function (subvalue){
                            return subvalue;
                        }).join(SUBCOMPONENT_SEPARATOR));
                    }
                }
                result.push(components.join(COMPONENT_SEPARATOR));

            });
            return result.join(REPEAT_SEPARATOR);
        }
    };

    return {
        encode: encode,
        encodeSegment: encodeSegment,
        encodeField: encodeField
    };

};

module.exports = Encoder2;
<|endoftext|>


<commit_before>"use strict";

// if local development, communicate with DEFAULT_HOSTNAME, otherwise - with web-UI host
const DEFAULT_HOSTNAME = "demo.semiot.ru";
const hostname = location.hostname === "localhost" ? DEFAULT_HOSTNAME : location.hostname;

const TSDB_BASE_URL = `http://${hostname}:4242/api/query`;

export default {
    COOKIE_NAME: "ru.semiot",
    URLS: {
        messageBus: "ws://" + hostname + ":8080/ws",
        tripleStore: "http://" + hostname + ":3030/ds/query",
        tsdb: {
            archiveQuantity: `${TSDB_BASE_URL}?start={0}&end={1}&m=sum:{2}`,
            archiveEnum: `${TSDB_BASE_URL}?start={0}&end={1}&m=sum:{2}{enum_value=*}`,
            last: `${TSDB_BASE_URL}/last/{0}`
        }
    },
    TOPICS: {
        "device_registered": 'ru.semiot.devices.newandobserving',
        "device_turned_off": 'ru.semiot.devices.turnoff',
        "device_remove": 'ru.semiot.devices.remove'
    },
    SPARQL: {
        prefixes: {
            rdfs: 'http://www.w3.org/2000/01/rdf-schema#',
            ssn: 'http://purl.oclc.org/NET/ssnx/ssn#',
            rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
            ssncom: 'http://purl.org/NET/ssnext/communication#',
            saref: 'http://ontology.tno.nl/saref#',
            mcht: 'http://purl.org/NET/ssnext/machinetools#',
            qudt: 'http://www.qudt.org/qudt/owl/1.0.0/qudt/#',
            "qudt-quantity": 'http://qudt.org/vocab/quantity#',
            "qudt-unit": "http://qudt.org/vocab/unit#",
            om: 'http://purl.org/ifgi/om#'
        },
        types: {
            heatSystem: "http://purl.org/NET/ssnext/heatmeters#HeatMeter",
            electricSystem: "http://purl.org/NET/ssnext/electricmeters#ElectricMeter",
            temperature: "http://purl.org/NET/ssnext/heatmeters#Temperature",
            heat: "http://purl.org/NET/ssnext/heatmeters#Heat",
            observationResult: "http://purl.org/NET/ssnext/meters/core#hasQuantityValue"
        },
        queries: {
            getAllSystems: [
                "SELECT DISTINCT ?label ?uri ?state",
                "WHERE {",
                "   ?uri a ssn:System ;",
                "       saref:hasState ?state ;",
                "       rdfs:label ?label .",
                "}"
            ].join('\n'),
            getSystemEndpoint: `
                SELECT ?endpoint ?type ?observationType ?propLabel ?valueUnitLabel {
                  <{0}> ssn:hasSubSystem ?subsystem .
                  ?subsystem ssn:observes ?type .
                  ?subsystem ssn:hasMeasurementCapability ?mc .
                  ?mc ssn:forProperty ?prop .
                  ?prop rdfs:label ?propLabel .
                  ?mc ssn:hasMeasurementProperty ?mp .
                  ?mp ssn:hasValue ?v .
                  ?v a ?observationType .
                  ?v ssn:hasValue ?valueUnit .
                  ?valueUnit rdfs:label ?valueUnitLabel .
                  ?subsystem ssncom:hasCommunicationEndpoint ?endpoint .
                  ?endpoint ssncom:protocol 'WAMP' .
                }
            `,
            getSystemName: [
                "SELECT ?label {",
                "   <{0}> rdfs:label ?label .",
                "}"
            ].join('\n'),
            getMachineToolStates: `
                SELECT ?stateURI ?stateLabel ?stateDescription
                WHERE {
                    ?stateURI rdf:type mcht:MachineToolWorkingStateValue ;
                        rdfs:label ?stateLabel ;
                        rdfs:comment ?stateDescription .
                }
            `
        }
    },
    TIMEZONE_OFFSET: -1 * new Date().getTimezoneOffset() * 60 * 1000 // in ms
};
<commit_msg>#64 tempate for platform version<commit_after>"use strict";

// if local development, communicate with DEFAULT_HOSTNAME, otherwise - with web-UI host
const DEFAULT_HOSTNAME = "demo.semiot.ru";
const hostname = location.hostname === "localhost" ? DEFAULT_HOSTNAME : location.hostname;

const TSDB_BASE_URL = `http://${hostname}:4242/api/query`;

export default {
    COOKIE_NAME: "ru.semiot",
    VERSION: "@version",
    URLS: {
        messageBus: "ws://" + hostname + ":8080/ws",
        tripleStore: "http://" + hostname + ":3030/ds/query",
        tsdb: {
            archiveQuantity: `${TSDB_BASE_URL}?start={0}&end={1}&m=sum:{2}`,
            archiveEnum: `${TSDB_BASE_URL}?start={0}&end={1}&m=sum:{2}{enum_value=*}`,
            last: `${TSDB_BASE_URL}/last/{0}`
        }
    },
    TOPICS: {
        "device_registered": 'ru.semiot.devices.newandobserving',
        "device_turned_off": 'ru.semiot.devices.turnoff',
        "device_remove": 'ru.semiot.devices.remove'
    },
    SPARQL: {
        prefixes: {
            rdfs: 'http://www.w3.org/2000/01/rdf-schema#',
            ssn: 'http://purl.oclc.org/NET/ssnx/ssn#',
            rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
            ssncom: 'http://purl.org/NET/ssnext/communication#',
            saref: 'http://ontology.tno.nl/saref#',
            mcht: 'http://purl.org/NET/ssnext/machinetools#',
            qudt: 'http://www.qudt.org/qudt/owl/1.0.0/qudt/#',
            "qudt-quantity": 'http://qudt.org/vocab/quantity#',
            "qudt-unit": "http://qudt.org/vocab/unit#",
            om: 'http://purl.org/ifgi/om#'
        },
        types: {
            heatSystem: "http://purl.org/NET/ssnext/heatmeters#HeatMeter",
            electricSystem: "http://purl.org/NET/ssnext/electricmeters#ElectricMeter",
            temperature: "http://purl.org/NET/ssnext/heatmeters#Temperature",
            heat: "http://purl.org/NET/ssnext/heatmeters#Heat",
            observationResult: "http://purl.org/NET/ssnext/meters/core#hasQuantityValue"
        },
        queries: {
            getAllSystems: [
                "SELECT DISTINCT ?label ?uri ?state",
                "WHERE {",
                "   ?uri a ssn:System ;",
                "       saref:hasState ?state ;",
                "       rdfs:label ?label .",
                "}"
            ].join('\n'),
            getSystemEndpoint: `
                SELECT ?endpoint ?type ?observationType ?propLabel ?valueUnitLabel {
                  <{0}> ssn:hasSubSystem ?subsystem .
                  ?subsystem ssn:observes ?type .
                  ?subsystem ssn:hasMeasurementCapability ?mc .
                  ?mc ssn:forProperty ?prop .
                  ?prop rdfs:label ?propLabel .
                  ?mc ssn:hasMeasurementProperty ?mp .
                  ?mp ssn:hasValue ?v .
                  ?v a ?observationType .
                  ?v ssn:hasValue ?valueUnit .
                  ?valueUnit rdfs:label ?valueUnitLabel .
                  ?subsystem ssncom:hasCommunicationEndpoint ?endpoint .
                  ?endpoint ssncom:protocol 'WAMP' .
                }
            `,
            getSystemName: [
                "SELECT ?label {",
                "   <{0}> rdfs:label ?label .",
                "}"
            ].join('\n'),
            getMachineToolStates: `
                SELECT ?stateURI ?stateLabel ?stateDescription
                WHERE {
                    ?stateURI rdf:type mcht:MachineToolWorkingStateValue ;
                        rdfs:label ?stateLabel ;
                        rdfs:comment ?stateDescription .
                }
            `
        }
    },
    TIMEZONE_OFFSET: -1 * new Date().getTimezoneOffset() * 60 * 1000 // in ms
};
<|endoftext|>


<commit_before>var Car = require('./car');

var timer = 0;

var firstCar = new Car({y: 606, x: 700});
var secondCar = new Car({y: 554, x: -40}, 'right');
var thirdCar = new Car({y: 406, x: 700});
var fourCar = new Car({y: 506, x: 700});
var carOne = [firstCar];
var carTwo = [secondCar];
var carThree = [thirdCar];
var carFour = [fourCar];
var row = new Row()
function Enemies(context, frog) {
  timer++;
  row(context, frog, carOne, 170, 1, {y: 606, x: 700});
  rowTwo(context, frog);
  rowThree(context, frog);
  rowFour(context, frog);
}

function makeRandoNum(){
  return Math.floor((Math.random() * 100) + 1);
}

function Row(context, frog, array, num, speed, cord) {
  if (timer % num === 0 && array.length < 4) {
    array.push(new Car(cord));
  }
  groupLeft(context, frog, array, speed);
}

function rowTwo(context, frog) {
  var num = Math.floor((Math.random() * 100) + 1);
  if (timer % 150 === 0 && carTwo.length < 4 ) {
    carTwo.push(new Car({y: 554, x: -40}, 'right'));
  }
  groupRight(context, frog, carTwo, 2);
}

function rowThree(context, frog) {
  var num = Math.floor((Math.random() * 100) + 1);
  if (timer % 180 === 0 && carThree.length < 4 ) {
carThree.push(new Car({y: 406, x: 700}));
  }
  groupLeft(context, frog, carThree, 1.5);
}

function rowFour(context, frog) {
  if (timer % 180 === 0 && carFour.length < 4 ) {
    carFour.push(new Car({y: 506, x: 700}));
  }
  groupLeft(context, frog, carFour, 1);
}

function groupLeft(context, frog, array, speed) {
  array.forEach(function(car) {
    car.draw(context).moveLeft(speed).collision(frog);
    if (car.x < (-40)) {
      array.shift();
    }
  });
}

function groupRight(context, frog, array, speed) {
  array.forEach(function(car) {
    car.draw(context).moveRight(speed).collision(frog);
    if (car.x > (740)) {
      array.shift();
    }
  });
}
module.exports = Enemies;
<commit_msg>Refactoring<commit_after>var Car = require('./car');

var timer = 0;

var firstCar = new Car({y: 606, x: 700});
var secondCar = new Car({y: 554, x: -40}, 'right');
var thirdCar = new Car({y: 406, x: 700});
var fourCar = new Car({y: 506, x: 700});
var arrayOne = [firstCar];
var arrayTwo = [secondCar];
var arrayThree = [thirdCar];
var arrayFour = [fourCar];
var rowOne = new Row(1, {y: 606, x: 700}, arrayOne, 180);
var rowTwo = new Row(1, {y: 554, x: -40}, arrayTwo, 180, 'right');
// var rowThree = new Row(1, {y: 606, x: 700}, arrayOne, 180);

function Enemies(context, frog) {
  timer++;
  rowOne.update(context, frog, timer);
  rowTwo.update(context, frog, timer);
}

function makeRandoNum(){
  return Math.floor((Math.random() * 100) + 1);
}

function Row(speed, cord, array, difference, startPosition) {
  this.speed = speed;
  this.carArray = array;
  this.difference = difference;
  this.position = startPosition;
  if (this.position === 'right') {
    this.cord = cord;
  } else {
    this.cord = cord;
  }
}

Row.prototype.update = function(context, frog, timer) {
  debugger
  if (timer % this.difference === 0 && this.carArray.length < 4) {
    this.carArray.push(new Car(this.cord));
  };
  let array = this.carArray
  if (this.position === 'right') {
    groupRight(context, frog, array, this.speed)
  } else {
    groupLeft(context, frog, array, this.speed)
  };
};

function groupLeft(context, frog, array, speed) {
  array.forEach(function(car) {
    car.draw(context).moveLeft(speed).collision(frog);
    if (car.x < (-40)) {
      array.shift();
    }
  });
}

function groupRight(context, frog, array, speed) {
  array.forEach(function(car) {
    car.draw(context).moveRight(speed).collision(frog);
    if (car.x > (740)) {
      array.shift();
    }
  });
}
module.exports = Enemies;
<|endoftext|>


<commit_before>var fs     = require('fs');
var jade   = require('jade');
var hogan  = require('hogan.js');

/*
 * File Attribute Regexes
 */
// //@ viewbridge
// //-@ viewbridge
JADE_ATTR = /\/\/-?\s*@\s*viewbridge\s*$/im;

// {{!@ viewbridge }}
HOGAN_ATTR = /\{\{!\s*@\s*viewbridge\s*\}\}/i

/*
 * Export
 */
var ENGINES = module.exports = {};

ENGINES.isSupported = function(name) {
  return !!~Object.keys(ENGINES).indexOf(name.toLowerCase());
};

/*
 * Jade
 */
ENGINES.jade = {
  ext:           '.jade'
, attrRegex:     JADE_ATTR
, compileConfig: {client: true, compileDebug: false}
, compile: function(tmpltext) {
    return jade.compile(tmpltext, this.compileConfig).toString();
  }
, runtime: function() {
    if (this.runtime.cache) return this.runtime.cache;
    return this.runtime.cache = fs.readFileSync('node_modules/jade/runtime.js', 'utf8');
  }
};

/*
 * Hogan
 */
ENGINES.hogan = {
  ext:           '.hjs'
, attrRegex:     HOGAN_ATTR
, compileConfig: {asString: true}
, compile: function(tmpltext) {
    var fnstring = hogan.compile(tmpltext, this.compileConfig);
    return [
      '(function() {'
    , '  var t = new Hogan.Template(' + fnstring + ');'
    , '  return function(data, partial) {'
    , '    return t.render(data, partial);'
    , '  };'
    , '})();'
    ].join('\n');
  }
, runtime: function() {
    if (this.runtime.cache) return this.runtime.cache;
    return this.runtime.cache = fs.readFileSync('node_modules/hogan.js/web/builds/2.0.0/template-2.0.0.js', 'utf8');
  }
};
<commit_msg>Comments added for regex change<commit_after>var fs     = require('fs');
var jade   = require('jade');
var hogan  = require('hogan.js');

/*
 * File Attribute Regexes
 *
 * Whitespace flexible with the '@' and 'viewbridge'
 * Eg, '@viewbridge', '@ viewbridge', multiline(eg, mustache), etc
 */
// //@ viewbridge
// //-@ viewbridge
JADE_ATTR = /\/\/-?\s*@\s*viewbridge\s*$/im;

// {{!@ viewbridge }}
// {{!
//   @viewbridge
// }}
HOGAN_ATTR = /\{\{!\s*@\s*viewbridge\s*\}\}/i

/*
 * Export
 */
var ENGINES = module.exports = {};

ENGINES.isSupported = function(name) {
  return !!~Object.keys(ENGINES).indexOf(name.toLowerCase());
};

/*
 * Jade
 */
ENGINES.jade = {
  ext:           '.jade'
, attrRegex:     JADE_ATTR
, compileConfig: {client: true, compileDebug: false}
, compile: function(tmpltext) {
    return jade.compile(tmpltext, this.compileConfig).toString();
  }
, runtime: function() {
    if (this.runtime.cache) return this.runtime.cache;
    return this.runtime.cache = fs.readFileSync('node_modules/jade/runtime.js', 'utf8');
  }
};

/*
 * Hogan
 */
ENGINES.hogan = {
  ext:           '.hjs'
, attrRegex:     HOGAN_ATTR
, compileConfig: {asString: true}
, compile: function(tmpltext) {
    var fnstring = hogan.compile(tmpltext, this.compileConfig);
    return [
      '(function() {'
    , '  var t = new Hogan.Template(' + fnstring + ');'
    , '  return function(data, partial) {'
    , '    return t.render(data, partial);'
    , '  };'
    , '})();'
    ].join('\n');
  }
, runtime: function() {
    if (this.runtime.cache) return this.runtime.cache;
    return this.runtime.cache = fs.readFileSync('node_modules/hogan.js/web/builds/2.0.0/template-2.0.0.js', 'utf8');
  }
};
<|endoftext|>


<commit_before>$(document).ready(function() {
    // Update elements based off of clicked data attributes
    $(document).on('click', '#vagrantfile-details input', function(e){
        var operatingSystem = this.getAttribute('data-operating-system');
        var vmBox           = this.getAttribute('data-vagrantfile-vm-box');

        $('#operating-system').val(operatingSystem);
        $('#vagrantfile-vm-box').val(vmBox);
    });

    // input or select elements; allows user to create their own tags
    $('.tags, .select-tags-editable').selectize({
        plugins: ['remove_button'],
        delimiter: ',',
        persist: false,
        create: function(input) {
            return {
                value: input,
                text: input
            }
        }
    });

    // select elements; asks user for value of selected tags; cannot create own tags
    $('.select-tags-user-input').selectize({
        plugins: ['remove_button'],
        delimiter: ',',
        persist: false,
        create: false,
        onItemAdd: function(value, $item) {
            var suffix = prompt('Enter Value:') || '0';
            var label  = this.options[value].text + ' = ' + suffix;
            var data   = $.extend({}, this.options[value], {
                text: label
            });

            this.updateOption(value, data);
        }
    });

    // select elements; does not allow creating new tags
    $('.select-tags').selectize({
        delimiter: ',',
        persist: false,
        create: false
    });

    // add repeatable containers based on button data source-url
    $(document).on('click', 'button.addParentContainer', function(e){
        var sourceUrl = this.getAttribute('data-source-url');
        var buttonEle = $(this);

        $.ajax({
            url: sourceUrl,
            cache: false
        }).done(function(response) {
            $(response).insertBefore(buttonEle.closest('.row'));
        });

    });

    // delete repeatable containers based on button data id
    $(document).on('click', 'button.deleteParentContainer', function(e){
        var parentId = this.getAttribute('data-parent-id');
        var $parentContainer = $('#' + parentId);

        $parentContainer.remove();

    });
});
<commit_msg>v2 - Adding x button on selectize elements<commit_after>$(document).ready(function() {
    // Update elements based off of clicked data attributes
    $(document).on('click', '#vagrantfile-details input', function(e){
        var operatingSystem = this.getAttribute('data-operating-system');
        var vmBox           = this.getAttribute('data-vagrantfile-vm-box');

        $('#operating-system').val(operatingSystem);
        $('#vagrantfile-vm-box').val(vmBox);
    });

    // input or select elements; allows user to create their own tags
    $('.tags, .select-tags-editable').selectize({
        plugins: ['remove_button'],
        delimiter: ',',
        persist: false,
        create: function(input) {
            return {
                value: input,
                text: input
            }
        }
    });

    // select elements; asks user for value of selected tags; cannot create own tags
    $('.select-tags-user-input').selectize({
        plugins: ['remove_button'],
        delimiter: ',',
        persist: false,
        create: false,
        onItemAdd: function(value, $item) {
            var suffix = prompt('Enter Value:') || '0';
            var label  = this.options[value].text + ' = ' + suffix;
            var data   = $.extend({}, this.options[value], {
                text: label
            });

            this.updateOption(value, data);
        }
    });

    // select elements; does not allow creating new tags
    $('.select-tags').selectize({
        plugins: ['remove_button'],
        delimiter: ',',
        persist: false,
        create: false
    });

    // add repeatable containers based on button data source-url
    $(document).on('click', 'button.addParentContainer', function(e){
        var sourceUrl = this.getAttribute('data-source-url');
        var buttonEle = $(this);

        $.ajax({
            url: sourceUrl,
            cache: false
        }).done(function(response) {
            $(response).insertBefore(buttonEle.closest('.row'));
        });

    });

    // delete repeatable containers based on button data id
    $(document).on('click', 'button.deleteParentContainer', function(e){
        var parentId = this.getAttribute('data-parent-id');
        var $parentContainer = $('#' + parentId);

        $parentContainer.remove();

    });
});
<|endoftext|>