<commit_before>const LINE_CHANNEL_ACCESS_TOKEN = '{your token}';

var request = require('request');

/*
 * button template message definition
 */
var ButtonsMessage = function(text) {
    this.text = text;
    this.actions = [];
};

ButtonsMessage.prototype.addAction = function(text, data) {
    this.actions.push({
        text,
        data
    });
};

ButtonsMessage.prototype.build = function() {
    var message = {
        type: 'template',
        altText: 'スマホじゃないと話せないんだよね…。',
        template: {
            type: 'buttons',
            text: this.text,
            actions: []
        }
    };
    // TODO: this.actionsがなければエラー
    for (var a of this.actions) {
        var action = {
            type: 'postback',
            label: a.text,
            text: a.text,
            data: a.data
        }
        message.template.actions.push(action);
    }
    return message;
};

/*
 * main skeleton impl of LINE REPLY_MESSAGE API
 */
var Reply = function(replyToken) {
    this.replyToken = replyToken;
    this.messages = [];
};

Reply.prototype.url = 'https://api.line.me/v2/bot/message/reply';

Reply.prototype.method = 'POST';

Reply.prototype.headers = {
    'Content-type': 'application/json',
    'Authorization': 'Bearer ' + LINE_CHANNEL_ACCESS_TOKEN
};

Reply.prototype.addMessage = function(message) {
    this.messages.push(message);
}

Reply.prototype.addTextMessage = function(text) {
    var message = {
        type: 'text',
        text: text
    };
    this.addMessage(message);
}

Reply.prototype.addButtonsMessage = function(buttons) {
    this.addMessage(buttons.build());
}

Reply.prototype.execute = function() {
    // TODO: エラーハンドリング
    request({
        url: this.url,
        method: this.method,
        headers: this.headers,
        body: {
            replyToken: this.replyToken,
            messages: this.messages
        },
        json: true
    });
};

/*
 * bbbot module's main body.
 */
module.exports = class bbbot {
    static date(replyToken) {
        var ask = new Reply(replyToken);
        ask.addTextMessage('こんにちは！会議室を取るよ！');
        var buttons = new ButtonsMessage('いつ？');
        buttons.addAction('今日', "{ \"date\": \"today\" }");
        buttons.addAction('明日', "{ \"date\": \"tomorrow\" }");
        buttons.addAction('あさって', "{ \"date\": \"after_tomorrow\" }");
        buttons.addAction('それ以外', "{ \"date\": \"none_of_them\" }");
        ask.addButtonsMessage(buttons);
        ask.execute();
    }

    static time(replyToken, botMemory) {
        var date;
        if (botMemory.date == 'today') {
            date = '今日';
        } else if (botMemory.date == 'tomorrow') {
            date = 'あした';
        } else if (botMemory.date == 'after_tomorrow') {
            date = 'あさって';
        }
        var ask = new Reply(replyToken);
        ask.addTextMessage(date + 'だね！');
        ask.addTextMessage('なんじから？');
        ask.addMessage({
            type: 'template',
            altText: 'スマートフォンでないと話せないんだよね…。',
            template: {
                type: 'carousel',
                text: '何時？',
                columns: [
                    {
                        thumbnailImageUrl: 'https://bbbot-a63225.apaas.us6.oraclecloud.com/images/morning.jpg',
                        text: '朝',
                        actions: [
                            {
                                type: 'postback',
                                text: '9時',
                                label: '9時',
                                data: "{ \"time\": 9 }"
                            },
                            {
                                type: 'postback',
                                text: '10時',
                                label: '10時',
                                data: "{ \"time\": 10 }"
                            },
                            {
                                type: 'postback',
                                text: '11時',
                                label: '11時',
                                data: "{ \"time\": 11 }"
                            }
                        ]
                    },
                    {
                        thumbnailImageUrl: 'https://bbbot-a63225.apaas.us6.oraclecloud.com/images/daytime.jpg',
                        text: '昼',
                        actions: [
                            {
                                type: 'postback',
                                text: '13時',
                                label: '13時',
                                data: "{ \"time\": 13 }"
                            },
                            {
                                type: 'postback',
                                text: '14時',
                                label: '14時',
                                data: "{ \"time\": 14 }"
                            },
                            {
                                type: 'postback',
                                text: '15時',
                                label: '15時',
                                data: "{ \"time\": 15 }"
                            }
                        ]
                    },
                    {
                        thumbnailImageUrl: 'https://bbbot-a63225.apaas.us6.oraclecloud.com/images/evening.jpg',
                        text: '夜',
                        actions: [
                            {
                                type: 'postback',
                                text: '16時',
                                label: '16時',
                                data: "{ \"time\": 16 }"
                            },
                            {
                                type: 'postback',
                                text: '17時',
                                label: '17時',
                                data: "{ \"time\": 17 }"
                            },
                            {
                                type: 'postback',
                                text: 'それ以外',
                                label: 'それ以外',
                                data: "{ \"time\": \"none_of_them\" }"
                            }
                        ]
                    }
                ]
            }
        });
        ask.execute();
    }

    static turnout(replyToken, botMemory) {
        var ask = new Reply(replyToken);
        ask.addTextMessage(botMemory.time + '時だね！');
        ask.addTextMessage('なんにん？');
        ask.execute();
    }

    static duration(replyToken, botMemory) {
        var ask = new Reply(replyToken);
        ask.addTextMessage(botMemory.turnout + '人だね！');
        var buttons = new ButtonsMessage('なんぷん？');
        buttons.addAction('30分', "{ \"duration\": 30 }");
        buttons.addAction('60分', "{ \"duration\": 60 }");
        buttons.addAction('それ以外', "{ \"duration\": \"none_of_them\" }");
        ask.addButtonsMessage(buttons);
        ask.execute();
    }

    static room(replyToken, botMemory) {
        var ask = new Reply(replyToken);
        ask.addTextMessage(botMemory.duration + '分だね！');
        var buttons = new ButtonsMessage('開いている部屋はこれだよ。どれがいい？');
        buttons.addAction('15M1', "{ \"room\": \"15M1\" }");
        buttons.addAction('17M2', "{ \"room\": \"17M2\" }");
        buttons.addAction('19M3', "{ \"room\": \"19M3\" }");
        buttons.addAction('20M6', "{ \"room\": \"20M6\" }");
        ask.addButtonsMessage(buttons);
        ask.execute();
    }

    static title(replyToken, botMemory) {
        var ask = new Reply(replyToken);
        ask.addTextMessage('OK! 予約しちゃうよ。');
        ask.addTextMessage('なんて名前で予約する？');
        ask.execute();
    }

    static result(replyToken, botMemory) {
        var date;
        if (botMemory.date == 'today') {
            date = new Date();
        } else if (botMemory.date == 'tomorrow') {
            date = new Date((new Date().getTime()) + (60 * 60 * 24 * 1000));
        } else if (botMemory.date == 'after_tomorrow') {
            date = new Date((new Date().getTime()) + (60 * 60 * 24 * 1000 * 2));
        }
        var dateString = (date.getMonth() + 1) + '/' + date.getDate();

        var begin = botMemory.time + ':00';
        var end;
        if (botMemory.duration == 30) {
            end = botMemory.time + ':30';
        } else if (botMemory.duration == 60) {
            end = botMemory.time + 1 + ':00';
        }
        var ask = new Reply(replyToken);
        ask.addTextMessage('OK! 予約できたよ！');
        ask.addTextMessage('名前: ' + botMemory.title + '\n' + '日時: ' + dateString + ' ' + begin + '～' + end + '\n' + '場所: ' + botMemory.room);
        ask.execute();
    }

    static abandon(replyToken) {
        var ask = new Reply(replyToken);
        ask.addTextMessage('ちょっと僕にはむずかしいな・・・');
        ask.addTextMessage('近くのアドミさんに相談してみてね！');
        ask.execute();
    }
}
<commit_msg>Consolidate code duplicates<commit_after>const LINE_CHANNEL_ACCESS_TOKEN = '{your token}';

var request = require('request');

/*
 * buttons template message definition
 */
var Buttons = function(text) {
    this.text = text;
    this.thumbnailImageUrl = null;
    this.actions = [];
};

Buttons.prototype.addThumbnailImageUrl = function(url) {
    this.thumbnailImageUrl = url;
};

Buttons.prototype.addAction = function(text, data) {
    this.actions.push({
        text,
        data
    });
};

Buttons.prototype.build = function() {
    var obj = [];
    for (var a of this.actions) {
        var action = {
            type: 'postback',
            label: a.text,
            text: a.text,
            data: a.data
        }
        obj.push(action);
    }
    return obj;
};

var ButtonsMessage = function(buttons) {
    this.buttons = buttons;
};

ButtonsMessage.prototype.build = function() {
    var message = {
        type: 'template',
        altText: 'スマホじゃないと話せないんだよね…。',
        template: {
            type: 'buttons',
            thumbnailImageUrl: this.buttons.thumbnailImageUrl,
            text: this.buttons.text,
            actions: this.buttons.build()
        }
    };
    return message;
};

/*
 * carousel template message definition
 */
var CarouselMessage = function() {
    this.columns = [];
};

CarouselMessage.prototype.addColumn = function(buttonsAsColumn) {
    this.columns.push(buttonsAsColumn);
};

CarouselMessage.prototype.build = function() {
    var message = {
        type: 'template',
        altText: 'スマホじゃないと話せないんだよね…。',
        template: {
            type: 'carousel',
            text: this.text,
            columns: []
        }
    };
    // TODO: this.actionsがなければエラー
    for (var c of this.columns) {
        var colobj = {
            thumbnailImageUrl: c.thumbnailImageUrl,
            text: c.text,
            actions: c.build()
        }
        message.template.columns.push(colobj);
    }
    return message;
};

/*
 * main skeleton impl of LINE REPLY_MESSAGE API
 */
var Reply = function(replyToken) {
    this.replyToken = replyToken;
    this.messages = [];
};

Reply.prototype.addMessage = function(message) {
    this.messages.push(message);
};

Reply.prototype.addTextMessage = function(text) {
    var message = {
        type: 'text',
        text: text
    };
    this.addMessage(message);
};

Reply.prototype.addButtonsMessage = function(buttons) {
    this.addMessage(buttons.build());
};

Reply.prototype.addCarouselMessage = function(carousel) {
    console.log(carousel.build());
    this.addMessage(carousel.build());
};

Reply.prototype.execute = function() {
    // TODO: エラーハンドリング
    request({
        url: 'https://api.line.me/v2/bot/message/reply',
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
            'Authorization': 'Bearer ' + LINE_CHANNEL_ACCESS_TOKEN
        },
        body: {
            replyToken: this.replyToken,
            messages: this.messages
        },
        json: true
    });
};

/*
 * bbbot module's main body.
 */
module.exports = class bbbot {
    static date(replyToken) {
        var ask = new Reply(replyToken);
        ask.addTextMessage('こんにちは！会議室を取るよ！');
        var buttons = new Buttons('いつ？');
        buttons.addAction('今日', "{ \"date\": \"today\" }");
        buttons.addAction('明日', "{ \"date\": \"tomorrow\" }");
        buttons.addAction('あさって', "{ \"date\": \"after_tomorrow\" }");
        buttons.addAction('それ以外', "{ \"date\": \"none_of_them\" }");
        ask.addButtonsMessage(new ButtonsMessage(buttons));
        ask.execute();
    }

    static time(replyToken, botMemory) {
        var date;
        if (botMemory.date == 'today') {
            date = '今日';
        } else if (botMemory.date == 'tomorrow') {
            date = 'あした';
        } else if (botMemory.date == 'after_tomorrow') {
            date = 'あさって';
        }
        var ask = new Reply(replyToken);
        ask.addTextMessage(date + 'だね！');
        ask.addTextMessage('なんじから？');

        var carousel = new CarouselMessage();

        var column_morning = new Buttons('朝');
        column_morning.addThumbnailImageUrl('https://bbbot-a63225.apaas.us6.oraclecloud.com/images/morning.jpg');
        column_morning.addAction('9時', "{ \"time\": 9 }");
        column_morning.addAction('10時', "{ \"time\": 10 }");
        column_morning.addAction('11時', "{ \"time\": 11 }");
        carousel.addColumn(column_morning);

        var column_daytime = new Buttons('昼');
        column_daytime.addThumbnailImageUrl('https://bbbot-a63225.apaas.us6.oraclecloud.com/images/daytime.jpg');
        column_daytime.addAction('13時', "{ \"time\": 13 }");
        column_daytime.addAction('14時', "{ \"time\": 14 }");
        column_daytime.addAction('15時', "{ \"time\": 15 }");
        carousel.addColumn(column_daytime);

        var column_evening = new Buttons('夜');
        column_evening.addThumbnailImageUrl('https://bbbot-a63225.apaas.us6.oraclecloud.com/images/evening.jpg');
        column_evening.addAction('16時', "{ \"time\": 17 }");
        column_evening.addAction('17時', "{ \"time\": 17 }");
        column_evening.addAction('それ以外', "{ \"time\": \"none_of_them\" }");
        carousel.addColumn(column_evening);

        ask.addCarouselMessage(carousel);
        ask.execute();
    }

    static turnout(replyToken, botMemory) {
        var ask = new Reply(replyToken);
        ask.addTextMessage(botMemory.time + '時だね！');
        ask.addTextMessage('なんにん？');
        ask.execute();
    }

    static duration(replyToken, botMemory) {
        var ask = new Reply(replyToken);
        ask.addTextMessage(botMemory.turnout + '人だね！');
        var buttons = new Buttons('なんぷん？');
        buttons.addAction('30分', "{ \"duration\": 30 }");
        buttons.addAction('60分', "{ \"duration\": 60 }");
        buttons.addAction('それ以外', "{ \"duration\": \"none_of_them\" }");
        ask.addButtonsMessage(new ButtonsMessage(buttons));
        ask.execute();
    }

    static room(replyToken, botMemory) {
        var ask = new Reply(replyToken);
        ask.addTextMessage(botMemory.duration + '分だね！');
        var buttons = new Buttons('開いている部屋はこれだよ。どれがいい？');
        buttons.addAction('15M1', "{ \"room\": \"15M1\" }");
        buttons.addAction('17M2', "{ \"room\": \"17M2\" }");
        buttons.addAction('19M3', "{ \"room\": \"19M3\" }");
        buttons.addAction('20M6', "{ \"room\": \"20M6\" }");
        ask.addButtonsMessage(new ButtonsMessage(buttons));
        ask.execute();
    }

    static title(replyToken, botMemory) {
        var ask = new Reply(replyToken);
        ask.addTextMessage('OK! 予約しちゃうよ。');
        ask.addTextMessage('なんて名前で予約する？');
        ask.execute();
    }

    static result(replyToken, botMemory) {
        var date;
        if (botMemory.date == 'today') {
            date = new Date();
        } else if (botMemory.date == 'tomorrow') {
            date = new Date((new Date().getTime()) + (60 * 60 * 24 * 1000));
        } else if (botMemory.date == 'after_tomorrow') {
            date = new Date((new Date().getTime()) + (60 * 60 * 24 * 1000 * 2));
        }
        var dateString = (date.getMonth() + 1) + '/' + date.getDate();

        var begin = botMemory.time + ':00';
        var end;
        if (botMemory.duration == 30) {
            end = botMemory.time + ':30';
        } else if (botMemory.duration == 60) {
            end = botMemory.time + 1 + ':00';
        }
        var ask = new Reply(replyToken);
        ask.addTextMessage('OK! 予約できたよ！');
        ask.addTextMessage('名前: ' + botMemory.title + '\n' + '日時: ' + dateString + ' ' + begin + '～' + end + '\n' + '場所: ' + botMemory.room);
        ask.execute();
    }

    static abandon(replyToken) {
        var ask = new Reply(replyToken);
        ask.addTextMessage('ちょっと僕にはむずかしいな・・・');
        ask.addTextMessage('近くのアドミさんに相談してみてね！');
        ask.execute();
    }
}
<|endoftext|>


<commit_before>'use strict'
import 'lodash/lodash'

const ConfigField = {
  template: "#vue-config-field",
  props: [
    "pluginType",
    "option",
    "initialExpression",
    "initialTimeFormat",
    "initialTextValue",
  ],

  data: function() {
    return {
      expression: null,
      timeFormat: null,
      textValue: null,
    }
  },

  filters: {
    humanize: function(value) {
      return _.capitalize(value.replace(/_/g, " "))
    }
  },

  mounted: function() {
    if (this.option.name === "expression") {
      this.expression = this.initialExpression
    } else if (this.option.name === "time_format") {
      this.timeFormat = this.initialTimeFormat
    } else {
      this.textValue = this.initialTextValue || this.option.default
    }
  },

  updated: function() {
    if (this.option.name === "expression") {
      this.expression = this.initialExpression
    }
    if (this.option.name === "time_format") {
      this.timeFormat = this.initialTimeFormat
    }
    this.$nextTick(() => {
      console.log("config-field updated")
      $("[data-toggle=tooltip]").tooltip("dispose")
      $("[data-toggle=tooltip]").tooltip("enable")
    })
  },

  watch: {
    "expression": function(newValue, oldValue) {
      this.$emit("change-parse-config", {
        "expression": this.expression,
        "timeFormat": this.timeFormat
      })
    },
    "timeFormat": function(newValue, oldValue) {
      this.$emit("change-parse-config", {
        "expression": this.expression,
        "timeFormat": this.timeFormat
      })
    }
  },

  methods: {
    inputId: function(pluginType, option) {
      if (pluginType === "output") {
        return `setting_${option.name}`
      } else {
        return `setting_${pluginType}_0__${option.name}`
      }

    },
    inputName: function(pluginType, option) {
      if (pluginType === "output") {
        return `setting[${option.name}]`
      } else {
        return `setting[${pluginType}[0]][${option.name}]`
      }
    },
    checked: function(checked) {
      if (checked === true || checked === "true") {
        return "checked"
      } else {
        return ""
      }
    }
  }
}

export { ConfigField as default }
<commit_msg>Apply snakeCase method to camel case string<commit_after>'use strict'
import 'lodash/lodash'

const ConfigField = {
  template: "#vue-config-field",
  props: [
    "pluginType",
    "option",
    "initialExpression",
    "initialTimeFormat",
    "initialTextValue",
  ],

  data: function() {
    return {
      expression: null,
      timeFormat: null,
      textValue: null,
    }
  },

  filters: {
    humanize: function(value) {
      return _.capitalize(value.replace(/_/g, " "))
    }
  },

  mounted: function() {
    if (this.option.name === "expression") {
      this.expression = this.initialExpression
    } else if (this.option.name === "time_format") {
      this.timeFormat = this.initialTimeFormat
    } else {
      this.textValue = this.initialTextValue || this.option.default
    }
  },

  updated: function() {
    if (this.option.name === "expression") {
      this.expression = this.initialExpression
    }
    if (this.option.name === "time_format") {
      this.timeFormat = this.initialTimeFormat
    }
    this.$nextTick(() => {
      console.log("config-field updated")
      $("[data-toggle=tooltip]").tooltip("dispose")
      $("[data-toggle=tooltip]").tooltip("enable")
    })
  },

  watch: {
    "expression": function(newValue, oldValue) {
      this.$emit("change-parse-config", {
        "expression": this.expression,
        "timeFormat": this.timeFormat
      })
    },
    "timeFormat": function(newValue, oldValue) {
      this.$emit("change-parse-config", {
        "expression": this.expression,
        "timeFormat": this.timeFormat
      })
    }
  },

  methods: {
    inputId: function(pluginType, option) {
      if (pluginType === "output") {
        return `setting_${option.name}`
      } else {
        return `setting_${_.snakeCase(pluginType)}_0__${option.name}`
      }
    },
    inputName: function(pluginType, option) {
      if (pluginType === "output") {
        return `setting[${option.name}]`
      } else {
        return `setting[${_.snakeCase(pluginType)}[0]][${option.name}]`
      }
    },
    checked: function(checked) {
      if (checked === true || checked === "true") {
        return "checked"
      } else {
        return ""
      }
    }
  }
}

export { ConfigField as default }
<|endoftext|>


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

	return ["api", "$timeout", function(api, $timeout) {

		return {
			scope: true,

			restrict: "A",

			templateUrl: "/partials/pod_carousel.html",

			link: function(scope, element, attrs) {
				scope.startPod = 0;
				scope.pods = api.pods.get();

				scope.pods.$promise.then(function(){
					Array.prototype.sort.call(scope.pods,function(a,b) { return a.id < b.id; });
				});

				$timeout(function() {
					scope.startPod++;
				}, 10000);
			},
		};
	}];
});<commit_msg>Sort correct pod array.<commit_after>/**
 * Copyright 2015 Ian Davies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 * 		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
define([], function() {

	return ["api", "$timeout", function(api, $timeout) {

		return {
			scope: true,

			restrict: "A",

			templateUrl: "/partials/pod_carousel.html",

			link: function(scope, element, attrs) {
				scope.startPod = 0;
				scope.pods = api.pods.get();

				scope.pods.$promise.then(function(){
					Array.prototype.sort.call(scope.pods.results,function(a,b) { return a.id > b.id; });
					scope.$apply();
				});

				$timeout(function() {
					scope.startPod++;
				}, 10000);
			},
		};
	}];
});<|endoftext|>


<commit_before>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
const routerPrefix = '/react-router'

module.exports = {
  entry: './index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      }, {
        test: /\.(js|jsx)$/,
        use: [{
          loader: 'babel-loader',
          // 该选项必须添加
          query: {
            presets: ['es2015', 'stage-0', 'react']
          }
        }]
      }, {
        test: /\.html$/,
        loader: 'html-loader'
      }
    ]
  },
  // https://webpack.docschina.org/configuration/dev-server/#devserver-historyapifallback
  // /home 页面无法访问的解决办法，这是在 webpack-dev-server 层面需要支持的
  // 当使用 HTML5 History API 时，任意的 404 响应都可能需要被替代为 index.html。通过传入以下启用：
  devServer: {
    historyApiFallback: true,
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        prefix: JSON.stringify(routerPrefix)
      }
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html'
    })
  ]
}
<commit_msg>docs: 更新之前 /home 不生效的解释说明<commit_after>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
const routerPrefix = '/react-router'

module.exports = {
  entry: './index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      }, {
        test: /\.(js|jsx)$/,
        use: [{
          loader: 'babel-loader',
          // 该选项必须添加
          query: {
            presets: ['es2015', 'stage-0', 'react']
          }
        }]
      }, {
        test: /\.html$/,
        loader: 'html-loader'
      }
    ]
  },

  // /home 页面无法访问的原因其实是 webpack-dev-server 如何定位文件的原理
  // webpack-dev-sever 如何定位文件呢
  // webpack-dev-sever 是静态资源服务器，他会通过你的 output 配置去读取文件，通过’/’分割以文件查找的模式匹配文件。
  // 这样自然就产生问题了，因为你配置的路由并不是实际存在的文件，根据文件查找的方式是找不到的，只会 404。
  // https://webpack.docschina.org/configuration/dev-server/#devserver-historyapifallback
  // /home 页面无法访问的解决办法
  // 当使用 HTML5 History API 时，任意的 404 响应都可能需要被替代为 index.html。通过传入以下启用：`historyApiFallback: true`
  // 加入后，可以看到 webpack-dev-server 启动后的 log 中有一行 `404s will fallback to /index.html`
  // 意味着原本会进入 /home 目录下查找，但在设置后路径会执行 index.html
  devServer: {
    historyApiFallback: true,
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        prefix: JSON.stringify(routerPrefix)
      }
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html'
    })
  ]
}
<|endoftext|>


<commit_before>// simulate and plot a passive membrane with a pulse
function plotPassiveMembrane()
{
    // get the drawing surface
    var canvas = document.getElementById('PassiveMembranePlot');
    var context = canvas.getContext('2d');

    // clear the canvas
    canvas.width = canvas.width;

    // create the passive membrane
    var model = componentModel.componentModel();
    var passiveMembrane = electrophys.passiveMembrane(model,
        { C: 2e-9, g_leak: 1e-6, E_leak: -65e-3 });

    passiveMembrane.addCurrent(electrophys.pulse(
        {start: 15e-3, width: 10e-3, height: 10e-9}));

    // simulate it
    var result = model.integrate({tMin: 0, tMax: 50e-3});
    var t = result.t;
    var v = passiveMembrane.V(result.y, result.t);

    // set up axes for the plot
    var timeAxis = graph.linearAxis(t[0], t[t.length-1], 0, 500);
    var vAxis = graph.linearAxis(-70e-3, -50e-3, 200, 0);
    var vPlot = graph.plotArea(timeAxis, vAxis);

    // plot the results
    vPlot.addXYLine(t, v);
    vPlot.draw(context);
}

// simulate and plot the C2 neuron from Calin-Jageman et al 2007
function plotC2()
{
    // get the drawing surface
    var canvas = document.getElementById('C2Plot');
    var context = canvas.getContext('2d');

    // clear the canvas
    canvas.width = canvas.width;

    // create the passive membrane
    var model = componentModel.componentModel();
    var C2 = electrophys.gettingIFNeuron(model,
        { C: 2.27e-9, g_leak: 1/23.3e6, E_leak: -48e-3,
            theta_ss: -34e-3, theta_r: 0e-3, theta_tau: 65.0e-3 });
    var C2Fast = electrophys.gettingSynapse(model, C2, C2,
        { W: 0.12000e-6, E_rev: -80e-3, tau_open:   10e-3, tau_close:   30e-3 });
    var C2Med = electrophys.gettingSynapse(model, C2, C2,
        { W: 0.02800e-6, E_rev: -80e-3, tau_open:   10e-3, tau_close: 1200e-3 });
    var C2Slow = electrophys.gettingSynapse(model, C2, C2,
        { W: 0.00300e-6, E_rev: -80e-3, tau_open: 4000e-3, tau_close: 4000e-3 });

    C2.addCurrent(electrophys.pulse(
        {start: 1, width: 5, height: 2e-9}));

    // simulate it
    var result = model.integrate({tMin: 0, tMax: 7, tMaxStep: 2e-3});
    var t = result.t;
    var v = C2.VWithSpikes(result.y, result.t);

    // set up axes for the plot
    var timeAxis = graph.linearAxis(t[0], t[t.length-1], 0, 500);
    var vAxis = graph.linearAxis(-80e-3, 55e-3, 200, 0);
    var vPlot = graph.plotArea(timeAxis, vAxis);

    // plot the results
    vPlot.addXYLine(t, v);
    vPlot.draw(context);
}

// simulate and plot the DSI neuron from Calin-Jageman et al 2007
function plotDSI()
{
    // get the drawing surface
    var canvas = document.getElementById('DSIPlot');
    var context = canvas.getContext('2d');

    // clear the canvas
    canvas.width = canvas.width;

    // create the passive membrane
    var model = componentModel.componentModel();
    var DSI = electrophys.gettingIFNeuron(model,
        { C: 1.57e-9, g_leak: 1/38.8e6, E_leak: -47.5e-3,
            theta_ss: -50-3, theta_r: 200e-3, theta_tau: 15.0e-3 });
    var DSIShunt = electrophys.gettingShuntConductance(model, DSI,
        { G: 0.08e-6, E_rev: -47.5e-3, B_m: 29e-3, C_m: -1e-3, tau_m: 10e-3,
                B_h: -100e-3, C_h: 1e-3, tau_h: 100000e-3 });
        //{ G: 1e-6, E_rev: -70e-3, B_m: 30e-3, C_m: -9e-3, tau_m: 10e-3,
        //        B_h: 54e-3, C_h: 4e-3, tau_h: 600e-3 });
    var DSIFast = electrophys.gettingSynapse(model, DSI, DSI,
        { W: 0.30000e-6, E_rev: -80e-3, tau_open:   10e-3, tau_close:   85e-3 });
    var DSISlow = electrophys.gettingSynapse(model, DSI, DSI,
        { W: 0.01200e-6, E_rev: -80e-3, tau_open:  200e-3, tau_close: 2800e-3 });

    DSI.addCurrent(electrophys.pulse(
        {start: 0.5, width: 5, height: 3e-9}));

    // simulate it
    var result = model.integrate({tMin: -0.6, tMax: 7, tMaxStep: 2e-3});
    var t = result.t;
    var v = DSI.VWithSpikes(result.y, result.t);

    // set up axes for the plot
    var timeAxis = graph.linearAxis(0, t[t.length-1], 0, 500);
    var vAxis = graph.linearAxis(-80e-3, 55e-3, 200, 0);
    var vPlot = graph.plotArea(timeAxis, vAxis);

    // plot the results
    vPlot.addXYLine(t, v);
    vPlot.draw(context);
}

// simulate and plot the VSI neuron from Calin-Jageman et al 2007
function plotVSI()
{
    // get the drawing surface
    var canvas = document.getElementById('VSIPlot');
    var context = canvas.getContext('2d');

    // clear the canvas
    canvas.width = canvas.width;

    // create the passive membrane
    var model = componentModel.componentModel();
    var VSI = electrophys.gettingIFNeuron(model,
        { C: 3.2e-9, g_leak: 1/14e6, E_leak: -56e-3, V_rest: -70e-3,
            theta_ss: -38e-3, theta_r: 10e-3, theta_tau: 10.0e-3 });
    var VSIShunt = electrophys.gettingShuntConductance(model, VSI,
        { G: 1e-6, E_rev: -70e-3, B_m: 30e-3, C_m: -9e-3, tau_m: 10e-3,
                B_h: 54e-3, C_h: 4e-3, tau_h: 600e-3 });
    var VSIFast = electrophys.gettingSynapse(model, VSI, VSI,
        { W: 0.54000e-6, E_rev: -80e-3, tau_open:   10e-3, tau_close:  100e-3 });
    var VSISlow = electrophys.gettingSynapse(model, VSI, VSI,
        { W: 0.00460e-6, E_rev: -80e-3, tau_open: 1000e-3, tau_close: 2500e-3 });

    VSI.addCurrent(electrophys.pulse(
        {start: 0.5, width: 5, height: 2.5e-9}));

    // simulate it
    var result = model.integrate({tMin: -0.6, tMax: 7, tMaxStep: 2e-3});
    var t = result.t;
    var v = VSI.VWithSpikes(result.y, result.t);

    // set up axes for the plot
    var timeAxis = graph.linearAxis(0, t[t.length-1], 0, 500);
    var vAxis = graph.linearAxis(-80e-3, 55e-3, 200, 0);
    var vPlot = graph.plotArea(timeAxis, vAxis);

    // plot the results
    vPlot.addXYLine(t, v);
    vPlot.draw(context);
}

<commit_msg>Fix typo that broke DSI<commit_after>// simulate and plot a passive membrane with a pulse
function plotPassiveMembrane()
{
    // get the drawing surface
    var canvas = document.getElementById('PassiveMembranePlot');
    var context = canvas.getContext('2d');

    // clear the canvas
    canvas.width = canvas.width;

    // create the passive membrane
    var model = componentModel.componentModel();
    var passiveMembrane = electrophys.passiveMembrane(model,
        { C: 2e-9, g_leak: 1e-6, E_leak: -65e-3 });

    passiveMembrane.addCurrent(electrophys.pulse(
        {start: 15e-3, width: 10e-3, height: 10e-9}));

    // simulate it
    var result = model.integrate({tMin: 0, tMax: 50e-3});
    var t = result.t;
    var v = passiveMembrane.V(result.y, result.t);

    // set up axes for the plot
    var timeAxis = graph.linearAxis(t[0], t[t.length-1], 0, 500);
    var vAxis = graph.linearAxis(-70e-3, -50e-3, 200, 0);
    var vPlot = graph.plotArea(timeAxis, vAxis);

    // plot the results
    vPlot.addXYLine(t, v);
    vPlot.draw(context);
}

// simulate and plot the C2 neuron from Calin-Jageman et al 2007
function plotC2()
{
    // get the drawing surface
    var canvas = document.getElementById('C2Plot');
    var context = canvas.getContext('2d');

    // clear the canvas
    canvas.width = canvas.width;

    // create the passive membrane
    var model = componentModel.componentModel();
    var C2 = electrophys.gettingIFNeuron(model,
        { C: 2.27e-9, g_leak: 1/23.3e6, E_leak: -48e-3,
            theta_ss: -34e-3, theta_r: 0e-3, theta_tau: 65.0e-3 });
    var C2Fast = electrophys.gettingSynapse(model, C2, C2,
        { W: 0.12000e-6, E_rev: -80e-3, tau_open:   10e-3, tau_close:   30e-3 });
    var C2Med = electrophys.gettingSynapse(model, C2, C2,
        { W: 0.02800e-6, E_rev: -80e-3, tau_open:   10e-3, tau_close: 1200e-3 });
    var C2Slow = electrophys.gettingSynapse(model, C2, C2,
        { W: 0.00300e-6, E_rev: -80e-3, tau_open: 4000e-3, tau_close: 4000e-3 });

    C2.addCurrent(electrophys.pulse(
        {start: 1, width: 5, height: 2e-9}));

    // simulate it
    var result = model.integrate({tMin: 0, tMax: 7, tMaxStep: 2e-3});
    var t = result.t;
    var v = C2.VWithSpikes(result.y, result.t);

    // set up axes for the plot
    var timeAxis = graph.linearAxis(t[0], t[t.length-1], 0, 500);
    var vAxis = graph.linearAxis(-80e-3, 55e-3, 200, 0);
    var vPlot = graph.plotArea(timeAxis, vAxis);

    // plot the results
    vPlot.addXYLine(t, v);
    vPlot.draw(context);
}

// simulate and plot the DSI neuron from Calin-Jageman et al 2007
function plotDSI()
{
    // get the drawing surface
    var canvas = document.getElementById('DSIPlot');
    var context = canvas.getContext('2d');

    // clear the canvas
    canvas.width = canvas.width;

    // create the passive membrane
    var model = componentModel.componentModel();
    var DSI = electrophys.gettingIFNeuron(model,
        { C: 1.57e-9, g_leak: 1/38.8e6, E_leak: -47.5e-3,
            theta_ss: -50e-3, theta_r: 200e-3, theta_tau: 15.0e-3 });
    var DSIShunt = electrophys.gettingShuntConductance(model, DSI,
        { G: 0.08e-6, E_rev: -47.5e-3, B_m: 29e-3, C_m: -1e-3, tau_m: 10e-3,
                B_h: -100e-3, C_h: 1e-3, tau_h: 100000e-3 });
        //{ G: 1e-6, E_rev: -70e-3, B_m: 30e-3, C_m: -9e-3, tau_m: 10e-3,
        //        B_h: 54e-3, C_h: 4e-3, tau_h: 600e-3 });
    var DSIFast = electrophys.gettingSynapse(model, DSI, DSI,
        { W: 0.30000e-6, E_rev: -80e-3, tau_open:   10e-3, tau_close:   85e-3 });
    var DSISlow = electrophys.gettingSynapse(model, DSI, DSI,
        { W: 0.01200e-6, E_rev: -80e-3, tau_open:  200e-3, tau_close: 2800e-3 });

    DSI.addCurrent(electrophys.pulse(
        {start: 0.5, width: 5, height: 3e-9}));

    // simulate it
    var result = model.integrate({tMin: -0.6, tMax: 7, tMaxStep: 2e-3});
    var t = result.t;
    var v = DSI.VWithSpikes(result.y, result.t);

    // set up axes for the plot
    var timeAxis = graph.linearAxis(0, t[t.length-1], 0, 500);
    var vAxis = graph.linearAxis(-80e-3, 55e-3, 200, 0);
    var vPlot = graph.plotArea(timeAxis, vAxis);

    // plot the results
    vPlot.addXYLine(t, v);
    vPlot.draw(context);
}

// simulate and plot the VSI neuron from Calin-Jageman et al 2007
function plotVSI()
{
    // get the drawing surface
    var canvas = document.getElementById('VSIPlot');
    var context = canvas.getContext('2d');

    // clear the canvas
    canvas.width = canvas.width;

    // create the passive membrane
    var model = componentModel.componentModel();
    var VSI = electrophys.gettingIFNeuron(model,
        { C: 3.2e-9, g_leak: 1/14e6, E_leak: -56e-3,
            theta_ss: -38e-3, theta_r: 10e-3, theta_tau: 10.0e-3 });
    var VSIShunt = electrophys.gettingShuntConductance(model, VSI,
        { G: 1e-6, E_rev: -70e-3, B_m: 30e-3, C_m: -9e-3, tau_m: 10e-3,
                B_h: 54e-3, C_h: 4e-3, tau_h: 600e-3 });
    var VSIFast = electrophys.gettingSynapse(model, VSI, VSI,
        { W: 0.54000e-6, E_rev: -80e-3, tau_open:   10e-3, tau_close:  100e-3 });
    var VSISlow = electrophys.gettingSynapse(model, VSI, VSI,
        { W: 0.00460e-6, E_rev: -80e-3, tau_open: 1000e-3, tau_close: 2500e-3 });

    VSI.addCurrent(electrophys.pulse(
        {start: 0.5, width: 5, height: 2.5e-9}));

    // simulate it
    var result = model.integrate({tMin: -0.6, tMax: 7, tMaxStep: 2e-3});
    var t = result.t;
    var v = VSI.VWithSpikes(result.y, result.t);

    // set up axes for the plot
    var timeAxis = graph.linearAxis(0, t[t.length-1], 0, 500);
    var vAxis = graph.linearAxis(-80e-3, 55e-3, 200, 0);
    var vPlot = graph.plotArea(timeAxis, vAxis);

    // plot the results
    vPlot.addXYLine(t, v);
    vPlot.draw(context);
}

<|endoftext|>


<commit_before>
import module from '../module';
import GameState from '../../rogue/init/gamestate';

module.controller('Dungeon', ($scope) => {

  $scope.currentFloor = 0;

  GameState.on('start', () => {
    $scope.world = GameState.world;
    $scope.victory = GameState.winCondition;
  });

  GameState.on('descend', () => {
    $scope.currentFloor = GameState.currentFloor;
  });

});<commit_msg>fix(game): dungeon level is reset when a new game starts<commit_after>
import module from '../module';
import GameState from '../../rogue/init/gamestate';

module.controller('Dungeon', ($scope) => {

  $scope.currentFloor = 0;

  GameState.on('start', () => {
    $scope.world = GameState.world;
    $scope.victory = GameState.winCondition;
    $scope.currentFloor = GameState.currentFloor;
  });

  GameState.on('descend', () => {
    $scope.currentFloor = GameState.currentFloor;
  });

});
<|endoftext|>


<commit_before>/**
 * Variable auxiliar para conocer el estado de edición de los elementos
 */
var enEdicion = false;

// Metodo para eliminar elemento
$(document).on({
	'paste' : function(e) {

		e.preventDefault();
		var text = '';
		if (e.clipboardData || e.originalEvent.clipboardData) {
			text = (e.originalEvent || e).clipboardData.getData('text/plain');
		} else if (window.clipboardData) {
			text = window.clipboardData.getData('Text');
		}
		if (document.queryCommandSupported('insertText')) {
			document.execCommand('insertText', false, text);
		} else {
			document.execCommand('paste', false, text);
		}
	}
}, '.home-article-desc');

//Revisa lo que hay que borrar
setInterval(function() {
	$('.sinGuardar').each(function(index) {
		var element = $(this);
		if (($(this).text()).trim() == '') {
			$(this).text('Agregar texto');
			$(this).data('new', 'esNuevo');
		} else {
			var token = element.data('token');
			var url = basePath
					+ 'admin-panel/editar-historia?token='
					+ token;

			if (element.data('progress') == 'noProceso') {
				element.data('progress', 'enProceso');
				var valor = element.html();

				$.ajax({
					url : url,
					data : {
						valor : valor,
						token : token
					},
					method : "POST",
					success : function(response) {

						element.data('progress', 'noProceso');
						element.removeClass('sinGuardar');
					}
				});
			} else if (element.data('progress') == 'enProceso') {
				element.addClass('sinGuardar');
			}
		}
	});
}, 1000);

//Metodo para guardar al elemento
$(document).on(
		{
			'focus' : function() {
				var esNuevo = $(this).data('new');
				if (esNuevo == 'esNuevo') {
					$(this).text('');
				}
			},
			'focusout' : function() {
				var element = $(this);
				if (($(this).text()).trim() == '') {
					$(this).text('Agregar texto');
					$(this).data('new', 'esNuevo');
				} else {
					var token = element.data('token');
					var url = basePath
							+ 'admin-panel/editar-historia?token='
							+ token;

					if (element.data('progress') == 'noProceso') {
						element.data('progress', 'enProceso');
						var valor = element.html();

						$.ajax({
							url : url,
							data : {
								valor : valor,
								token : token
							},
							method : "POST",
							success : function(response) {

								element.data('progress', 'noProceso');
							}
						});
					} else if (element.data('progress') == 'enProceso') {
						element.addClass('sinGuardar');
					}
				}
			},
			'DOMSubtreeModified' : function() {
				$(this).data('new', 'noNuevo');
			}

		}, '.home-article-desc');

function cambiarImagen(input, elementjs){
	readURL(elementjs, input);
	guardarImagen(input, elementjs);
}

/**
 * Pone la imagen para vista previa
 *
 * @param input
 * @param element
 */
function readURL(input, element) {

	var file = input.files[0];

	if (!file) {

		return false;
	}

	var imagefile = file.type;

	var filename = element.val();

	if (filename.substring(3, 11) == 'fakepath') {
		filename = filename.substring(12);
	}// remove c:\fake at beginning from localhost chrome
	// var url = base+'usrUsuarios/guardarFotosCompetencia';

	var match = [ "image/jpeg", "image/jpg", 'image/png' ];

	if (!((imagefile == match[0]) || (imagefile == match[1]) || (imagefile == match[2]))) {

		alert('Archivo no valido');

		return false;
	}

	if (input.files && input.files[0]) {
		var reader = new FileReader();

		reader.onload = function(e) {
			$(".image-change-"+element.data('token')).attr('src', e.target.result);
		}

		reader.readAsDataURL(input.files[0]);
	}
}

/**
 * Guarda la imagen en la base de datos
 *
 * @param input
 * @param file
 */
function guardarImagen(input, jav) {

	var token = input.data('token');

	var data = new FormData();
	data.append('fileHistoria', jav.files[0]);
	$.ajax({
		url : basePath + "admin-panel/guardar-imagen-historia?token="
				+ token,
		type : "POST",
		data : data,
		processData : false, // Work around #1
		contentType : false, // Work around #2
		success : function() {

		},
		cache : false,
		error : function() {
			alert("Failed");
		},
		// Work around #3
		xhr : function() {
			var xhr = new window.XMLHttpRequest();
			// Upload progress
			xhr.upload.addEventListener("progress", function(evt) {
				if (evt.lengthComputable) {
					var percentComplete = evt.loaded / evt.total;
					// Do something with upload progress
					console.log('upload' + percentComplete);
				}
			}, false);
			// Download progress
			xhr.addEventListener("progress", function(evt) {
				if (evt.lengthComputable) {
					var percentComplete = evt.loaded / evt.total;
					// Do something with download progress
					console.log('download' + percentComplete);
				}
			}, false);
			return xhr;
		}
	});
}

$(document).ready(function(){
	$("#js-edicion-capitulos").on('click', function(){

		if (!enEdicion) {
			enEdicion = true;
			habilitarEdicion();
		} else {
			enEdicion = false;
			desHabilitarEdicion();
		}

	});
});

function habilitarEdicion() {
	$("#js-edicion-capitulos i").removeClass('ion-android-create');
	$("#js-edicion-capitulos i").addClass('ion-checkmark-circled');
	$('.listado-image').css('display', 'block');
	$('.home-article-desc').attr('contenteditable', 'true');

	$('#modal-agregar-post-open').css('display', 'none');
	$('.listado-articles-item-hover-close-btn').css('display', 'flex');
}

function desHabilitarEdicion() {
	$("#js-edicion-capitulos i").removeClass('ion-checkmark-circled');
	$("#js-edicion-capitulos i").addClass('ion-android-create');
	$('.listado-image').css('display', 'none');
	$('.home-article-desc').removeAttr('contenteditable');
	$('#modal-agregar-post-open').css('display', 'flex');

}

$('body')
.on(
		'beforeSubmit',
		'#form-agregar-historia',
		function() {
			var form = $(this);
			var token = $("#js-historia").data('historia');

			if (form.find('.has-error').length) {
				return false;
			}
			var button = document
					.getElementById('modal-agregar-post-guardar');
			var l = Ladda.create(button);
			l.start();

			$
					.ajax({
						url : basePath
								+ 'admin-panel/guardar-historia',
						type : 'post',
						data : new FormData(this),
						dataType : 'json',
						cache : false,
						contentType : false,
						processData : false,
						success : function(response) {
							if (response.hasOwnProperty('status')
									&& response.status == 'success') {

								document.getElementById(
										"form-agregar-historia")
										.reset();

								$(modal).trigger('click');

								$("#js-contenedor-image-cap img")
										.remove();
								$(".modal-admin-form-titulo").html(
										'Dame un título...');

								$(".modal-admin-form-descripcion").html('Agrega la descripción de la historia');
							} else {

								$('#form-agregar-historia')
										.yiiActiveForm(
												'updateMessages',
												response, true);
							}
							l.stop();
						},
						error : function() {
							l.stop();
						},
						statusCode : {
							404 : function() {
								alert("page not found");
							}
						}

					});
			return false;
		});

$(document).ready(function(){

	$('#js-nombre-capitulo').focusout(function() {

		if (($(this).text()).trim() == '') {
			$(this).text('Dame un nombre...');
			$(this).data('new', 'esNuevo');
		} else {
			$("#enthistorias-txt_nombre").val($(this).text());

		}

	});

	$('#js-descripcion-historia').focusout(function() {

		if (($(this).text()).trim() == '') {
			$(this).text('Agrega la descripción de la historia');
			$(this).data('new', 'esNuevo');
		} else {
			$("#enthistorias-txt_descripcion").val($(this).html());

		}

	});
//	$('#modal-agregar-post-open').on('click', function(e){
//		e.preventDefault();
//
//		$('#modal-agregar-post').css('display', 'flex');
//
//	});
});

$(document).on({
	'click' : function(e) {
		$('.inputFileCapitulo').trigger('click');

	}
}, '.js-label-image-cap');

//funciones para el input de imagen
$(document).on({
	'change' : function(e) {
		$("#js-contenedor-image-cap img").remove();
		// guardarImagen($(this), this);
		readURLCap(this, $(this));
	}
}, '.inputFileCapitulo');

/**
 * Pone la imagen para vista previa
 *
 * @param input
 * @param element
 */
function readURLCap(input, element) {

	var file = input.files[0];

	if (!file) {

		return false;
	}

	var imagefile = file.type;

	var filename = element.val();

	if (filename.substring(3, 11) == 'fakepath') {
		filename = filename.substring(12);
	}// remove c:\fake at beginning from localhost chrome
	// var url = base+'usrUsuarios/guardarFotosCompetencia';

	var match = [ "image/jpeg", "image/jpg", 'image/png' ];

	if (!((imagefile == match[0]) || (imagefile == match[1]) || (imagefile == match[2]))) {

		alert('Archivo no valido');

		return false;
	}

	if (input.files && input.files[0]) {
		var reader = new FileReader();

		reader.onload = function(e) {
			$("#js-contenedor-image-cap").addClass(
					"listado-modal-image-item-file");
			$("#js-contenedor-image-cap").append(
					'');

		}

		reader.readAsDataURL(input.files[0]);
	}
}<commit_msg>agregando funcionalidad a header<commit_after>/**
 * Variable auxiliar para conocer el estado de edición de los elementos
 */
var enEdicion = false;

// Metodo para eliminar elemento
$(document).on({
	'paste' : function(e) {

		e.preventDefault();
		var text = '';
		if (e.clipboardData || e.originalEvent.clipboardData) {
			text = (e.originalEvent || e).clipboardData.getData('text/plain');
		} else if (window.clipboardData) {
			text = window.clipboardData.getData('Text');
		}
		if (document.queryCommandSupported('insertText')) {
			document.execCommand('insertText', false, text);
		} else {
			document.execCommand('paste', false, text);
		}
	}
}, '.home-article-desc');

//Revisa lo que hay que borrar
setInterval(function() {
	$('.sinGuardar').each(function(index) {
		var element = $(this);
		if (($(this).text()).trim() == '') {
			$(this).text('Agregar texto');
			$(this).data('new', 'esNuevo');
		} else {
			var token = element.data('token');
			var url = basePath
					+ 'admin-panel/editar-historia?token='
					+ token;

			if (element.data('progress') == 'noProceso') {
				element.data('progress', 'enProceso');
				var valor = element.html();

				$.ajax({
					url : url,
					data : {
						valor : valor,
						token : token
					},
					method : "POST",
					success : function(response) {

						element.data('progress', 'noProceso');
						element.removeClass('sinGuardar');
					}
				});
			} else if (element.data('progress') == 'enProceso') {
				element.addClass('sinGuardar');
			}
		}
	});
}, 1000);

//Metodo para guardar al elemento
$(document).on(
		{
			'focus' : function() {
				var esNuevo = $(this).data('new');
				if (esNuevo == 'esNuevo') {
					$(this).text('');
				}
			},
			'focusout' : function() {
				var element = $(this);
				if (($(this).text()).trim() == '') {
					$(this).text('Agregar texto');
					$(this).data('new', 'esNuevo');
				} else {
					var token = element.data('token');
					var url = basePath
							+ 'admin-panel/editar-historia?token='
							+ token;

					if (element.data('progress') == 'noProceso') {
						element.data('progress', 'enProceso');
						var valor = element.html();

						$.ajax({
							url : url,
							data : {
								valor : valor,
								token : token
							},
							method : "POST",
							success : function(response) {

								element.data('progress', 'noProceso');
							}
						});
					} else if (element.data('progress') == 'enProceso') {
						element.addClass('sinGuardar');
					}
				}
			},
			'DOMSubtreeModified' : function() {
				$(this).data('new', 'noNuevo');
			}

		}, '.home-article-desc');

function cambiarImagen(input, elementjs){
	readURL(elementjs, input);
	guardarImagen(input, elementjs);
}

/**
 * Pone la imagen para vista previa
 *
 * @param input
 * @param element
 */
function readURL(input, element) {

	var file = input.files[0];

	if (!file) {

		return false;
	}

	var imagefile = file.type;

	var filename = element.val();

	if (filename.substring(3, 11) == 'fakepath') {
		filename = filename.substring(12);
	}// remove c:\fake at beginning from localhost chrome
	// var url = base+'usrUsuarios/guardarFotosCompetencia';

	var match = [ "image/jpeg", "image/jpg", 'image/png' ];

	if (!((imagefile == match[0]) || (imagefile == match[1]) || (imagefile == match[2]))) {

		alert('Archivo no valido');

		return false;
	}

	if (input.files && input.files[0]) {
		var reader = new FileReader();

		reader.onload = function(e) {
			$(".image-change-"+element.data('token')).attr('src', e.target.result);
		}

		reader.readAsDataURL(input.files[0]);
	}
}

/**
 * Guarda la imagen en la base de datos
 *
 * @param input
 * @param file
 */
function guardarImagen(input, jav) {

	var token = input.data('token');

	var data = new FormData();
	data.append('fileHistoria', jav.files[0]);
	$.ajax({
		url : basePath + "admin-panel/guardar-imagen-historia?token="
				+ token,
		type : "POST",
		data : data,
		processData : false, // Work around #1
		contentType : false, // Work around #2
		success : function() {

		},
		cache : false,
		error : function() {
			alert("Failed");
		},
		// Work around #3
		xhr : function() {
			var xhr = new window.XMLHttpRequest();
			// Upload progress
			xhr.upload.addEventListener("progress", function(evt) {
				if (evt.lengthComputable) {
					var percentComplete = evt.loaded / evt.total;
					// Do something with upload progress
					console.log('upload' + percentComplete);
				}
			}, false);
			// Download progress
			xhr.addEventListener("progress", function(evt) {
				if (evt.lengthComputable) {
					var percentComplete = evt.loaded / evt.total;
					// Do something with download progress
					console.log('download' + percentComplete);
				}
			}, false);
			return xhr;
		}
	});
}

$(document).ready(function(){
	$("#js-edicion-capitulos").on('click', function(){

		if (!enEdicion) {
			enEdicion = true;
			habilitarEdicion();
		} else {
			enEdicion = false;
			desHabilitarEdicion();
		}

	});
});

function habilitarEdicion() {
	$("#js-edicion-capitulos i").removeClass('ion-android-create');
	$("#js-edicion-capitulos i").addClass('ion-checkmark-circled');
	$('.listado-image').css('display', 'block');
	$('.home-article-desc').attr('contenteditable', 'true');

	$('#modal-agregar-post-open').css('display', 'none');
	$('.listado-articles-item-hover-close-btn').css('display', 'flex');
}

function desHabilitarEdicion() {
	$("#js-edicion-capitulos i").removeClass('ion-checkmark-circled');
	$("#js-edicion-capitulos i").addClass('ion-android-create');
	$('.listado-image').css('display', 'none');
	$('.home-article-desc').removeAttr('contenteditable');
	$('#modal-agregar-post-open').css('display', 'flex');

}

$('body')
.on(
		'beforeSubmit',
		'#form-agregar-historia',
		function() {
			var form = $(this);
			var token = $("#js-historia").data('historia');

			if (form.find('.has-error').length) {
				return false;
			}
			var button = document
					.getElementById('modal-agregar-post-guardar');
			var l = Ladda.create(button);
			l.start();

			$
					.ajax({
						url : basePath
								+ 'admin-panel/guardar-historia',
						type : 'post',
						data : new FormData(this),
						dataType : 'json',
						cache : false,
						contentType : false,
						processData : false,
						success : function(response) {
							if (response.hasOwnProperty('status')
									&& response.status == 'success') {

								window.location.href = basePath+'site/lista-de-capitulos?token='+response.tk;

								document.getElementById(
										"form-agregar-historia")
										.reset();

								$(modal).trigger('click');

								$("#js-contenedor-image-cap img")
										.remove();
								$(".modal-admin-form-titulo").html(
										'Dame un título...');

								$(".modal-admin-form-descripcion").html('Agrega la descripción de la historia');
							} else {

								$('#form-agregar-historia')
										.yiiActiveForm(
												'updateMessages',
												response, true);
							}
							l.stop();
						},
						error : function() {
							l.stop();
						},
						statusCode : {
							404 : function() {
								alert("page not found");
							}
						}

					});
			return false;
		});

$(document).ready(function(){

	$('#js-nombre-capitulo').focusout(function() {

		if (($(this).text()).trim() == '') {
			$(this).text('Dame un nombre...');
			$(this).data('new', 'esNuevo');
		} else {
			$("#enthistorias-txt_nombre").val($(this).text());

		}

	});

	$('#js-descripcion-historia').focusout(function() {

		if (($(this).text()).trim() == '') {
			$(this).text('Agrega la descripción de la historia');
			$(this).data('new', 'esNuevo');
		} else {
			$("#enthistorias-txt_descripcion").val($(this).html());

		}

	});
//	$('#modal-agregar-post-open').on('click', function(e){
//		e.preventDefault();
//
//		$('#modal-agregar-post').css('display', 'flex');
//
//	});
});

$(document).on({
	'click' : function(e) {
		$('.inputFileCapitulo').trigger('click');

	}
}, '.js-label-image-cap');

//funciones para el input de imagen
$(document).on({
	'change' : function(e) {
		$("#js-contenedor-image-cap img").remove();
		// guardarImagen($(this), this);
		readURLCap(this, $(this));
	}
}, '.inputFileCapitulo');

/**
 * Pone la imagen para vista previa
 *
 * @param input
 * @param element
 */
function readURLCap(input, element) {

	var file = input.files[0];

	if (!file) {

		return false;
	}

	var imagefile = file.type;

	var filename = element.val();

	if (filename.substring(3, 11) == 'fakepath') {
		filename = filename.substring(12);
	}// remove c:\fake at beginning from localhost chrome
	// var url = base+'usrUsuarios/guardarFotosCompetencia';

	var match = [ "image/jpeg", "image/jpg", 'image/png' ];

	if (!((imagefile == match[0]) || (imagefile == match[1]) || (imagefile == match[2]))) {

		alert('Archivo no valido');

		return false;
	}

	if (input.files && input.files[0]) {
		var reader = new FileReader();

		reader.onload = function(e) {
			$("#js-contenedor-image-cap").addClass(
					"listado-modal-image-item-file");
			$("#js-contenedor-image-cap").append(
					'');

		}

		reader.readAsDataURL(input.files[0]);
	}
}<|endoftext|>


<commit_before>import EventEmitter from 'events';

import MessengerClient from './MessengerClient';

import Text from './elements/Text';
import Button from './elements/Button';
import Address from './elements/Address';
import Element from './elements/Element';
import Summary from './elements/Summary';
import Adjustment from './elements/Adjustment';
import Image from './attachments/Image';
import Audio from './attachments/Audio';
import Video from './attachments/Video';
import File from './attachments/File';

import ButtonTemplate from './templates/ButtonTemplate';
import GenericTemplate from './templates/GenericTemplate';
import ReceiptTemplate from './templates/ReceiptTemplate';

import { QuickReplies, QuickReply } from './QuickReplies';
import {
  GreetingText,
  GetStartedButton,
  PersistentMenu,
  PersistentMenuItem,
} from './ThreadSettings';

class Messenger extends EventEmitter {
  constructor(opts = {}) {
    super();

    if (!Object.prototype.hasOwnProperty.call(opts, 'pageAccessToken')) {
      throw new Error('PAGE_ACCESS_TOKEN is missing.');
    }

    this.pageAccessToken = opts.pageAccessToken;
    this.client = new MessengerClient(this.pageAccessToken);
    this.lastMessage = {};
  }

  handle(payload) {
    const entries = payload.entry;
    entries.forEach(entry => {
      entry.messaging.forEach(message => {
        if (message.message) {
          this.handleEvent('message', message);
        }
        if (message.delivery) {
          this.handleEvent('delivery', message);
        }
        if (message.read) {
          this.handleEvent('read', message);
        }
        if (message.postback) {
          this.handleEvent('postback', message);
        }
        if (message.account_linking) {
          this.handleEvent('account_linking', message);
        }
        if (message.optin) {
          this.handleEvent('optin', message);
        }
      });
    });
  }

  handleEvent(event, message) {
    this.lastMessage = message;
    this.emit(event, message);
  }

  getUser() {
    return this.client.getUser(this.lastMessage.sender.id);
  }

  send(payload) {
    return this.client.send(payload, this.lastMessage.sender.id);
  }

  senderAction(senderAction) {
    return this.client.senderAction(senderAction, this.lastMessage.sender.id);
  }

  setThreadSetting(payload) {
    return this.client.setThreadSetting(payload);
  }

  subscribeAppToPage() {
    return this.client.subscribeAppToPage();
  }

  deleteGetStarted() {
    return this.client.deleteGetStarted();
  }

  linkAccount(accountLinkingToken) {
    return this.client.linkAccount(accountLinkingToken);
  }

  unlinkAccount(self, psid) {
    return this.client.unlinkAccount(psid);
  }

}

export {
  Messenger,
  Text,
  Button,
  Address,
  Summary,
  Adjustment,
  Element,
  Image,
  Audio,
  Video,
  File,
  ButtonTemplate,
  GenericTemplate,
  ReceiptTemplate,
  QuickReplies,
  QuickReply,
  GreetingText,
  GetStartedButton,
  PersistentMenu,
  PersistentMenuItem,
};
<commit_msg>Allow passing id to send method<commit_after>import EventEmitter from 'events';

import MessengerClient from './MessengerClient';

import Text from './elements/Text';
import Button from './elements/Button';
import Address from './elements/Address';
import Element from './elements/Element';
import Summary from './elements/Summary';
import Adjustment from './elements/Adjustment';
import Image from './attachments/Image';
import Audio from './attachments/Audio';
import Video from './attachments/Video';
import File from './attachments/File';

import ButtonTemplate from './templates/ButtonTemplate';
import GenericTemplate from './templates/GenericTemplate';
import ReceiptTemplate from './templates/ReceiptTemplate';

import { QuickReplies, QuickReply } from './QuickReplies';
import {
  GreetingText,
  GetStartedButton,
  PersistentMenu,
  PersistentMenuItem,
} from './ThreadSettings';

class Messenger extends EventEmitter {
  constructor(opts = {}) {
    super();

    if (!Object.prototype.hasOwnProperty.call(opts, 'pageAccessToken')) {
      throw new Error('PAGE_ACCESS_TOKEN is missing.');
    }

    this.pageAccessToken = opts.pageAccessToken;
    this.client = new MessengerClient(this.pageAccessToken);
    this.lastMessage = {};
  }

  handle(payload) {
    const entries = payload.entry;
    entries.forEach(entry => {
      entry.messaging.forEach(message => {
        if (message.message) {
          this.handleEvent('message', message);
        }
        if (message.delivery) {
          this.handleEvent('delivery', message);
        }
        if (message.read) {
          this.handleEvent('read', message);
        }
        if (message.postback) {
          this.handleEvent('postback', message);
        }
        if (message.account_linking) {
          this.handleEvent('account_linking', message);
        }
        if (message.optin) {
          this.handleEvent('optin', message);
        }
      });
    });
  }

  handleEvent(event, message) {
    this.lastMessage = message;
    this.emit(event, message);
  }

  getUser() {
    return this.client.getUser(this.lastMessage.sender.id);
  }

  send(payload, id = '') {
    let userId = id;
    if (!id) {
      userId = this.lastMessage.sender.id;
    }
    return this.client.send(payload, userId);
  }

  senderAction(senderAction, id = '') {
    let userId = id;
    if (!id) {
      userId = this.lastMessage.sender.id;
    }

    return this.client.senderAction(senderAction, userId);
  }

  setThreadSetting(payload) {
    return this.client.setThreadSetting(payload);
  }

  subscribeAppToPage() {
    return this.client.subscribeAppToPage();
  }

  deleteGetStarted() {
    return this.client.deleteGetStarted();
  }

  linkAccount(accountLinkingToken) {
    return this.client.linkAccount(accountLinkingToken);
  }

  unlinkAccount(self, psid) {
    return this.client.unlinkAccount(psid);
  }

}

export {
  Messenger,
  Text,
  Button,
  Address,
  Summary,
  Adjustment,
  Element,
  Image,
  Audio,
  Video,
  File,
  ButtonTemplate,
  GenericTemplate,
  ReceiptTemplate,
  QuickReplies,
  QuickReply,
  GreetingText,
  GetStartedButton,
  PersistentMenu,
  PersistentMenuItem,
};
<|endoftext|>


<commit_before>require.config({
    paths: {
        'angular':          '//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular',
        'angular-route':    '//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route',
        'auth-angular':     '//cdn.auth0.com/w2/auth0-angular-4.js',
        'angular-jwt':     '//cdn.rawgit.com/auth0/angular-jwt/master/dist/angular-jwt',
        'angular-storage': '//cdn.rawgit.com/auth0/angular-storage/master/dist/angular-storage',
        'auth0':            '//cdn.auth0.com/w2/auth0-6'
    },
    shim: {
        'angular':{ exports:'angular' },
        'angular-route':    { deps:['angular']         },
        'angular-storage':    { deps:['angular']         },
        'angular-jwt':    { deps:['angular']         },
        'auth0-angular':    { deps:['angular']         }
    }
});

define([ './controllers' ], function () {
  // Your app has loaded!
});

<commit_msg>Update Auth0.js<commit_after>require.config({
    paths: {
        'angular':          '//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular',
        'angular-route':    '//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route',
        'auth-angular':     '//cdn.auth0.com/w2/auth0-angular-4.js',
        'angular-jwt':     '//cdn.rawgit.com/auth0/angular-jwt/master/dist/angular-jwt',
        'angular-storage': '//cdn.rawgit.com/auth0/angular-storage/master/dist/angular-storage',
        'auth0':            '//cdn.auth0.com/w2/auth0-6.7.js'
    },
    shim: {
        'angular':{ exports:'angular' },
        'angular-route':    { deps:['angular']         },
        'angular-storage':    { deps:['angular']         },
        'angular-jwt':    { deps:['angular']         },
        'auth0-angular':    { deps:['angular']         }
    }
});

define([ './controllers' ], function () {
  // Your app has loaded!
});

<|endoftext|>


<commit_before>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) 2010 M-Way Solutions GmbH. All rights reserved.
//            (c) 2011 panacoda GmbH. All rights reserved.
// Creator:   Dominik
// Date:      29.10.2010
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

m_require('core/utility/logger.js');

/**
 * @class
 *
 * The observable knows all observers, mainly views, and pushes updates if necessary.
 *
 * @extends M.Object
 */
M.Observable = M.Object.extend(
/** @scope M.Observable.prototype */ {

    /**
     * The type of this object.
     *
     * @type String
     */
    type: 'M.Observable',

    /**
     * List that contains pairs of an observer with an observable. An observer is tightened to one
     * observable, but one observable can have multiple observers.
     *
     * @type Array|Object
     */
    bindingList: null,

    /**
     * Attach an observer to an observable.
     *
     * @param {String} observer The observer.
     * @param {String} observable The observable.
     */
    attach: function(observer, observable) {
        if(!this.bindingList) {
            this.bindingList = [];
        }
        this.bindingList.push({
            observer: observer,
            observable: observable
        });
    },

    /**
     * Detach an observer from an observable.
     *
     * @param {String} observer The observer.
     */
    detach: function(observer) {
        /* grep is a jQuery function that finds
         * elements in an array that satisfy a certain criteria.
         * It works on a copy so we have to assign the "cleaned"
         * array to our bindingList.
         */
        this.bindingList = _.filter(this.bindingList, function(value, index) {
                return value.observable !== observer;
        });
    },

    /**
     * Notify all observers that observe the property behind 'key'.
     *
     * @param {String} key The key of the property that changed.
     */
    notifyObservers: function(key) {
        _.each(this.bindingList, function(entry){
            if((key === entry.observable || (entry.observable.indexOf('.') > 0 && entry.observable.indexOf(key) > -1)) || (key.indexOf('.') > 0 && entry.observable.indexOf(key.substring(0, key.lastIndexOf('.'))))) {
                if(entry.observer.valueBinding && (key === entry.observer.valueBinding.property || key === entry.observer.valueBinding.property.split('.')[0])){
                    entry.observer.valueDidChange();
                }else{
                    entry.observer.contentDidChange();
                }
            }
        });
    }

});<commit_msg>Fix a potential infinite loop when notifying observers<commit_after>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) 2010 M-Way Solutions GmbH. All rights reserved.
//            (c) 2011 panacoda GmbH. All rights reserved.
// Creator:   Dominik
// Date:      29.10.2010
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

m_require('core/utility/logger.js');

/**
 * @class
 *
 * The observable knows all observers, mainly views, and pushes updates if necessary.
 *
 * @extends M.Object
 */
M.Observable = M.Object.extend(
/** @scope M.Observable.prototype */ {

    /**
     * The type of this object.
     *
     * @type String
     */
    type: 'M.Observable',

    /**
     * List that contains pairs of an observer with an observable. An observer is tightened to one
     * observable, but one observable can have multiple observers.
     *
     * @type Array|Object
     */
    bindingList: null,

    /**
     * Attach an observer to an observable.
     *
     * @param {String} observer The observer.
     * @param {String} observable The observable.
     */
    attach: function(observer, observable) {
        if(!this.bindingList) {
            this.bindingList = [];
        }
        this.bindingList.push({
            observer: observer,
            observable: observable
        });
    },

    /**
     * Detach an observer from an observable.
     *
     * @param {String} observer The observer.
     */
    detach: function(observer) {
        /* grep is a jQuery function that finds
         * elements in an array that satisfy a certain criteria.
         * It works on a copy so we have to assign the "cleaned"
         * array to our bindingList.
         */
        this.bindingList = _.filter(this.bindingList, function(value, index) {
                return value.observable !== observer;
        });
    },

    /**
     * Notify all observers that observe the property behind 'key'.
     *
     * @param {String} key The key of the property that changed.
     */
    notifyObservers: function(key) {
        _.each(this.bindingList, function(entry){
            if((key === entry.observable || (entry.observable.indexOf('.') > 0 && entry.observable.indexOf(key) > -1)) || (key.indexOf('.') > 0 && entry.observable.indexOf(key.substring(0, key.lastIndexOf('.'))) >-1)) {
                if(entry.observer.valueBinding && (key === entry.observer.valueBinding.property || key === entry.observer.valueBinding.property.split('.')[0])){
                    entry.observer.valueDidChange();
                }else{
                    entry.observer.contentDidChange();
                }
            }
        });
    }

});<|endoftext|>


<commit_before>var request = require('request'),
	url = require('url'),
	parseXml = require('xml2js').parseString;
	async = require('async');

var uriSource = url.parse('http://www.stolpersteine-berlin.de/st_interface/xml/geo/linked');
//var urlApi = 'http://127.0.0.1:3000/api';
var urlApi = 'https://stolpersteine-optionu.rhcloud.com/api';
var userAgent = 'Stolpersteine/1.0 (http://option-u.com; admin@option-u.com)';

var source = {
	url: uriSource.href,
	name: "Koordinierungsstelle Stolpersteine Berlin"
}

console.log('Loading source data...');
request({ uri:uriSource, headers: {'user-agent' : userAgent } }, function(error, response, body) {
	console.log('Loading source data done');
  if (error) {
    console.log('Error when loading source data');
		return;
  }

	console.log('Parsing source data...');
	parseXml(body, function (err, result) {
		console.log('Parsing source data done');
	  if (error) {
	    console.log('Error when parsing source data');
			return;
	  }

		console.log('Found ' + result.markers.$.cnt + ' stolpersteine in ' + result.markers.marker.length + ' markers');
		var stolpersteine = [];
		source.retrievedAt = 	new Date(response.headers["date"]);
		var markers = result.markers.marker;
		markers = markers.slice(0, 10);	// restrict test data
		async.forEachLimit(markers, 1, function(marker, callback) {
			var location = {
				street : marker.$.adresse,
				city : "Berlin",
				sublocality1 : marker.$.bezirk,
				sublocality2 : marker.$.ortsteil,
				coordinates : {
					longitude: marker.$.lng,
					latitude: marker.$.lat
				}
			};

			var stolperstein = {};
			stolperstein.location = location;
			stolperstein.source = source;
			console.log(stolperstein);
			callback();
		});
	});
});

function convertStolperstein($, tableRow, callback) {
	var stolperstein = {};
	var itemRows = $(tableRow).find('td');

	// Person
	var nameSpan = $(itemRows[1]).find('span');
	if (nameSpan.find('span').length) {
		nameSpan = nameSpan.find('span');
	}
	var names = nameSpan.text().split(',');
	stolperstein.person = {
		lastName: names[0].trim(),
		firstName: names[1].trim()
	};
	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (converting...)');

	// Image
	var imageTag = $(itemRows[0]).find('img');
	stolperstein.imageUrl = uriSource.protocol + imageTag.attr('src');
	stolperstein.imageUrl = stolperstein.imageUrl.replace('/100px-', '/1024px-'); // width

	// Location
	stolperstein.location = {
		street: $(itemRows[2]).text().trim(),
		city: "Berlin"
	};

	// Laid at date
	stolperstein.laidAt = {};
	var laidAtSpan = $(itemRows[3]).find('span');
	if ($(laidAtSpan).find('span').length) {
		laidAtSpan = laidAtSpan.find('span');
	}
	var laidAtDates = laidAtSpan.text().split('-');
	if (laidAtDates[0]) {
		var number = new Number(laidAtDates[0]);
		if (number != 0) {
			stolperstein.laidAt.year = number;
		}
	}
	if (laidAtDates[1]) {
		var number = new Number(laidAtDates[1]);
		if (number != 0) {
			stolperstein.laidAt.month = number;
		}
	}
	if (laidAtDates[2]) {
		var number = new Number(laidAtDates[2]);
		if (number != 0) {
			stolperstein.laidAt.date = number;
		}
	}

	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (converting done)');
	callback(null, stolperstein);
}

function patchStolperstein(stolperstein, callback) {
	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (patching...)');

	stolperstein.location.street = stolperstein.location.street.replace("(heute Eingang U-Bahnhof Turmstraße)", "");
	stolperstein.location.street = stolperstein.location.street.replace("Spenerstraße Ecke Melanchtonstraße", "Spenerstr. 14");
	stolperstein.location.street = stolperstein.location.street.replace("Bundesratufer 1", "Bundesratufer 2");

	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (patching done)');
	callback(null, stolperstein);
}

function addSourceToStolperstein(source, stolperstein, callback) {
	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (adding source...)');

	stolperstein.source = source;

	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (adding source done)');
	callback(null, stolperstein);
}<commit_msg>Finished converting stolpersteine<commit_after>var request = require('request'),
	url = require('url'),
	parseXml = require('xml2js').parseString;
	async = require('async');

var uriSource = url.parse('http://www.stolpersteine-berlin.de/st_interface/xml/geo/linked');
//var urlApi = 'http://127.0.0.1:3000/api';
var urlApi = 'https://stolpersteine-optionu.rhcloud.com/api';
var userAgent = 'Stolpersteine/1.0 (http://option-u.com; admin@option-u.com)';

var source = {
	url: uriSource.href,
	name: "Koordinierungsstelle Stolpersteine Berlin"
}

// Request data
console.log('Loading source data...');
request({ uri:uriSource, headers: {'user-agent' : userAgent } }, function(error, response, body) {
	console.log('Loading source data done');
  if (error) {
    console.log('Error when loading source data');
		return;
  }

	// Parse XML
	console.log('Parsing source data...');
	parseXml(body, function (err, result) {
		console.log('Parsing source data done');
	  if (error) {
	    console.log('Error when parsing source data');
			return;
	  }

		// Process marker tags
		console.log('Found ' + result.markers.$.cnt + ' stolpersteine in ' + result.markers.marker.length + ' markers');
		var stolpersteine = [];
		source.retrievedAt = 	new Date(response.headers["date"]);
		var markers = result.markers.marker;
//		markers = markers.slice(250, 260); // restrict test data
		for (var j = 0; j < markers.length; j++) {
			var marker = markers[j];

			var location = {
				street : marker.$.adresse,
				city : "Berlin",
				sublocality1 : marker.$.bezirk,
				sublocality2 : marker.$.ortsteil,
				coordinates : {
					longitude: marker.$.lng,
					latitude: marker.$.lat
				}
			};

			// Convert person tags
			for (var i = 0; i < marker.person.length; i++) {
				var person = marker.person[i];
				console.log('- ' + person.$.name + ' (converting...)');
				var stolperstein = convertStolperstein(person, location, source);
				stolpersteine.push(stolperstein);
				console.log('- ' + person.$.name + ' (converting done)');
			}

			// Convert person tags nested in 'weitere'
			if (marker.weitere) {
				console.log('Processing "weitere"');
				for (var i = 0; i < marker.weitere.length; i++) {
					location.street = marker.weitere[i].$.adresse;

					for (var k = 0; k < marker.weitere[i].person.length; k++) {
						var person = marker.weitere[i].person[k];
						console.log('- ' + person.$.name + ' (converting...)');
						var stolperstein = convertStolperstein(person, location, source);
						stolpersteine.push(stolperstein);
						console.log('- ' + person.$.name + ' (converting done)');
					}
				}
			}
		};
		console.log('Converted ' + stolpersteine.length + ' stolperstein(e)');
	});
});

function convertStolperstein(person, location, source) {
	return stolperstein = {
		person : {
			firstName : person.name,
			lastName : ''
		},
		location : location,
		source : source
	};
}

function patchStolperstein(stolperstein, callback) {
	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (patching...)');

	stolperstein.location.street = stolperstein.location.street.replace("(heute Eingang U-Bahnhof Turmstraße)", "");
	stolperstein.location.street = stolperstein.location.street.replace("Spenerstraße Ecke Melanchtonstraße", "Spenerstr. 14");
	stolperstein.location.street = stolperstein.location.street.replace("Bundesratufer 1", "Bundesratufer 2");

	console.log('- ' + stolperstein.person.lastName + ', ' + stolperstein.person.firstName + ' (patching done)');
	callback(null, stolperstein);
}<|endoftext|>


<commit_before>var u = require('./Utils');
var a = require('async');

//HTTP
var HeadRequest = require('./core/HeadRequestAsyncTask');
var DataRequest = require('./core/DataRequestTask');

//FILE
var FileHandler = require('./core/FileHandlerAsyncTask');
var Truncator = require('./core/TruncateAsyncTask');
var FileNameGenerator = require('./core/FileNameGeneratorSync');
var Renamer = require('./core/RenameAsyncTask');

//Threads
var ThreadsGenerator = require('./core/ThreadsGeneratorSyncTask');

//META DATA
var MetaDataBuilder = require('./core/MetaDataBuilderSyncTask');

//READ WRITE
var DownloadWriter = require('./core/DownloadWriterAsyncTask');
var DownloadReader = require('./core/DownloadReaderAsyncTask');

//EXECUTOR
var ExecutorGenerator = require('./core/ExecutorGenerator');

//INDICATOR
var StartIndicator = require('./core/StartIndicator');

//VALIDATOR
var DownloadValidator = require('./core/DownloadValidator');

var Setup_New_Download = function(cParams) {
	this.cParams = cParams;
};

Setup_New_Download.prototype.execute = function(callback) {
	var cParams = this.cParams;
	cParams.headUrl = cParams.headUrl || cParams.url;

	this.tasks = {

		//HTTP
		'http-head': ['file-handle', function(callback, results) {
			u.executor(HeadRequest, cParams.head_url, cParams)(callback);
		}],

		//THREADS
		'threads-generate': ['http-head',

		function(callback, results) {
			u.executor(ThreadsGenerator,
			results['http-head'].fileSize,
			cParams)(callback);
		}],

		//FILE
		'file-name': a.apply(u.executor(FileNameGenerator,
		cParams.file)),

		'file-handle': ['file-name',

		function(callback, results) {
			u.executor(FileHandler,
			results['file-name'].downloadFile, true)(callback);
		}],

		'file-truncate': ['validate-download',

		function(callback, results) {
			u.executor(Truncator,
			results['file-handle'],
			results['meta-read'].downloadSize)(callback);
		}],

		'file-rename': ['file-truncate',

		function(callback, results) {
			u.executor(Renamer,
			results['file-name'].downloadFile,
			results['file-name'].originalFile)(callback);
		}],

		//META(UPDATE AND WRITE TIMELY)
		'meta-generate': ['threads-generate',

		function(callback, results) {
			u.executor(MetaDataBuilder,
			results['threads-generate'],
			results['http-head'].fileSize,
			cParams.url,
			cParams.method,
			cParams.port,
			results['http-head'].headers,
			cParams)(callback);
		}],

		'meta-write': ['meta-generate', 'file-handle',

		function(callback, results) {
			u.executor(DownloadWriter,
			results['file-handle'])(results['meta-generate'].data,
			results['meta-generate'].position,
			callback);
		}],
		'meta-read': ['meta-write',

		function(callback, results) {

			u.executor(DownloadReader,
			results['file-handle'],
			cParams)(callback);
		}],

		//INDICATOR
		'start-indicator': ['meta-read', function(callback, results) {
			u.executor(StartIndicator,
			results['meta-read'].threads,
			results['meta-read'].downloadSize,
			results['meta-read'].url,
			results['meta-read'].headers,
			cParams)(callback);
		}],
		//EXECUTOR GENERATOR
		'executor-generator': ['meta-read', function(callback, results) {
			u.executor(ExecutorGenerator,
			results['file-handle'],
			results['meta-read'].threads,
			results['meta-read'].downloadSize,
			results['meta-read'].url,
			results['meta-read'].method,
			results['meta-read'].port,
			results['meta-read'].headers,
			cParams)(callback);
		}],

		//VALIDATE DOWNLOAD
		'validate-download': ['http-data',

		function(callback, results) {
			u.executor(DownloadValidator, results['meta-read'].threads)(callback);
		}],

		//DATA
		'http-data': ['executor-generator',

		function(callback, results) {
			u.executor(DataRequest,
			results['executor-generator'].writer,
			results['executor-generator'].threads,
			results['executor-generator'].metaBuilder,
			results['executor-generator'].timer,
			results['executor-generator'].threadUpdator,
			results['executor-generator'].threadsDestroyer,
			results['meta-read'].downloadSize,
			cParams)(callback);
		}]
	};
	callback(this.tasks);
};

module.exports = Setup_New_Download;
<commit_msg>copy error<commit_after>var u = require('./Utils');
var a = require('async');

//HTTP
var HeadRequest = require('./core/HeadRequestAsyncTask');
var DataRequest = require('./core/DataRequestTask');

//FILE
var FileHandler = require('./core/FileHandlerAsyncTask');
var Truncator = require('./core/TruncateAsyncTask');
var FileNameGenerator = require('./core/FileNameGeneratorSync');
var Renamer = require('./core/RenameAsyncTask');

//Threads
var ThreadsGenerator = require('./core/ThreadsGeneratorSyncTask');

//META DATA
var MetaDataBuilder = require('./core/MetaDataBuilderSyncTask');

//READ WRITE
var DownloadWriter = require('./core/DownloadWriterAsyncTask');
var DownloadReader = require('./core/DownloadReaderAsyncTask');

//EXECUTOR
var ExecutorGenerator = require('./core/ExecutorGenerator');

//INDICATOR
var StartIndicator = require('./core/StartIndicator');

//VALIDATOR
var DownloadValidator = require('./core/DownloadValidator');

var Setup_New_Download = function(cParams) {
	this.cParams = cParams;
};

Setup_New_Download.prototype.execute = function(callback) {
	var cParams = this.cParams;
	cParams.headUrl = cParams.headUrl || cParams.url;

	this.tasks = {

		//HTTP
		'http-head': ['file-handle', function(callback, results) {
			u.executor(HeadRequest, cParams.headUrl, cParams)(callback);
		}],

		//THREADS
		'threads-generate': ['http-head',

		function(callback, results) {
			u.executor(ThreadsGenerator,
			results['http-head'].fileSize,
			cParams)(callback);
		}],

		//FILE
		'file-name': a.apply(u.executor(FileNameGenerator,
		cParams.file)),

		'file-handle': ['file-name',

		function(callback, results) {
			u.executor(FileHandler,
			results['file-name'].downloadFile, true)(callback);
		}],

		'file-truncate': ['validate-download',

		function(callback, results) {
			u.executor(Truncator,
			results['file-handle'],
			results['meta-read'].downloadSize)(callback);
		}],

		'file-rename': ['file-truncate',

		function(callback, results) {
			u.executor(Renamer,
			results['file-name'].downloadFile,
			results['file-name'].originalFile)(callback);
		}],

		//META(UPDATE AND WRITE TIMELY)
		'meta-generate': ['threads-generate',

		function(callback, results) {
			u.executor(MetaDataBuilder,
			results['threads-generate'],
			results['http-head'].fileSize,
			cParams.url,
			cParams.method,
			cParams.port,
			results['http-head'].headers,
			cParams)(callback);
		}],

		'meta-write': ['meta-generate', 'file-handle',

		function(callback, results) {
			u.executor(DownloadWriter,
			results['file-handle'])(results['meta-generate'].data,
			results['meta-generate'].position,
			callback);
		}],
		'meta-read': ['meta-write',

		function(callback, results) {

			u.executor(DownloadReader,
			results['file-handle'],
			cParams)(callback);
		}],

		//INDICATOR
		'start-indicator': ['meta-read', function(callback, results) {
			u.executor(StartIndicator,
			results['meta-read'].threads,
			results['meta-read'].downloadSize,
			results['meta-read'].url,
			results['meta-read'].headers,
			cParams)(callback);
		}],
		//EXECUTOR GENERATOR
		'executor-generator': ['meta-read', function(callback, results) {
			u.executor(ExecutorGenerator,
			results['file-handle'],
			results['meta-read'].threads,
			results['meta-read'].downloadSize,
			results['meta-read'].url,
			results['meta-read'].method,
			results['meta-read'].port,
			results['meta-read'].headers,
			cParams)(callback);
		}],

		//VALIDATE DOWNLOAD
		'validate-download': ['http-data',

		function(callback, results) {
			u.executor(DownloadValidator, results['meta-read'].threads)(callback);
		}],

		//DATA
		'http-data': ['executor-generator',

		function(callback, results) {
			u.executor(DataRequest,
			results['executor-generator'].writer,
			results['executor-generator'].threads,
			results['executor-generator'].metaBuilder,
			results['executor-generator'].timer,
			results['executor-generator'].threadUpdator,
			results['executor-generator'].threadsDestroyer,
			results['meta-read'].downloadSize,
			cParams)(callback);
		}]
	};
	callback(this.tasks);
};

module.exports = Setup_New_Download;
<|endoftext|>