<commit_before>'use strict';

/**
 * Module dependencies.
 */
const config = require('../config'),
    chalk = require('chalk'),
    path = require('path'),
    mongoose = require('mongoose');
const Pagination = require('./Pagination');

let baseFieldPlugin = function (schema, options) {
    schema.set('toJSON', {virtuals: true});
    schema.add({
        updated: {
            type: Date,
            default: Date.now
        },
        updateId: String,
        created: {
            type: Date,
            default: Date.now
        },
        creator: {
            type: String
        }
    });
    schema.pre('update', function (next) {
        this.updated = Date.now;
        next();
    });
};

let paginationPlugin = function (schema, options) {

    schema.statics.findPagination = function (query, sort, pageSize,
                                              pageNum) {
        let self = this;
        return new Promise(function (resolve, reject) {
            self.count({}, function (err, totalCount) {
                if (err) {
                    throw err;
                }
                let pagination = new Pagination(pageSize, pageNum,
                    totalCount);
                self.find(query).sort(sort).skip(pageSize * pageNum).limit(
                    pageSize).exec(
                    function (err, array) {
                        if (err) {
                            throw err;
                        } else {
                            pagination.data = array;
                            resolve(pagination);
                        }
                    });
            });
        });
    };
};

// Load the mongoose models
module.exports.loadModels = function (callback) {
    mongoose.plugin(baseFieldPlugin);
    mongoose.plugin(paginationPlugin);
    // Globbing model files
    config.files.server.models.forEach(function (modelPath) {
        require(path.resolve(modelPath));
    });

    if (callback) callback();
};

// Initialize Mongoose
module.exports.connect = function (cb) {
    var _this = this;

    var db = mongoose.connect(config.db.uri, config.db.options, function (err) {
        // Log Error
        if (err) {
            console.error(chalk.red('Could not connect to MongoDB!'));
            console.log(err);
        } else {

            // Enabling mongoose debug mode if required
            mongoose.set('debug', config.db.debug);

            // Call callback FN
            if (cb) cb(db);
        }
    });
};

module.exports.disconnect = function (cb) {
    mongoose.disconnect(function (err) {
        console.info(chalk.yellow('Disconnected from MongoDB.'));
        cb(err);
    });
};
<commit_msg>fix an error totalCount bug  ...<commit_after>'use strict';

/**
 * Module dependencies.
 */
const config = require('../config'),
    chalk = require('chalk'),
    path = require('path'),
    mongoose = require('mongoose');
const Pagination = require('./Pagination');
const logger = require(path.resolve('./config/lib/logger'));

// Load the mongoose models
module.exports.loadModels = loadModels;
// Initialize Mongoose
module.exports.connect = connect;

module.exports.disconnect = disconnect;

function connect(cb) {
    var _this = this;

    var db = mongoose.connect(config.db.uri, config.db.options, function (err) {
        // Log Error
        if (err) {
            logger.error(chalk.red('Could not connect to MongoDB!'));
            logger.error(err);
        } else {

            // Enabling mongoose debug mode if required
            mongoose.set('debug', config.db.debug);

            // Call callback FN
            if (cb) cb(db);
        }
    });
}

function disconnect(cb) {
    mongoose.disconnect(function (err) {
        logger.info(chalk.yellow('Disconnected from MongoDB.'));
        cb(err);
    });
}

function loadModels(callback) {
    mongoose.plugin(baseFieldPlugin);
    mongoose.plugin(paginationPlugin);
    // Globbing model files
    config.files.server.models.forEach(function (modelPath) {
        require(path.resolve(modelPath));
    });

    if (callback) callback();
}

function baseFieldPlugin(schema) {
    schema.set('toJSON', {virtuals: true});
    schema.add({
        updated: {
            type: Date,
            default: Date.now
        },
        updateId: String,
        created: {
            type: Date,
            default: Date.now
        },
        creator: {
            type: String
        }
    });
    schema.pre('update', function (next) {
        this.updated = Date.now;
        next();
    });
}

function paginationPlugin(schema) {

    schema.statics.findPagination = function (query, sort, pageSize,
                                              pageNum) {
        let self = this;
        return new Promise(function (resolve, reject) {
            self.count(query, function (err, totalCount) {
                if (err) {
                    throw err;
                }
                let pagination = new Pagination(pageSize, pageNum,
                    totalCount);
                self.find(query).sort(sort).skip(pageSize * pageNum).limit(
                    pageSize).exec(
                    function (err, array) {
                        if (err) {
                            throw err;
                        } else {
                            pagination.data = array;
                            resolve(pagination);
                        }
                    });
            });
        });
    };
}
<|endoftext|>


<commit_before>/**
 * Created by adil on 17. 2. 18.
 */

"use strict";
/*jshint esversion: 6*/

/**
 * Control for High Constant (1).
 */
//TODO: Remove the direct dependency from raphael.
class HighConstant extends BaseControl {
    /**
     * Constructor for HighConstant
     * @param paper raphael paper object.
     */
    constructor(paper) {
        super(paper);
    }

    initControl() {
        super.initControl();

        let componentBody = this.paper.path("m 2.9332995,3.4333413 0,159.6333587 122.9864205,0 0,-159.6333587 -122.9864205,0 z M 126.77747,83.250031 l 49.87061,0 -49.87061,0 z");
        let componentText = this.paper.path("m 30.266032,119.60624 c 8.501315,0 17.00263,0 25.503945,0 0,-24.12873 0,-48.25747 0,-72.3862 -8.72635,1.80028 -17.452699,3.60055 -26.179049,5.40083 0,-6.55101 0,-13.10203 0,-19.65304 8.770589,-1.78124 17.52568,-3.71345 26.305903,-5.40083 9.059123,0 18.118247,0 27.17737,0 0,30.67975 0,61.35949 0,92.03924 8.501315,0 17.002629,0 25.503949,0 0,6.651 0,13.3021 0,19.9531 -26.104042,0 -52.20808,0 -78.312118,0 0,-6.651 0,-13.3021 0,-19.9531 z");
        var componentPin3 = new ConnectionPin(this, 186, 83, "out");

        this.setShapes([componentBody, componentText]);
        this.addOutputPins(componentPin3);
    }

    getValue() {
        return 1;
    }
}
<commit_msg>[HighConstang] SVG path values are integers now<commit_after>/**
 * Created by adil on 17. 2. 18.
 */

"use strict";
/*jshint esversion: 6*/

/**
 * Control for High Constant (1).
 */
//TODO: Remove the direct dependency from raphael.
class HighConstant extends BaseControl {
    /**
     * Constructor for HighConstant
     * @param paper raphael paper object.
     */
    constructor(paper) {
        super(paper);
    }

    initControl() {
        super.initControl();

        let componentBody = this.paper.path("m 2,3 0,159 122,0 0,-159 -122,0 z M 126,83 l 49,0 -49,0 z");
        let componentText = this.paper.path("m 30,119 c 8,0 17,0 25,0 0,-24 0,-48 0,-72 -8,1 -17,3 -26,5 0,-6 0,-13 0,-19 8,-1 17,-3 26,-5 9,0 18,0 27,0 0,30 0,61 0,92 8,0 17,0 25,0 0,6 0,13 0,19 -26,0 -52,0 -78,0 0,-6 0,-13 0,-19 z");
        var componentPin3 = new ConnectionPin(this, 186, 83, "out");

        this.setShapes([componentBody, componentText]);
        this.addOutputPins(componentPin3);
    }

    getValue() {
        return 1;
    }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
const config = require('../config'),
    chalk = require('chalk'),
    path = require('path'),
    mongoose = require('mongoose');
const Pagination = require('./Pagination');
const logger = require(path.resolve('./config/lib/logger'));

// Load the mongoose models
module.exports.loadModels = loadModels;
// Initialize Mongoose
module.exports.connect = connect;

module.exports.disconnect = disconnect;

function connect(cb) {
    var _this = this;

    var db = mongoose.connect(config.db.uri, config.db.options, function (err) {
        // Log Error
        if (err) {
            logger.error(chalk.red('Could not connect to MongoDB!'));
            logger.error(err);
        } else {

            // Enabling mongoose debug mode if required
            mongoose.set('debug', config.db.debug);

            // Call callback FN
            if (cb) cb(db);
        }
    });
}

function disconnect(cb) {
    mongoose.disconnect(function (err) {
        logger.info(chalk.yellow('Disconnected from MongoDB.'));
        cb(err);
    });
}

function loadModels(callback) {
    mongoose.plugin(baseFieldPlugin);
    mongoose.plugin(paginationPlugin);
    // Globbing model files
    config.files.server.models.forEach(function (modelPath) {
        require(path.resolve(modelPath));
    });

    if (callback) callback();
}

function baseFieldPlugin(schema) {
    schema.set('toJSON', {virtuals: true});
    schema.add({
        updated: {
            type: Number,
            default: Date.now
        },
        updateId: String,
        created: {
            type: Number,
            default: Date.now
        },
        creator: {
            type: String
        }
    });
    schema.pre('update', function (next) {
        this.updated = Date.now;
        next();
    });
}

function paginationPlugin(schema) {

    schema.statics.findPagination = function (query, sort, pageSize,
                                              pageNum) {
        let self = this;
        return new Promise(function (resolve, reject) {
            self.count(query, function (err, totalCount) {
                if (err) {
                    throw err;
                }
                let pagination = new Pagination(pageSize, pageNum,
                    totalCount);
                self.find(query).sort(sort).skip(pageSize * pageNum).limit(
                    pageSize).exec(
                    function (err, array) {
                        if (err) {
                            throw err;
                        } else {
                            pagination.data = array;
                            resolve(pagination);
                        }
                    });
            });
        });
    };
}
<commit_msg>remove dependency of webstomp-client<commit_after>'use strict';

/**
 * Module dependencies.
 */
const config = require('../config'),
    chalk = require('chalk'),
    path = require('path'),
    mongoose = require('mongoose');
const Pagination = require('./Pagination');
const logger = require(path.resolve('./config/lib/logger'));

// Load the mongoose models
module.exports.loadModels = loadModels;
// Initialize Mongoose
module.exports.connect = connect;

module.exports.disconnect = disconnect;

function connect(cb) {
    var _this = this;

    var db = mongoose.connect(config.db.uri, config.db.options, function (err) {
        // Log Error
        if (err) {
            logger.error(chalk.red('Could not connect to MongoDB!'));
            logger.error(err);
        } else {

            // Enabling mongoose debug mode if required
            mongoose.set('debug', config.db.debug);

            // Call callback FN
            if (cb) cb(db);
        }
    });
}

function disconnect(cb) {
    mongoose.disconnect(function (err) {
        logger.info(chalk.yellow('Disconnected from MongoDB.'));
        cb(err);
    });
}

function loadModels(callback) {
    mongoose.plugin(baseFieldPlugin);
    mongoose.plugin(paginationPlugin);
    // Globbing model files
    config.files.server.models.forEach(function (modelPath) {
        require(path.resolve(modelPath));
    });

    if (callback) callback();
}

function baseFieldPlugin(schema) {
    schema.set('toJSON', {virtuals: true});
    schema.add({
        updated: {
            type: Number,
            default: Date.now
        },
        updateId: String,
        created: {
            type: Number,
            default: Date.now
        },
        creator: {
            type: String
        }
    });
    schema.pre('update', function (next) {
        this.updated = Date.now;
        next();
    });
}

function paginationPlugin(schema) {

    schema.statics.findPagination = function (query, sort, pageSize, pageNum) {
        let self = this;
        return new Promise(function (resolve) {
            self.count(query, function (err, totalCount) {
                if (err) {
                    throw err;
                }
                let pagination = new Pagination(pageSize, pageNum,
                    totalCount);
                self.find(query).sort(sort).skip(pageSize * pageNum).limit(
                    pageSize).exec(
                    function (err, array) {
                        if (err) {
                            throw err;
                        } else {
                            pagination.data = array;
                            resolve(pagination);
                        }
                    });
            });
        });
    };
}
<|endoftext|>


<commit_before>
(function($) {

  Drupal.CultureFeed = Drupal.CultureFeed || {};
  Drupal.CultureFeed.Calendar = {};
  Drupal.CultureFeed.Calendar.cookieJson = null;

  $(document).ready(function() {

    if ($.cookie('Drupal.visitor.calendar') !== null) {
      Drupal.CultureFeed.Calendar.cookieJson = jQuery.parseJSON($.cookie('Drupal.visitor.calendar'));
    }

    Drupal.CultureFeed.Calendar.initButtons();
    Drupal.CultureFeed.Calendar.showTotalAdded();
  });

  /**
   * Init the calendar buttons.
   */
  Drupal.CultureFeed.Calendar.initButtons = function () {

    if (Drupal.CultureFeed.Calendar.cookieJson !== null) {

      // Loop through the cookie event objects and store the nodeId's in an array.
      var ids = [];
      $.each(Drupal.CultureFeed.Calendar.cookieJson, function(index, value) {
        ids.push(value["nodeId"]);
      });

        // Show the correct buttons.
        $('.calendar-button').each(function() {

          var $this = $(this);
          var eventid = $this.data('eventid');
          // When item is added, only show btn-view-calendar.
          if ($.inArray(eventid, ids) !== -1) {
            if ($this.hasClass('btn-view-calendar')) {
              $this.show();
            }
          }
          else {
            if (!$this.hasClass('btn-view-calendar')) {
              $this.show();
            }
          }

      })

    }
    else {
      // No cookie => show all add to calendars.
      $(".btn-add-calendar").show();
    }
  }

  /**
   * Show how many activites are currently stored in the cookie.
   */
  Drupal.CultureFeed.Calendar.showTotalAdded = function() {

    var $calendarItem = $('#block-culturefeed-ui-profile-box').find('li.activities');
    $calendarItem.hide();

    // Get cookie calendar information.
    if (Drupal.CultureFeed.Calendar.cookieJson !== null) {

      // Count the cookie event objects.
      var total = 0;
      $.each(Drupal.CultureFeed.Calendar.cookieJson, function(index, value) {
        total++;
      });

      // set the label and value if needed.
      if (total > 0) {
        $("span.unread-activities").text(total);
        $calendarItem.show();
      }
    }
  }

})(jQuery);<commit_msg>UIV-1086 make calendar count selector less specific<commit_after>
(function($) {

  Drupal.CultureFeed = Drupal.CultureFeed || {};
  Drupal.CultureFeed.Calendar = {};
  Drupal.CultureFeed.Calendar.cookieJson = null;

  $(document).ready(function() {

    if ($.cookie('Drupal.visitor.calendar') !== null) {
      Drupal.CultureFeed.Calendar.cookieJson = jQuery.parseJSON($.cookie('Drupal.visitor.calendar'));
    }

    Drupal.CultureFeed.Calendar.initButtons();
    Drupal.CultureFeed.Calendar.showTotalAdded();
  });

  /**
   * Init the calendar buttons.
   */
  Drupal.CultureFeed.Calendar.initButtons = function () {

    if (Drupal.CultureFeed.Calendar.cookieJson !== null) {

      // Loop through the cookie event objects and store the nodeId's in an array.
      var ids = [];
      $.each(Drupal.CultureFeed.Calendar.cookieJson, function(index, value) {
        ids.push(value["nodeId"]);
      });

        // Show the correct buttons.
        $('.calendar-button').each(function() {

          var $this = $(this);
          var eventid = $this.data('eventid');
          // When item is added, only show btn-view-calendar.
          if ($.inArray(eventid, ids) !== -1) {
            if ($this.hasClass('btn-view-calendar')) {
              $this.show();
            }
          }
          else {
            if (!$this.hasClass('btn-view-calendar')) {
              $this.show();
            }
          }

      })

    }
    else {
      // No cookie => show all add to calendars.
      $(".btn-add-calendar").show();
    }
  }

  /**
   * Show how many activites are currently stored in the cookie.
   */
  Drupal.CultureFeed.Calendar.showTotalAdded = function() {

    var $calendarItem = $('#block-culturefeed-ui-profile-box').find('.activities');
    $calendarItem.hide();

    // Get cookie calendar information.
    if (Drupal.CultureFeed.Calendar.cookieJson !== null) {

      // Count the cookie event objects.
      var total = 0;
      $.each(Drupal.CultureFeed.Calendar.cookieJson, function(index, value) {
        total++;
      });

      // set the label and value if needed.
      if (total > 0) {
        $("span.unread-activities").text(total);
        $calendarItem.show();
      }
    }
  }

})(jQuery);<|endoftext|>


<commit_before>import Ember from 'ember';
import NotifierMixin from '../../../mixins/notifier';

export default Ember.Controller.extend(NotifierMixin, {
	documentService: Ember.inject.service('document'),

	actions: {
		onCancel() {
			this.transitionToRoute('document');
		},

		onAddSection(section) {
			this.audit.record("added-section");
			this.audit.record("added-section-" + section.get('contentType'));

			let page = {
				documentId: this.get('model.document.id'),
				title: `${section.get('contentType')} Section`,
				level: 1,
				sequence: 2048,
				body: "",
				contentType: section.get('contentType')
			};

			let data = this.get('store').normalize('page', page);
			let pageData = this.get('store').push(data);

			let meta = {
				documentId: this.get('model.document.id'),
				rawBody: "",
				config: ""
			};

			let pageMeta = this.get('store').normalize('page-meta', meta);
			let pageMetaData = this.get('store').push(pageMeta);

			let model = {
				page: pageData,
				meta: pageMetaData
			};

			this.get('documentService').addPage(this.get('model.document.id'), model).then((newPage) => {
				this.transitionToRoute('document.edit',
					this.get('model.folder.id'),
					this.get('model.folder.slug'),
					this.get('model.document.id'),
					this.get('model.document.slug'),
					newPage.id);
			});
		}
	}
});
<commit_msg>Section title fix<commit_after>import Ember from 'ember';
import NotifierMixin from '../../../mixins/notifier';

export default Ember.Controller.extend(NotifierMixin, {
	documentService: Ember.inject.service('document'),

	actions: {
		onCancel() {
			this.transitionToRoute('document');
		},

		onAddSection(section) {
			this.audit.record("added-section");
			this.audit.record("added-section-" + section.get('contentType'));

			let page = {
				documentId: this.get('model.document.id'),
				title: `${section.get('title')} Section`,
				level: 1,
				sequence: 2048,
				body: "",
				contentType: section.get('contentType')
			};

			let data = this.get('store').normalize('page', page);
			let pageData = this.get('store').push(data);

			let meta = {
				documentId: this.get('model.document.id'),
				rawBody: "",
				config: ""
			};

			let pageMeta = this.get('store').normalize('page-meta', meta);
			let pageMetaData = this.get('store').push(pageMeta);

			let model = {
				page: pageData,
				meta: pageMetaData
			};

			this.get('documentService').addPage(this.get('model.document.id'), model).then((newPage) => {
				this.transitionToRoute('document.edit',
					this.get('model.folder.id'),
					this.get('model.folder.slug'),
					this.get('model.document.id'),
					this.get('model.document.slug'),
					newPage.id);
			});
		}
	}
});
<|endoftext|>


<commit_before>/**
 * Configuration for watch task(s)
 */
'use strict';

var _ = require('lodash');

var taskConfig = function(grunt) {

    // Configuration
    var config = {
        configFiles: {
            files: [
                'Gruntfile.js',
                'grunt/**/*.js',
                '*.json'
            ],
            options: {
                reload: true,
                interrupt: true
            },
            tasks: [
                'serve:nowatch'
            ]
        },<% if (htmlOption === 'jade' && !useServer) { %>
        jade: {
            files: [
                '<%%= yeogurt.client %>/templates/*.jade'
            ],
            tasks: [
                'newer:jade:server'
            ]
        },
        jadePartials: {
            files: [
                '<%%= yeogurt.client %>/templates/**/*.jade',
                '!<%%= yeogurt.client %>/templates/*.jade'
            ],
            tasks: [
                'injector:jade',
                'jade:server'
            ]
        },<% } %><% if (htmlOption === 'swig' && !useServer) { %>
        swig: {
            files: [
                '<%%= yeogurt.client %>/templates/*.swig'
            ],
            tasks: [
                'newer:swig:server'
            ]
        },
        swigPartials: {
            files: [
                '<%%= yeogurt.client %>/templates/**/*.swig',
                '!<%%= yeogurt.client %>/templates/*.swig'
            ],
            tasks: [
                'injector:swig',
                'swig:server'
            ]
        },<% } %><% if (htmlOption === 'html' || jsFramework === 'backbone') { %>
        html: {
            files: [
                '<%%= yeogurt.client %>/templates/**/*.html'
            ],
            tasks: [
                'newer:copy:server',
                'clean:temp'
            ]
        },<% } %><% if (cssOption === 'sass') { %>
        sass: {
            files: ['<%%= yeogurt.client %>/styles/**/*.<% if (useKss) { %>{scss,sass,md}<% } else { %>{scss,sass}<% } %>'],
            tasks: [
                'injector:sass',
                'sass:server'
            ]
        },<% } %><% if (cssOption === 'less') { %>
        less: {
            files: ['<%%= yeogurt.client %>/styles/**/*.<% if (useKss) { %>{less,md}<% } else { %>less<% } %>'],
            tasks: [
                'injector:less',
                'less:server'
            ]
        },<% } %><% if (cssOption === 'stylus') { %>
        stylus: {
            files: ['<%%= yeogurt.client %>/styles/**/*.<% if (useKss) { %>{styl,md}<% } else { %>styl<% } %>'],
            tasks: [
                'injector:stylus',
                'stylus:server'
            ]
        },<% } %>
        injectCss: {
            files: [
                '<%%= yeogurt.client %>/styles/**/*.css'
            ],
            tasks: ['injector:css']
        },<% if (jsOption === 'none') { %>
        injectJs: {
            files: [
                '<%%= yeogurt.client %>/scripts/**/*.js',
                '!<%%= yeogurt.client %>/scripts/app.js'<% if (jsFramework === 'backbone') { %>,
                '!<%%= yeogurt.client %>/scripts/routes.js'<% } %>
            ],
            tasks: ['injector:scripts']
        },<% } %>
        js: {
            files: [
                '<%%= yeogurt.client %>/scripts/**/*.js'<% if (jsFramework === 'react' && !useJsx) { %>,
                '!<%%= yeogurt.client %>/scripts/**/components/*.js'<% } %>
            ],
            tasks: [<% if (jshint) { %>
                'newer:jshint',<% } %><% if (jsOption === 'browserify') { %>
                'browserify:server',
                'exorcise:server',<% } %>
                'newer:copy:server'
            ]
        },<% if (jsFramework === 'react') { %>
        react: {<% if (useJsx) { %>
            files: ['<%%= yeogurt.client %>/scripts/components/**/*.jsx'],<% } else { %>
            files: ['<%%= yeogurt.client %>/scripts/components/**/*.js'],<% } %>
            tasks: [<% if (jsOption === 'requirejs') { %>
                'newer:copy:server',<% } %><% if (jsOption === 'browserify') { %>
                'browserify:server',
                'exorcise:server'<% } %>
            ]
        },<% } %><% if (jsTemplate === 'handlebars') { %>
        handlebars: {
            files: ['<%%= yeogurt.client %>/templates/**/*.hbs'],
            tasks: [
                'handlebars:server'
            ]
        },<% } %><% if (jsTemplate === 'lodash') { %>
        jst: {
            files: ['<%%= yeogurt.client %>/templates/**/*.jst'],
            tasks: [
                'jst:server'
            ]
        },<% } %><% if (jsTemplate === 'jade') { %>
        jade: {
            files: ['<%%= yeogurt.client %>/templates/**/*.jade'],
            tasks: [
                'jade:server'<% if (useServer) { %>,
                'express:server'<% } %>
            ]
        },<% } %>
        images: {
            files: ['<%%= yeogurt.client %>/images/**/*.{png,jpg,gif}'],
            tasks: ['newer:copy:server']
        },
        root: {
            files: [
                '<%%= yeogurt.client %>/*.{ico,png,txt,html}',
                '<%%= yeogurt.client %>/images/**/*.webp',
                '<%%= yeogurt.client %>/styles/fonts/**/*.*'
            ],
            tasks: ['newer:copy:server']
        },
        livereload: {
            options: {
                livereload: <% if (!useServer) { %>'<%%= connect.options.livereload %>'<% } else { %>true<% } %>
            },
            files: [
                '<%%= yeogurt.staticServer %>/*.{ico,png,txt,html}',
                '<%%= yeogurt.staticServer %>/**/*.html',
                '<%%= yeogurt.staticServer %>/styles/**/*.{css,ttf,otf,woff,svg,eot}',
                '<%%= yeogurt.staticServer %>/scripts/**/*.js',<% if (singlePageApplication && jsTemplate !== 'react') { %>
                '<%%= yeogurt.staticServer %>/templates/**/*.{jst,hbs,jade}',<% } %>
                '<%%= yeogurt.staticServer %>/images/**/*.{png,jpg,jpeg,gif,webp,svg}'
            ]
        }<% if (useServer) { %>,
        express: {
            files: [
                'server.js',
                'server/**/*.{js,json,html}'<% if (jsFramework === 'react') { %><% if (useJsx) { %>,
                '<%%= yeogurt.client %>/scripts/components/*.jsx'<% } else { %>,
                '<%%= yeogurt.client %>/scripts/components/*.js'<% } %><% } %><% if (htmlOption === 'swig') { %>,
                '<%%= yeogurt.server %>/templates/**/*.swig'<% } %><% if (htmlOption === 'jade') { %>,
                '<%%= yeogurt.server %>/templates/**/*.jade'<% } %>
            ],
            tasks: [<% if (htmlOption === 'swig') { %>
                'injector:swig',<% } %><% if (htmlOption === 'jade') { %>
                'injector:jade',<% } %>
                'express:server',
                'wait'
            ],
            options: {
                livereload: true,
                nospawn: true //Without this option specified express won't be reloaded
            }
        }<% } %>
    };
    <% if (useKss || useJsdoc || useDashboard) { %>
    // Documentation specific configuration
    var docsConfig = {<% if (htmlOption === 'jade' && useDashboard) { %>
        jade: {
            tasks: [
                'dashboard:server'
            ]
        },
        jadePartials: {
            tasks: [
                'dashboard:server'
            ]
        },<% } %><% if (htmlOption === 'swig' && useDashboard) { %>
        swig: {
            tasks: [
                'dashboard:server'
            ]
        },
        swigPartials: {
            tasks: [
                'dashboard:server'
            ]
        },<% } %><% if (useDashboard && htmlOption === 'html' || jsFramework === 'backbone') { %>
        html: {
            tasks: [
                'dashboard:server',
            ]
        },<% } %><% if (cssOption === 'sass' && useKss) { %>
        sass: {
            tasks: [
                'kss:server'
            ]
        },<% } %><% if (cssOption === 'less' && useKss) { %>
        less: {
            tasks: [
                'kss:server'
            ]
        },<% } %><% if (useJsdoc) { %>
        js: {
            files: [
                'README.md'
            ],
            tasks: [
                'jsdoc:server'
            ]
        },<% } %><% if (jsFramework === 'react' && useJsdoc) { %>
        react: {
            tasks: [
                'jsdoc:server'
            ]
        },<% } %><% if (useKss) { %>
        kss: {
            files: [
                '<%%= yeogurt.client %>/docs/styleguide/**/*.*'
            ],
            tasks: ['kss:server']
        },<% } %><% if (useDashboard) { %>
        dashboard: {
            files: [
                '<%%= yeogurt.client %>/docs/dashboard/**/*.*'
            ],
            tasks: ['dashboard:server']
        }<% } %>
    };<% } %>

    grunt.config.set('watch', config);
    <% if (useKss || useJsdoc || useDashboard) { %>
    grunt.registerTask('listen:docs', function() {
        // Merge docsConfig object with the config object without overwriting arrays
        // Instead concatenate all arrays with each other
        grunt.config('watch', _.merge(config, docsConfig, function(a, b) {
            return _.isArray(a) ? a.concat(b) : undefined;
        }));
        grunt.task.run('watch');
    });
    <% } %>

};

module.exports = taskConfig;
<commit_msg>Removed browserify:server tasks from watch as the `watch:true` option handles recompilation.<commit_after>/**
 * Configuration for watch task(s)
 */
'use strict';

var _ = require('lodash');

var taskConfig = function(grunt) {

    // Configuration
    var config = {
        configFiles: {
            files: [
                'Gruntfile.js',
                'grunt/**/*.js',
                '*.json'
            ],
            options: {
                reload: true,
                interrupt: true
            },
            tasks: [
                'serve:nowatch'
            ]
        },<% if (htmlOption === 'jade' && !useServer) { %>
        jade: {
            files: [
                '<%%= yeogurt.client %>/templates/*.jade'
            ],
            tasks: [
                'newer:jade:server'
            ]
        },
        jadePartials: {
            files: [
                '<%%= yeogurt.client %>/templates/**/*.jade',
                '!<%%= yeogurt.client %>/templates/*.jade'
            ],
            tasks: [
                'injector:jade',
                'jade:server'
            ]
        },<% } %><% if (htmlOption === 'swig' && !useServer) { %>
        swig: {
            files: [
                '<%%= yeogurt.client %>/templates/*.swig'
            ],
            tasks: [
                'newer:swig:server'
            ]
        },
        swigPartials: {
            files: [
                '<%%= yeogurt.client %>/templates/**/*.swig',
                '!<%%= yeogurt.client %>/templates/*.swig'
            ],
            tasks: [
                'injector:swig',
                'swig:server'
            ]
        },<% } %><% if (htmlOption === 'html' || jsFramework === 'backbone') { %>
        html: {
            files: [
                '<%%= yeogurt.client %>/templates/**/*.html'
            ],
            tasks: [
                'newer:copy:server',
                'clean:temp'
            ]
        },<% } %><% if (cssOption === 'sass') { %>
        sass: {
            files: ['<%%= yeogurt.client %>/styles/**/*.<% if (useKss) { %>{scss,sass,md}<% } else { %>{scss,sass}<% } %>'],
            tasks: [
                'injector:sass',
                'sass:server'
            ]
        },<% } %><% if (cssOption === 'less') { %>
        less: {
            files: ['<%%= yeogurt.client %>/styles/**/*.<% if (useKss) { %>{less,md}<% } else { %>less<% } %>'],
            tasks: [
                'injector:less',
                'less:server'
            ]
        },<% } %><% if (cssOption === 'stylus') { %>
        stylus: {
            files: ['<%%= yeogurt.client %>/styles/**/*.<% if (useKss) { %>{styl,md}<% } else { %>styl<% } %>'],
            tasks: [
                'injector:stylus',
                'stylus:server'
            ]
        },<% } %>
        injectCss: {
            files: [
                '<%%= yeogurt.client %>/styles/**/*.css'
            ],
            tasks: ['injector:css']
        },<% if (jsOption === 'none') { %>
        injectJs: {
            files: [
                '<%%= yeogurt.client %>/scripts/**/*.js',
                '!<%%= yeogurt.client %>/scripts/app.js'<% if (jsFramework === 'backbone') { %>,
                '!<%%= yeogurt.client %>/scripts/routes.js'<% } %>
            ],
            tasks: ['injector:scripts']
        },<% } %>
        js: {
            files: [
                '<%%= yeogurt.client %>/scripts/**/*.js'<% if (jsFramework === 'react' && !useJsx) { %>,
                '!<%%= yeogurt.client %>/scripts/**/components/*.js'<% } %>
            ],
            tasks: [<% if (jshint) { %>
                'newer:jshint',<% } %><% if (jsOption === 'browserify') { %>
                'exorcise:server',<% } %>
                'newer:copy:server'
            ]
        },<% if (jsFramework === 'react') { %>
        react: {<% if (useJsx) { %>
            files: ['<%%= yeogurt.client %>/scripts/components/**/*.jsx'],<% } else { %>
            files: ['<%%= yeogurt.client %>/scripts/components/**/*.js'],<% } %>
            tasks: [<% if (jsOption === 'requirejs') { %>
                'newer:copy:server',<% } %><% if (jsOption === 'browserify') { %>
                'exorcise:server'<% } %>
            ]
        },<% } %><% if (jsTemplate === 'handlebars') { %>
        handlebars: {
            files: ['<%%= yeogurt.client %>/templates/**/*.hbs'],
            tasks: [
                'handlebars:server'
            ]
        },<% } %><% if (jsTemplate === 'lodash') { %>
        jst: {
            files: ['<%%= yeogurt.client %>/templates/**/*.jst'],
            tasks: [
                'jst:server'
            ]
        },<% } %><% if (jsTemplate === 'jade') { %>
        jade: {
            files: ['<%%= yeogurt.client %>/templates/**/*.jade'],
            tasks: [
                'jade:server'<% if (useServer) { %>,
                'express:server'<% } %>
            ]
        },<% } %>
        images: {
            files: ['<%%= yeogurt.client %>/images/**/*.{png,jpg,gif}'],
            tasks: ['newer:copy:server']
        },
        root: {
            files: [
                '<%%= yeogurt.client %>/*.{ico,png,txt,html}',
                '<%%= yeogurt.client %>/images/**/*.webp',
                '<%%= yeogurt.client %>/styles/fonts/**/*.*'
            ],
            tasks: ['newer:copy:server']
        },
        livereload: {
            options: {
                livereload: <% if (!useServer) { %>'<%%= connect.options.livereload %>'<% } else { %>true<% } %>
            },
            files: [
                '<%%= yeogurt.staticServer %>/*.{ico,png,txt,html}',
                '<%%= yeogurt.staticServer %>/**/*.html',
                '<%%= yeogurt.staticServer %>/styles/**/*.{css,ttf,otf,woff,svg,eot}',
                '<%%= yeogurt.staticServer %>/scripts/**/*.js',<% if (singlePageApplication && jsTemplate !== 'react') { %>
                '<%%= yeogurt.staticServer %>/templates/**/*.{jst,hbs,jade}',<% } %>
                '<%%= yeogurt.staticServer %>/images/**/*.{png,jpg,jpeg,gif,webp,svg}'
            ]
        }<% if (useServer) { %>,
        express: {
            files: [
                'server.js',
                'server/**/*.{js,json,html}'<% if (jsFramework === 'react') { %><% if (useJsx) { %>,
                '<%%= yeogurt.client %>/scripts/components/*.jsx'<% } else { %>,
                '<%%= yeogurt.client %>/scripts/components/*.js'<% } %><% } %><% if (htmlOption === 'swig') { %>,
                '<%%= yeogurt.server %>/templates/**/*.swig'<% } %><% if (htmlOption === 'jade') { %>,
                '<%%= yeogurt.server %>/templates/**/*.jade'<% } %>
            ],
            tasks: [<% if (htmlOption === 'swig') { %>
                'injector:swig',<% } %><% if (htmlOption === 'jade') { %>
                'injector:jade',<% } %>
                'express:server',
                'wait'
            ],
            options: {
                livereload: true,
                nospawn: true //Without this option specified express won't be reloaded
            }
        }<% } %>
    };
    <% if (useKss || useJsdoc || useDashboard) { %>
    // Documentation specific configuration
    var docsConfig = {<% if (htmlOption === 'jade' && useDashboard) { %>
        jade: {
            tasks: [
                'dashboard:server'
            ]
        },
        jadePartials: {
            tasks: [
                'dashboard:server'
            ]
        },<% } %><% if (htmlOption === 'swig' && useDashboard) { %>
        swig: {
            tasks: [
                'dashboard:server'
            ]
        },
        swigPartials: {
            tasks: [
                'dashboard:server'
            ]
        },<% } %><% if (useDashboard && htmlOption === 'html' || jsFramework === 'backbone') { %>
        html: {
            tasks: [
                'dashboard:server',
            ]
        },<% } %><% if (cssOption === 'sass' && useKss) { %>
        sass: {
            tasks: [
                'kss:server'
            ]
        },<% } %><% if (cssOption === 'less' && useKss) { %>
        less: {
            tasks: [
                'kss:server'
            ]
        },<% } %><% if (useJsdoc) { %>
        js: {
            files: [
                'README.md'
            ],
            tasks: [
                'jsdoc:server'
            ]
        },<% } %><% if (jsFramework === 'react' && useJsdoc) { %>
        react: {
            tasks: [
                'jsdoc:server'
            ]
        },<% } %><% if (useKss) { %>
        kss: {
            files: [
                '<%%= yeogurt.client %>/docs/styleguide/**/*.*'
            ],
            tasks: ['kss:server']
        },<% } %><% if (useDashboard) { %>
        dashboard: {
            files: [
                '<%%= yeogurt.client %>/docs/dashboard/**/*.*'
            ],
            tasks: ['dashboard:server']
        }<% } %>
    };<% } %>

    grunt.config.set('watch', config);
    <% if (useKss || useJsdoc || useDashboard) { %>
    grunt.registerTask('listen:docs', function() {
        // Merge docsConfig object with the config object without overwriting arrays
        // Instead concatenate all arrays with each other
        grunt.config('watch', _.merge(config, docsConfig, function(a, b) {
            return _.isArray(a) ? a.concat(b) : undefined;
        }));
        grunt.task.run('watch');
    });
    <% } %>

};

module.exports = taskConfig;
<|endoftext|>


<commit_before>window.editable = Object.create({
	_edit_clicked: function(index, trigger_element){
		var _t 			= this;
		var edit_entry 	= $(trigger_element);

		var data = {
			'header' 			: 	'Editing ' + edit_entry.data('key'),
			'value' 			: 	edit_entry.text(),
			'identifier' 	: 	edit_entry.data('identifier'),
			'type'				: 	edit_entry.data('type'),
			'attribute'		: 	edit_entry.data('attribute'),
			'key'					: 	edit_entry.data('key')
		}

		// Here, register for updates pertaining to the edit-box currently displayed,
		// thus - only being responsible for the content contained here-in.

		// Register this to the de-registed once we close the popin!
		if(data.attribute){
			window.event_center.on('update', 'object', function(identifier, data, selector){
				_t.popin.find(selector).find('.' + data.key).html(data.value);
			});
		}else{
			window.event_center.on('update', 'property', function(identifier, data, selector){
				_t.popin.find(selector).html(data.value);
			});
		}

		// If we need to load the value from the server, render the popin
		// with loading == true, and start loading the data, replace the popin
		// once loading has completed.
		if(['object', 'objects'].indexOf(data.type) >= 0){
			$.ajax({
				url: '/create/property',
				type: 'get',
				dataType: 'json',
				data: {identifier: data.identifier, authenticity_token: authToken()},
				success: function(objects){
					objects = _t.ws_manager.prepare_gameobjects(objects, 1);
					_t.hide_edit();
					$.extend(data, objects);
					data.loading = false
					_t.create_edit(data, function(popin){
						Object.create(window.game_objects_collection).init(objects, popin, _t.ws_manager, _t.ws_manager.opts['gameobjects_collection']);
						_t.present_edit();
					});
				},
				error: function(){

				}
			});
			data.loading = true;
		}

		_t.create_edit(data, function(popin){
			_t.present_edit();
		});
	},

	present_edit: function(){
		this.workspace.prepend(this.popin);
	},

	create_edit: function(data, callback){
		var _t = this;
		var popin = $(_t.template.render(data));
		this.popin = popin;

		this.popin.find( ".go-droparea" ).droppable({
			accept: ".go-draghandle",
			hoverClass: "go-droparea-active",
			drop: function(e, ui){
				var identifier_data = ui.draggable.data('identifier');
				_t.save({identifier: data.identifier}, identifier_data.identifier)
			}
		});

		this.popin.find('.save-btn').one('click', _t.save.bind(_t, data, _t.popin.find('.property-edit-field').val()));
		this.popin.find('.property-edit-field').on('keypress', function(e){
			if(e.which == 13){
				e.preventDefault();
				_t.save.apply(_t, [data, _t.popin.find('.property-edit-field').val()]);
			}
		});
		callback(popin);
		return popin;
	},

	hide_edit: function(){
		if(this.popin){
			this.popin.find('.property-edit-field').off('keypress');
			this.popin.find('.save-btn').off('click');
			// Add animations to edit here...
			this.popin.remove();
			this.popin = null;
		}
	},

	save: function(data, value){
		var _t = this;
		var payload = {
			identifier: data.identifier,
			value: value,
			key: data.key,
			authenticity_token: authToken()
		};

		console.log(data);

		$.ajax({
			url: (data.attribute ? '/create' : '/create/property'),
			type: (data.attribute ? 'put' : 'post'),
			dataType: 'json',
			data: payload,
			success: function(server_data){
				var event_data = {
					identifier: payload.identifier,
					scope: null,
					data: {
						value: server_data.value,
						key: server_data.key
					}
				}
				if(data.attribute){
					$(document).trigger('update.object', [event_data]);
				}else{
					$(document).trigger('update.property', [event_data]);
				}
				_t.hide_edit();
			},
			error: function(){
				alert("Something went wrong!");
			}
		})
	},

	init: function(workspace, ws_manager){
		var _t 			= this;
		_t.workspace 	= workspace;
		_t.ws_manager	= ws_manager;

		_t.template		= Liquid.parse($('#workspace_editable_popin_template').html());

		// Attach events
		_t.workspace.find('.editable').each(function(index){
			$(this).on('click.creator.editable', function() {
				_t._edit_clicked.apply(_t, [index, this])
			});
		});
		return _t;
	}
});
<commit_msg>fixed broken editing<commit_after>window.editable = Object.create({
	_edit_clicked: function(index, trigger_element){
		var _t 			= this;
		var edit_entry 	= $(trigger_element);

		var data = {
			'header' 			: 	'Editing ' + edit_entry.data('key'),
			'value' 			: 	edit_entry.text(),
			'identifier' 	: 	edit_entry.data('identifier'),
			'type'				: 	edit_entry.data('type'),
			'attribute'		: 	edit_entry.data('attribute'),
			'key'					: 	edit_entry.data('key')
		}

		// Here, register for updates pertaining to the edit-box currently displayed,
		// thus - only being responsible for the content contained here-in.

		// Register this to the de-registed once we close the popin!
		if(data.attribute){
			window.event_center.on('update', 'object', function(identifier, data, selector){
				_t.popin.find(selector).find('.' + data.key).html(data.value);
			});
		}else{
			window.event_center.on('update', 'property', function(identifier, data, selector){
				_t.popin.find(selector).html(data.value);
			});
		}

		// If we need to load the value from the server, render the popin
		// with loading == true, and start loading the data, replace the popin
		// once loading has completed.
		if(['object', 'objects'].indexOf(data.type) >= 0){
			$.ajax({
				url: '/create/property',
				type: 'get',
				dataType: 'json',
				data: {identifier: data.identifier, authenticity_token: authToken()},
				success: function(objects){
					objects = _t.ws_manager.prepare_gameobjects(objects, 1);
					_t.hide_edit();
					$.extend(data, objects);
					data.loading = false
					_t.create_edit(data, function(popin){
						Object.create(window.game_objects_collection).init(objects, popin, _t.ws_manager, _t.ws_manager.opts['gameobjects_collection']);
						_t.present_edit();
					});
				},
				error: function(){

				}
			});
			data.loading = true;
		}

		_t.create_edit(data, function(popin){
			_t.present_edit();
		});
	},

	present_edit: function(){
		this.workspace.prepend(this.popin);
	},

	create_edit: function(data, callback){
		var _t = this;
		var popin = $(_t.template.render(data));
		this.popin = popin;

		this.popin.find( ".go-droparea" ).droppable({
			accept: ".go-draghandle",
			hoverClass: "go-droparea-active",
			drop: function(e, ui){
				var identifier_data = ui.draggable.data('identifier');
				_t.save({identifier: data.identifier}, identifier_data.identifier)
			}
		});

		this.popin.find('.save-btn').one('click', _t.save.bind(_t, data, _t.popin.find('.property-edit-field').val()));
		this.popin.find('.property-edit-field').on('keypress', function(e){
			if(e.which == 13){
				e.preventDefault();
				_t.save.apply(_t, [data, _t.popin.find('.property-edit-field').val()]);
			}
		});
		callback(popin);
		return popin;
	},

	hide_edit: function(){
		if(this.popin){
			this.popin.find('.property-edit-field').off('keypress');
			this.popin.find('.save-btn').off('click');
			// Add animations to edit here...
			this.popin.remove();
		//	this.popin = null;
		}
	},

	save: function(data, value){
		var _t = this;
		var payload = {
			identifier: data.identifier,
			value: value,
			key: data.key,
			authenticity_token: authToken()
		};

		$.ajax({
			url: (data.attribute ? '/create' : '/create/property'),
			type: (data.attribute ? 'put' : 'post'),
			dataType: 'json',
			data: payload,
			success: function(server_data){
				var event_data = {
					identifier: payload.identifier,
					scope: null,
					data: {
						value: server_data.value,
						key: server_data.key
					}
				}
				if(data.attribute){
					$(document).trigger('update.object', [event_data]);
				}else{
					$(document).trigger('update.property', [event_data]);
				}
				_t.hide_edit();
			},
			error: function(){
				alert("Something went wrong!");
			}
		})
	},

	init: function(workspace, ws_manager){
		var _t 			= this;
		_t.workspace 	= workspace;
		_t.ws_manager	= ws_manager;

		_t.template		= Liquid.parse($('#workspace_editable_popin_template').html());

		// Attach events
		_t.workspace.find('.editable').each(function(index){
			$(this).on('click.creator.editable', function() {
				_t._edit_clicked.apply(_t, [index, this])
			});
		});
		return _t;
	}
});
<|endoftext|>


<commit_before>//= require graphs/graph_scale

(function(){
  'use strict';

  var growstuff = (window.growstuff = window.growstuff || {});
  var GraphScale = growstuff.GraphScale;

function BarGroup(data) {
  this._data = data;
}

BarGroup.prototype.render = function(root){

  var data = this._data;
  var bars = this._data.bars;
  var xScale = new GraphScale(data, 'width').render();
  var yScale = new GraphScale(data, 'height').render();

  return root.append('g')
    .attr("class", "bar")
    .selectAll("rect")
    .data(bars.map(function(bar) { return bar.value; }))
    .enter()
    .append("rect")
    .attr("y", function(d, i){
      return yScale(i);

    })
    .attr("height", yScale.rangeBand())
      .attr("fill", "steelblue")
      .attr("width", function(d){
        return xScale(d);
      });
};

BarGroup.prototype.getBarValues = function () {
  var barValues = [];
  var bars = this._data.bars;
  var i = 0;
  var data = this._data;

  for (i; i < data.bars.length; i++){
    barValues.push(data.bars[i].value)
  };

  return barValues;
  }

growstuff.BarGroup = BarGroup;

})();<commit_msg>add tooltip to show data values<commit_after>//= require graphs/graph_scale

(function(){
  'use strict';

  var growstuff = (window.growstuff = window.growstuff || {});
  var GraphScale = growstuff.GraphScale;

function BarGroup(data) {
  this._data = data;
}

BarGroup.prototype.render = function(root){

  var data = this._data;
  var bars = this._data.bars;
  var xScale = new GraphScale(data, 'width').render();
  var yScale = new GraphScale(data, 'height').render();

  return root.append('g')
    .attr("class", "bar")
    .selectAll("rect")
    .data(bars.map(function(bar) { return bar.value; }))
    .enter()
    .append("rect")
    .attr("y", function(d, i){
      return yScale(i);

    })
    .attr("height", yScale.rangeBand())
    .attr("fill", "steelblue")
    .attr("width", function(d){
      return xScale(d);
    })
    .append("title")
    .text(function(d){
      return 'This value is ' + d + '.';
    });
};

BarGroup.prototype.getBarValues = function () {
  var barValues = [];
  var bars = this._data.bars;
  var i = 0;
  var data = this._data;

  for (i; i < data.bars.length; i++){
    barValues.push(data.bars[i].value)
  };

  return barValues;
  }

growstuff.BarGroup = BarGroup;

})();<|endoftext|>


<commit_before>//= require hyrax/save_work/save_work_control
//= require hyrax/save_work/required_fields
//= require hyrax/save_work/required_project
//= require hyrax/save_work/uploaded_files
//= require hyrax/save_work/checklist_item
//= require hyrax/save_work/deposit_agreement
//= require hyrax/save_work/visibility_component
<commit_msg>Add checklist item to save_work<commit_after>//= require hyrax/save_work/save_work_control
//= require hyrax/save_work/checklist_item
//= require hyrax/save_work/required_fields
//= require hyrax/save_work/required_project
//= require hyrax/save_work/uploaded_files
//= require hyrax/save_work/checklist_item
//= require hyrax/save_work/deposit_agreement
//= require hyrax/save_work/visibility_component
<|endoftext|>


<commit_before>app.controller("PlaceController",
              ["$http", "$location", "$scope", "$localStorage",
              function($http, $location, $scope, $localStorage) {
  var vm = this;
  vm.parent = $scope.$parent;
  // vm.prefectures = [];
  vm.places = [];

  vm.select = function(e) {
    delete $localStorage.places_keywords;
    $localStorage.places_keywords = vm.places;
  　$http.get("/suggestions/any.json", {params: { "places[]": vm.places}}).then(function(res) {
     vm.parent.vm.keyword = res.data.keyword;
     // $location.url("/interests");
    });
  }

  // $http.get("/prefectures.json").then(function(res) {
  //   vm.prefectures = res.data;
  // });

  var map;
  var infowindow;

  function initialize(lat,lng,create_only) {
    var city = new google.maps.LatLng(lat,lng);

    map = new google.maps.Map(document.getElementById('map'), {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: city,
        zoom: 14
    });

    if( create_only ){
      return;
    }

    var request = {
        location: city,
        radius: 1000  /* 指定した座標から半径1000m以内 */
    };
    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, callback);
  }

  function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      var j = 1;
      for (var i = 0; i < results.length; i++) {
        var spot = results[i];
        var types = spot.types;
        if( array_has("school", types)
        || array_has("train_station", types) ){
          continue;
        }
        // console.log(spot);
        createMarker(spot);
        vm.places.push(spot.name);
        // if( (array_has("establishment", types) && j==1) ||
        //   ((array_has("store",types) ||
        //     array_has("restaurant",types) ||
        //     array_has("shopping_mall",types) ||
        //     array_has("food",types) ||
        //     array_has("cafe",types) ||
        //     array_has("meal_takeaway",types)
        //    )
        //    && j==2) ){
        //   $(".place"+j).text(spot.name);
        //   createMarker(spot);
        //   j++;
        // }
        // if( j > 2 ){
        //   if( $(".place"+j).text() ){
        //     $(".place"+j).text(spot.name);
        //     createMarker(spot);
        //     j++;
        //   }
        // }
      }
      // if( j==1 ){
      //   $(".place1").text(results[0].name);
      //   createMarker(results[0]);
      //   $(".place2").text(results[1].name);
      //   createMarker(results[1]);
      // }
      // if( j==2 ){
      //   $(".place2").text(results[2].name);
      //   createMarker(results[5]);
      // }
      vm.select();
    }
  }

  function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
    });
//  マーカーをクリックすると場所の名前を表示
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(place.name);
        infowindow.open(map, this);
    });
  }

//google.maps.event.addDomListener(window, 'load', initialize);

  $(document).ready(function(){
    $("#search").click(findPlaces);
    $("#city_name").change(findPlaces);

    initialize(35.606938, 139.7489739, true);
  });

  function findPlaces(){
      // 入力された地名の緯度経度を得る
      var address = document.getElementById("city_name").value;
      if( !address ){
          alert("city not found");
          return;
      }
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode({'address':address},  //住所文字列
      function(results,status){
        if (status == google.maps.GeocoderStatus.OK) {
          var loc = results[0].geometry.location;
          $(".place_name").text(address);
          initialize(loc.lat(), loc.lng());
          // map.setCenter(results[0].geometry.location);  //入力された地域をmapの中心に表示
        }else {
          // 都市が見つからなければ、エラーのダイアログを出す
          alert("city not found: " + status);
        }
      }
      );
  }

  function array_has(target, items){
    for( var i=0; i<items.length; i++ ){
      if( target == items[i] ){
        return true;
      }
    }
    return false;
  }

}]);
<commit_msg>Reduce place keywords<commit_after>app.controller("PlaceController",
              ["$http", "$location", "$scope", "$localStorage",
              function($http, $location, $scope, $localStorage) {
  var vm = this;
  vm.parent = $scope.$parent;
  // vm.prefectures = [];
  vm.places = [];

  vm.select = function(e) {
    delete $localStorage.places_keywords;
    $localStorage.places_keywords = _.sample(vm.places, 10);
  　$http.get("/suggestions/any.json", {params: { "places[]": vm.places}}).then(function(res) {
     vm.parent.vm.keyword = res.data.keyword;
     // $location.url("/interests");
    });
  }

  // $http.get("/prefectures.json").then(function(res) {
  //   vm.prefectures = res.data;
  // });

  var map;
  var infowindow;

  function initialize(lat,lng,create_only) {
    var city = new google.maps.LatLng(lat,lng);

    map = new google.maps.Map(document.getElementById('map'), {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: city,
        zoom: 14
    });

    if( create_only ){
      return;
    }

    var request = {
        location: city,
        radius: 1000  /* 指定した座標から半径1000m以内 */
    };
    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, callback);
  }

  function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      var j = 1;
      for (var i = 0; i < results.length; i++) {
        var spot = results[i];
        var types = spot.types;
        if( array_has("school", types)
        || array_has("train_station", types) ){
          continue;
        }
        // console.log(spot);
        createMarker(spot);
        vm.places.push(spot.name);
        // if( (array_has("establishment", types) && j==1) ||
        //   ((array_has("store",types) ||
        //     array_has("restaurant",types) ||
        //     array_has("shopping_mall",types) ||
        //     array_has("food",types) ||
        //     array_has("cafe",types) ||
        //     array_has("meal_takeaway",types)
        //    )
        //    && j==2) ){
        //   $(".place"+j).text(spot.name);
        //   createMarker(spot);
        //   j++;
        // }
        // if( j > 2 ){
        //   if( $(".place"+j).text() ){
        //     $(".place"+j).text(spot.name);
        //     createMarker(spot);
        //     j++;
        //   }
        // }
      }
      // if( j==1 ){
      //   $(".place1").text(results[0].name);
      //   createMarker(results[0]);
      //   $(".place2").text(results[1].name);
      //   createMarker(results[1]);
      // }
      // if( j==2 ){
      //   $(".place2").text(results[2].name);
      //   createMarker(results[5]);
      // }
      vm.select();
    }
  }

  function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
    });
//  マーカーをクリックすると場所の名前を表示
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(place.name);
        infowindow.open(map, this);
    });
  }

//google.maps.event.addDomListener(window, 'load', initialize);

  $(document).ready(function(){
    $("#search").click(findPlaces);
    $("#city_name").change(findPlaces);

    initialize(35.606938, 139.7489739, true);
  });

  function findPlaces(){
      // 入力された地名の緯度経度を得る
      var address = document.getElementById("city_name").value;
      if( !address ){
          alert("city not found");
          return;
      }
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode({'address':address},  //住所文字列
      function(results,status){
        if (status == google.maps.GeocoderStatus.OK) {
          var loc = results[0].geometry.location;
          $(".place_name").text(address);
          initialize(loc.lat(), loc.lng());
          // map.setCenter(results[0].geometry.location);  //入力された地域をmapの中心に表示
        }else {
          // 都市が見つからなければ、エラーのダイアログを出す
          alert("city not found: " + status);
        }
      }
      );
  }

  function array_has(target, items){
    for( var i=0; i<items.length; i++ ){
      if( target == items[i] ){
        return true;
      }
    }
    return false;
  }

}]);
<|endoftext|>


<commit_before>function batch_edit_init () {

    // initialize popover helpers
    $("a[rel=popover]").popover({ html: true });

    function deserialize(Params) {
        var Data = Params.split("&");
        var i = Data.length;
        var Result  = {};
        while (i--) {
            var Pair = decodeURIComponent(Data[i]).split("=");
            var key = Pair[0];
            var val = Pair[1];
            if (Result[key] != null) {
                if(!$.isArray(Result[key])) Result[key] = [Result[key]];
                Result[key].push(val);
            } else
                Result[key] = val;
        }
        return Result;
    }

    var ajaxManager = (function () {
        var requests = [];
        var running = false;
        return {
            addReq: function (opt) {
                requests.push(opt);
            },
            removeReq: function (opt) {
                if ($.inArray(opt, requests) > -1)
                    requests.splice($.inArray(opt, requests), 1);
            },
            runNow: function () {
                clearTimeout(this.tid);
                if (!running) {
                    this.run();
                }
            },
            run: function () {
                running = true;
                var self = this;

                if (requests.length) {

                    // combine data from multiple requests
                    if (requests.length > 1) {
                      requests = this.combine_requests(requests);
                    }

                    requests = this.setup_request_complete(requests);
                    $.ajax(requests[0]);
                } else {
                    self.tid = setTimeout(function () {
                        self.run.apply(self, []);
                    }, 500);
                    running = false;
                }
            },
            stop: function () {
                requests = [];
                clearTimeout(this.tid);
            },
            setup_request_complete: function (requests) {
                oriComp = requests[0].complete;

                requests[0].complete = [ function (e) {
                    req = requests.shift();
                    if (typeof req.form === 'object') {
                        for (f in req.form) {
                            form_id = form[f];
                            after_ajax(form_id);
                        }
                    }
                    this.tid = setTimeout(function () {
                        ajaxManager.run.apply(ajaxManager, []);
                    }, 50);
                    return true;
                }];
                if (typeof oriComp === 'function') requests[0].complete.push(oriComp);
                return requests;
            },
            combine_requests: function (requests) {
                var data = deserialize(requests[0].data.replace(/\+/g, " "));
                form = [requests[0].form]
                for (var i = requests.length - 1; i > 0; i--) {
                    req = requests.pop();
                    adata = deserialize(req.data.replace(/\+/g, " "));

                    for (key in  Object.keys(adata)) {
                        curKey = Object.keys(adata)[key];
                        if (curKey.slice(0, 12) == "generic_file") {
                            data[curKey] = adata[curKey];
                            form.push(req.form);
                        }
                    }
                }
                requests[0].data = $.param(data);
                requests[0].form = form;
                return requests;
            }
        };
    }());

    ajaxManager.run();

    function after_ajax(form) {
        form.enableForm();
    }

    function before_ajax(form) {
        form.disableForm();
    }

    var BatchEditField = function (form) {
        this.form = form;
        this.formButtons = form.find('.btn');
        this.formFields = form.find('.form-group > *');
        this.formRightPanel = form.find('.form-group');
        this.statusField = form.find('.status');
    }

    BatchEditField.prototype = {
        disableForm: function () {
            this.formButtons.attr("disabled", "disabled");
            this.formRightPanel.addClass("loading");
            this.formFields.addClass('invisible')
        },

        enableForm: function () {
            this.statusField.html("Changes Saved");
            this.formButtons.removeAttr("disabled");
            this.formRightPanel.removeClass("loading");
            this.formFields.removeClass('invisible')
        }
    }

    function runSave(e) {
        e.preventDefault();
        var button = $(this);
        var form = button.closest('form');
        var f = new BatchEditField(form);
        var form_id = form[0].id;
        before_ajax(f);

        ajaxManager.addReq({
            form: form_id,
            queue: "add_doc",
            url: form.attr("action"),
            dataType: "json",
            type: form.attr("method").toUpperCase(),
            data: form.serialize(),
            success: function (e) {
                after_ajax(f);
            },
            fail: function (e) {
                alert("Error!  Status: " + e.status);
            }
        });
        setTimeout(ajaxManager.runNow(), 100);
    }

    $("#permissions_save").click(runSave);
    $(".field-save").click(runSave);
}

// turbolinks triggers page:load events on page transition
// If app isn't using turbolinks, this event will never be triggered, no prob.
$(document).on('page:load', function() {
    batch_edit_init();
});

$(document).ready(function() {
    batch_edit_init();
});
<commit_msg>Updating to allow the forms sent together to be properly enabled after the update<commit_after>function batch_edit_init () {

    // initialize popover helpers
    $("a[rel=popover]").popover({ html: true });

    function deserialize(Params) {
        var Data = Params.split("&");
        var i = Data.length;
        var Result  = {};
        while (i--) {
            var Pair = decodeURIComponent(Data[i]).split("=");
            var key = Pair[0];
            var val = Pair[1];
            if (Result[key] != null) {
                if(!$.isArray(Result[key])) Result[key] = [Result[key]];
                Result[key].push(val);
            } else
                Result[key] = val;
        }
        return Result;
    }

    var ajaxManager = (function () {
        var requests = [];
        var running = false;
        return {
            addReq: function (opt) {
                requests.push(opt);
            },
            removeReq: function (opt) {
                if ($.inArray(opt, requests) > -1)
                    requests.splice($.inArray(opt, requests), 1);
            },
            runNow: function () {
                clearTimeout(this.tid);
                if (!running) {
                    this.run();
                }
            },
            run: function () {
                running = true;
                var self = this;

                if (requests.length) {

                    // combine data from multiple requests
                    if (requests.length > 1) {
                      requests = this.combine_requests(requests);
                    }

                    requests = this.setup_request_complete(requests);
                    $.ajax(requests[0]);
                } else {
                    self.tid = setTimeout(function () {
                        self.run.apply(self, []);
                    }, 500);
                    running = false;
                }
            },
            stop: function () {
                requests = [];
                clearTimeout(this.tid);
            },
            setup_request_complete: function (requests) {
                oriComp = requests[0].complete;

                requests[0].complete = [ function (e) {
                    req = requests.shift();
                    if (typeof req.form === 'object') {
                        for (f in req.form) {
                            form_id = form[f];
                            after_ajax(new BatchEditField($("#"+form_id)));
                        }
                    }
                    this.tid = setTimeout(function () {
                        ajaxManager.run.apply(ajaxManager, []);
                    }, 50);
                    return true;
                }];
                if (typeof oriComp === 'function') requests[0].complete.push(oriComp);
                return requests;
            },
            combine_requests: function (requests) {
                var data = deserialize(requests[0].data.replace(/\+/g, " "));
                form = [requests[0].form]
                for (var i = requests.length - 1; i > 0; i--) {
                    req = requests.pop();
                    adata = deserialize(req.data.replace(/\+/g, " "));

                    for (key in  Object.keys(adata)) {
                        curKey = Object.keys(adata)[key];
                        if (curKey.slice(0, 12) == "generic_file") {
                            data[curKey] = adata[curKey];
                            form.push(req.form);
                        }
                    }
                }
                requests[0].data = $.param(data);
                requests[0].form = form;
                return requests;
            }
        };
    }());

    ajaxManager.run();

    function after_ajax(form) {
        form.enableForm();
    }

    function before_ajax(form) {
        form.disableForm();
    }

    var BatchEditField = function (form) {
        this.form = form;
        this.formButtons = form.find('.btn');
        this.formFields = form.find('.form-group > *');
        this.formRightPanel = form.find('.form-group');
        this.statusField = form.find('.status');
    }

    BatchEditField.prototype = {
        disableForm: function () {
            this.formButtons.attr("disabled", "disabled");
            this.formRightPanel.addClass("loading");
            this.formFields.addClass('invisible')
        },

        enableForm: function () {
            this.statusField.html("Changes Saved");
            this.formButtons.removeAttr("disabled");
            this.formRightPanel.removeClass("loading");
            this.formFields.removeClass('invisible')
        }
    }

    function runSave(e) {
        e.preventDefault();
        var button = $(this);
        var form = button.closest('form');
        var f = new BatchEditField(form);
        var form_id = form[0].id;
        before_ajax(f);

        ajaxManager.addReq({
            form: form_id,
            queue: "add_doc",
            url: form.attr("action"),
            dataType: "json",
            type: form.attr("method").toUpperCase(),
            data: form.serialize(),
            success: function (e) {
                after_ajax(f);
            },
            fail: function (e) {
                alert("Error!  Status: " + e.status);
            }
        });
        setTimeout(ajaxManager.runNow(), 100);
    }

    $("#permissions_save").click(runSave);
    $(".field-save").click(runSave);
}

// turbolinks triggers page:load events on page transition
// If app isn't using turbolinks, this event will never be triggered, no prob.
$(document).on('page:load', function() {
    batch_edit_init();
});

$(document).ready(function() {
    batch_edit_init();
});
<|endoftext|>


<commit_before>class_counter = 0;
has_classes = false;
selected_classes = {};

function ClassList(){}

ClassList.prototype.add_class_callback = function(event, ui) {
    var keycode = $.ui.keyCode;
    if( event.keyCode == keycode.TAB ) {
        /* If the user hit a tab, we don't want to add it just yet */
        return;
    }
    /* Prevent input box being filled */
    event.preventDefault();
    this.value = "";

    if ( ui.item ) {
        show_button();
        var class_id = ui.item.value;
        if( class_id in selected_classes ){
            /* return if the user as already selected the class*/
            pop_alert("error","class is already selected");
            return;
        } else {
            selected_classes[class_id] = class_counter;
        }

        /* Append the course to the currently populated list */
        var remove_course = $("<a/>").text("X").attr("href", "#").addClass("remove-link");
        var course_li = $("<li/>")
                            .append(remove_course)
                            .append($("<span/>")
                                .text(ui.item.label)
                                .addClass("code"))
                            .append($("<span/>")
                                .text(ui.item.title)
                                .addClass("title"))
                            .css("display", "none");
        course_li.appendTo(".user-course-list ul");
        course_li.slideDown();

        remove_course.click( function() {
            var removed = 0;
            // Search through the hidden form and remove this element
            $(".hidden-course-form").children().each( function(i) {
                if($(this).val() == class_id){
                    $(this).remove();
                    removed++;
                } else if ($(this).attr("name") == "size"){
                    var current_size = $(this).val();
                    $(this).val(current_size - removed );
                };
            });
            course_li.slideUp();
            $(this).remove();
        });

        /* Add the course id to our hidden form */
        add_course_id_to_hidden_form(class_id);
        class_counter++;

        /* use a form to keep track of count */
        $("<input>").val(class_counter)
            .attr("type", "hidden")
            .attr("name", "size")
            .appendTo(".hidden-course-form");
    }

}

function show_button() {
    if( has_classes ) return;
    $(".hidden-course-form .btn.primary.hidden").removeClass("hidden");
    $(".user-course-list span.hint")
        .animate({
            opacity: 0,
            display: 'none',
          }, 200, function() {
            $(this).slideUp();
          });
    has_classes = true;
};

/* In order to send a list of class ids to rails, we need to silently
   keep track of the class ids in a hidden form as well as send the size of the list */
var add_course_id_to_hidden_form = function( course_id ) {
    $("<input>").val(course_id)
        .attr("type", "hidden")
        .attr("name", class_counter)
        .appendTo(".hidden-course-form");
};
<commit_msg>fixed add/remove bug<commit_after>class_counter = 0;
has_classes = false;
selected_classes = {};

function ClassList(){}

ClassList.prototype.add_class_callback = function(event, ui) {
    var keycode = $.ui.keyCode;
    if( event.keyCode == keycode.TAB ) {
        /* If the user hit a tab, we don't want to add it just yet */
        return;
    }
    /* Prevent input box being filled */
    event.preventDefault();
    this.value = "";

    if ( ui.item ) {
        show_button();
        var class_id = ui.item.value;
        if( class_id in selected_classes ){
            /* return if the user as already selected the class*/
            pop_alert("error","class is already selected");
            return;
        } else {
            selected_classes[class_id] = class_counter;
        }

        /* Append the course to the currently populated list */
        var remove_course = $("<a/>").text("X").attr("href", "#").addClass("remove-link");
        var course_li = $("<li/>")
                            .append(remove_course)
                            .append($("<span/>")
                                .text(ui.item.label)
                                .addClass("code"))
                            .append($("<span/>")
                                .text(ui.item.title)
                                .addClass("title"))
                            .css("display", "none");
        course_li.appendTo(".user-course-list ul");
        course_li.slideDown();

        remove_course.click( function() {
            var removed = 0;
            // Search through the hidden form and remove this element
            $(".hidden-course-form").children().each( function(i) {
                if($(this).val() == class_id){
                    $(this).remove();
                    removed++;
                } else if ($(this).attr("name") == "size"){
                    var current_size = $(this).val();
                    $(this).val(current_size - removed );
                };
            });
            course_li.slideUp();
            $(this).remove();
            delete selected_classes[class_id];
        });

        /* Add the course id to our hidden form */
        add_course_id_to_hidden_form(class_id);
        class_counter++;

        /* use a form to keep track of count */
        $("<input>").val(class_counter)
            .attr("type", "hidden")
            .attr("name", "size")
            .appendTo(".hidden-course-form");
    }

}

function show_button() {
    if( has_classes ) return;
    $(".hidden-course-form .btn.primary.hidden").removeClass("hidden");
    $(".user-course-list span.hint")
        .animate({
            opacity: 0,
            display: 'none',
          }, 200, function() {
            $(this).slideUp();
          });
    has_classes = true;
};

/* In order to send a list of class ids to rails, we need to silently
   keep track of the class ids in a hidden form as well as send the size of the list */
var add_course_id_to_hidden_form = function( course_id ) {
    $("<input>").val(course_id)
        .attr("type", "hidden")
        .attr("name", class_counter)
        .appendTo(".hidden-course-form");
};
<|endoftext|>


<commit_before>Slipmat.Views.UserShow = Backbone.CompositeView.extend({

  tagName: "main",
  className: "group",
  template: JST["users/show"],

  initialize: function (options) {
    options = options || {};
    this.$rootEl = options.$rootEl;
    this.headerTemplate = JST["users/_userHeader"];

    this.listenTo(this.model, "sync", this.render);
  },

  render: function () {
    $(".profile-header").remove();

    var header = this.headerTemplate({ user: this.model });
    var content = this.template({ user: this.model });
    var profile = JST["users/_profile"]({ user: this.model });

    this.$rootEl.before(header);
    this.$el.html(content);
    this.$(".profile-main").html(profile);

    $(".tab").on("click", this.switchTab.bind(this));
    return this;
  },

  remove: function () {
    $(".profile-header").remove();
    Backbone.View.prototype.remove.call(this);
  },

  switchTab: function (e) {
    e.preventDefault();

    var template = $(e.currentTarget).data("id");
    var content = JST["users/_" + template]({ user: this.model });

    this.$(".profile-main").html(content);
  }

});
<commit_msg>Remove profile header event handler upon UserShow removal<commit_after>Slipmat.Views.UserShow = Backbone.CompositeView.extend({

  tagName: "main",
  className: "group",
  template: JST["users/show"],

  initialize: function (options) {
    options = options || {};
    this.$rootEl = options.$rootEl;
    this.headerTemplate = JST["users/_userHeader"];

    this.listenTo(this.model, "sync", this.render);
  },

  render: function () {
    var header = this.headerTemplate({ user: this.model });
    var content = this.template({ user: this.model });
    var profile = JST["users/_profile"]({ user: this.model });

    this.$rootEl.before(header);
    this.$el.html(content);

    $(".profile-header").remove();
    this.$(".profile-main").html(profile);
    $(".tab").on("click", this.switchTab.bind(this));

    return this;
  },

  remove: function () {
    $(".profile-header").remove();
    $(".tab").off("click");

    Backbone.View.prototype.remove.call(this);
  },

  switchTab: function (e) {
    e.preventDefault();

    var template = $(e.currentTarget).data("id");
    var content = JST["users/_" + template]({ user: this.model });

    this.$(".profile-main").html(content);
  }

});
<|endoftext|>


<commit_before>#!/usr/bin/env nodejs
var _ = require('lodash');
var cheerio = require('cheerio');
var moment = require('moment');
var debug = require('debug')('parser:imageAltTag');
var parse = require('./lib/parse');

/*
 * Extract alt text from img tags
 */

var PARSER_COMPLETED_SUCCESSFULLY = false;

function imageAltTag(snippet) {

    debug("→ %j", _.omit(snippet, ['html']));

    var $ = cheerio.load(snippet.html);

    var altTagFounds = $('img[alt]');
    altTagFounds = _.map(altTagFounds, function (e) {
      return e.attribs.alt;
    });
    altTagFounds = _.flatten(altTagFounds);
    altTagFounds = _.uniq(altTagFounds);

    PARSER_COMPLETED_SUCCESSFULLY = true;
    return {
        imageAltTag: PARSER_COMPLETED_SUCCESSFULLY,
        altTexts: altTagFounds
    }
};

return parse.please({
    'name': 'imageAltTag',
    'requirements': { hrefType: 'photo' },
    'implementation': imageAltTag,
    'since': "2017-03-15",
    'until': moment().toISOString(),
});
<commit_msg>debug in progress @endorama #60<commit_after>#!/usr/bin/env nodejs
var _ = require('lodash');
var cheerio = require('cheerio');
var moment = require('moment');
var debug = require('debug')('parser:imageAltText');
var parse = require('./lib/parse');

/*
 * Extract alt text from img tags
 */

function imageAltText(snippet) {

    var $ = cheerio.load(snippet.html);

    var altTagFounds = $('img[alt]');
    altTagFounds = _.map(altTagFounds, function (e) {
      return e.attribs.alt;
    });
    debug("Found %j", altTagFounds);
    altTagFounds = _.flatten(altTagFounds);
    altTagFounds = _.reject(altTagFounds, "");
    altTagFounds = _.uniq(altTagFounds);

    debug("Found %j", altTagFounds);

    if(!_.size(altTagFounds)) {
        debug("Failed in %s", snippet.id);
        return { imageAltText: false };
    }
    else {
        debug("Found %j", altTagFounds);
        return {
            imageAltText: true,
            altTexts: altTagFounds
        };
    }
};

return parse.please({
    'name': 'imageAltText',
    'requirements': { hrefType: 'photo' },
    'implementation': imageAltText,
    'since': "2017-12-09",
    'until': moment().toISOString(),
});
<|endoftext|>


<commit_before>'use strict';
import React from 'react';
import { PropTypes as T } from 'prop-types';
import { connect } from 'react-redux';
import _ from 'lodash';
import qs from 'qs';
import moment from 'moment';
import { Link } from 'react-router-dom';
import createReactClass from 'create-react-class';

import config from '../../config';
import {
  fetchLocationIfNeeded,
  fetchLatestMeasurements,
  fetchMeasurements,
  invalidateAllLocationData,
  openDownloadModal
} from '../../actions/action-creators';
import HeaderMessage from '../../components/header-message';
import StatsInfo from './stats-info';
import Metadata from './metadata';
import SourceInfo from './source-info';
import ValuesBreakdown from './values-breakdown';
import NearbyLoc from './nearby-loc';

var Location = createReactClass({
  displayName: 'Location',

  propTypes: {
    params: T.object,
    location: T.object,
    _fetchLocationIfNeeded: T.func,
    _fetchLocations: T.func,
    _fetchLatestMeasurements: T.func,
    _fetchMeasurements: T.func,
    _invalidateAllLocationData: T.func,
    _openDownloadModal: T.func,

    countries: T.array,
    sources: T.array,
    parameters: T.array,

    countryData: T.object,

    loc: T.shape({
      fetching: T.bool,
      fetched: T.bool,
      error: T.string,
      data: T.object
    }),

    latestMeasurements: T.shape({
      fetching: T.bool,
      fetched: T.bool,
      error: T.string,
      data: T.object
    }),

    measurements: T.shape({
      fetching: T.bool,
      fetched: T.bool,
      error: T.string,
      data: T.object
    })
  },

  getInitialState: function () {
    return {
      modalDownloadOpen: false
    };
  },

  shouldFetchData: function (prevProps) {
    let prevLoc = prevProps.match.params.name;
    let currLoc = this.props.match.params.name;

    return prevLoc !== currLoc;
  },

  getActiveParameterData: function () {
    const query = qs.parse(this.props.location.search);
    let parameterData = _.find(this.props.parameters, {id: query.parameter});
    return parameterData || _.find(this.props.parameters, {id: 'pm25'});
  },

  //
  // Start event listeners
  //

  onFilterSelect: function (parameter) {
    this.props.history.push(`/location/${encodeURIComponent(this.props.match.params.name)}?parameter=${parameter}`);
  },

  onDownloadClick: function () {
    let d = this.props.loc.data;
    this.props._openDownloadModal({
      country: d.country,
      area: d.city,
      location: d.location
    });
  },

  //
  // Start life-cycle methods.
  //

  componentDidMount: function () {
    // Invalidate all the data related to the location page.
    // This is needed otherwise the system thinks there's data and
    // throws errors.
    this.props._invalidateAllLocationData();
    this.props._fetchLocationIfNeeded(this.props.match.params.name);
  },

  componentDidUpdate: function (prevProps) {
    if (this.shouldFetchData(prevProps)) {
      // Invalidate all the data related to the location page.
      // This is needed otherwise the system thinks there's data and
      // throws errors.
      this.props._invalidateAllLocationData();
      this.props._fetchLocationIfNeeded(this.props.match.params.name);
      return;
    }

    if (this.props.loc.fetched && !this.props.loc.fetching &&
      !this.props.latestMeasurements.fetched && !this.props.latestMeasurements.fetching &&
      !this.props.measurements.fetched && !this.props.measurements.fetching) {
      let loc = this.props.loc.data;

      // Get the measurements.
      let toDate = moment.utc();
      let fromDate = toDate.clone().subtract(8, 'days');
      // this.props._fetchLatestMeasurements({city: loc.city, has_geo: 'true'});
      if (loc.coordinates) {
        this.props._fetchLatestMeasurements({
          coordinates: `${loc.coordinates.latitude},${loc.coordinates.longitude}`,
          radius: 10 * 1000, // 10 Km
          has_geo: 'true'
        });
      } else {
        this.props._fetchLatestMeasurements({
          location: loc.location
        });
      }
      this.props._fetchMeasurements(loc.location, fromDate.toISOString(), toDate.toISOString());
    }
  },

  //
  // Start render methods.
  //

  render: function () {
    const { countryData } = this.props;
    let {fetched, fetching, error, data} = this.props.loc;
    if (!fetched && !fetching) {
      return null;
    }

    const country = countryData || {};

    if (fetching) {
      return (
        <HeaderMessage>

Take a deep breath.

Location data is loading...

        </HeaderMessage>
      );
    }

    if (error) {
      return (
        <HeaderMessage>

Uh oh, something went wrong.

There was a problem getting the data. If you continue to have problems, please let us know.

Send us an Email

        </HeaderMessage>
      );
    }
    return (

location

{data.location} in {data.city}, {country.name}

<a href={`${config.api}/locations?location=${data.location}`} title='View in API documentation' className='ipha-api' target='_blank'>View API

<button type='button' title='Download data for this location' className='ipha-download' onClick={this.onDownloadClick}>Download</button>

<Link to={`/compare/${encodeURIComponent(data.location)}`} title='Compare location with another' className='ipha-compare ipha-main'>Compare</Link>

          <StatsInfo
            latestMeasurements={this.props.latestMeasurements}
            measurements={this.props.measurements}
            loc={this.props.loc}
            parameters={this.props.parameters}
            />
          <Metadata loc={this.props.loc} />
          <SourceInfo
            sources={this.props.sources}
            measurements={this.props.measurements}
            loc={this.props.loc}
          />
          <ValuesBreakdown
            measurements={this.props.measurements}
            parameters={this.props.parameters}
            activeParam={this.getActiveParameterData()}
            onFilterSelect={this.onFilterSelect}
          />
          <NearbyLoc
            countryData={this.props.countryData}
            latestMeasurements={this.props.latestMeasurements}
            loc={this.props.loc}
            parameters={this.props.parameters}
            sources={this.props.sources} />

    );
  }
});

// /////////////////////////////////////////////////////////////////// //
// Connect functions

function selector (state) {
  return {
    countries: state.baseData.data.countries,
    sources: state.baseData.data.sources,
    parameters: state.baseData.data.parameters,

    countryData: _.find(state.baseData.data.countries, {code: (state.location.data || {}).country}),

    loc: state.location,
    latestMeasurements: state.latestMeasurements,
    measurements: state.measurements
  };
}

function dispatcher (dispatch) {
  return {
    _fetchLocationIfNeeded: (...args) => dispatch(fetchLocationIfNeeded(...args)),
    _fetchLatestMeasurements: (...args) => dispatch(fetchLatestMeasurements(...args)),
    _fetchMeasurements: (...args) => dispatch(fetchMeasurements(...args)),
    _invalidateAllLocationData: (...args) => dispatch(invalidateAllLocationData(...args)),

    _openDownloadModal: (...args) => dispatch(openDownloadModal(...args))
  };
}

module.exports = connect(selector, dispatcher)(Location);
<commit_msg>Transform location into function component with hooks<commit_after>import React, { useEffect } from 'react';
import { PropTypes as T } from 'prop-types';
import { connect } from 'react-redux';
import _ from 'lodash';
import qs from 'qs';
import moment from 'moment';
import { Link } from 'react-router-dom';

import config from '../../config';
import {
  fetchLocationIfNeeded,
  fetchLatestMeasurements,
  fetchMeasurements,
  invalidateAllLocationData,
  openDownloadModal
} from '../../actions/action-creators';
import HeaderMessage from '../../components/header-message';
import StatsInfo from './stats-info';
import Metadata from './metadata';
import SourceInfo from './source-info';
import ValuesBreakdown from './values-breakdown';
import NearbyLoc from './nearby-loc';

function Location (props) {
  const query = qs.parse(props.location.search);
  const { name } = props.match.params;

  useEffect(() => {
    // Invalidate all the data related to the location page.
    // This is needed otherwise the system thinks there's data and
    // throws errors.
    props._invalidateAllLocationData();
    props._fetchLocationIfNeeded(name);
    return () => {
      props._invalidateAllLocationData();
    };
  }, [name]);

  useEffect(() => {
    // TODO: this needs more refactoring!
    if (
      props.loc.fetched &&
      !props.loc.fetching &&
      !props.latestMeasurements.fetched &&
      !props.latestMeasurements.fetching &&
      !props.measurements.fetched &&
      !props.measurements.fetching
    ) {
      let loc = props.loc.data;
      // Get the measurements.
      let toDate = moment.utc();
      let fromDate = toDate.clone().subtract(8, 'days');
      // props._fetchLatestMeasurements({city: loc.city, has_geo: 'true'});
      if (loc.coordinates) {
        props._fetchLatestMeasurements({
          coordinates: `${loc.coordinates.latitude},${loc.coordinates.longitude}`,
          radius: 10 * 1000, // 10 Km
          has_geo: 'true'
        });
      } else {
        props._fetchLatestMeasurements({
          location: loc.location
        });
      }
      props._fetchMeasurements(
        loc.location,
        fromDate.toISOString(),
        toDate.toISOString()
      );
    }
  });

  function getActiveParameterData () {
    let parameterData = _.find(props.parameters, { id: query.parameter });
    return parameterData || _.find(props.parameters, { id: 'pm25' });
  }

  function onFilterSelect (parameter) {
    props.history.push(
      `/location/${encodeURIComponent(name)}?parameter=${parameter}`
    );
  }

  function onDownloadClick () {
    let d = props.loc.data;
    props._openDownloadModal({
      country: d.country,
      area: d.city,
      location: d.location
    });
  }

  const { countryData } = props;
  let { fetched, fetching, error, data } = props.loc;
  if (!fetched && !fetching) {
    return null;
  }

  const country = countryData || {};

  if (fetching) {
    return (
      <HeaderMessage>

Take a deep breath.

Location data is loading...

      </HeaderMessage>
    );
  }

  if (error) {
    return (
      <HeaderMessage>

Uh oh, something went wrong.

            There was a problem getting the data. If you continue to have
            problems, please let us know.

              Send us an Email

      </HeaderMessage>
    );
  }

  return (

location

              {data.location}{' '}

                in {data.city}, {country.name}

                <a
                  href={`${config.api}/locations?location=${data.location}`}
                  title="View in API documentation"
                  className="ipha-api"
                  target="_blank"
                >
                  View API

                <button
                  type="button"
                  title="Download data for this location"
                  className="ipha-download"
                  onClick={onDownloadClick}
                >
                  Download
                </button>

                <Link
                  to={`/compare/${encodeURIComponent(data.location)}`}
                  title="Compare location with another"
                  className="ipha-compare ipha-main"
                >
                  Compare
                </Link>

        <StatsInfo
          latestMeasurements={props.latestMeasurements}
          measurements={props.measurements}
          loc={props.loc}
          parameters={props.parameters}
        />
        <Metadata loc={props.loc} />
        <SourceInfo
          sources={props.sources}
          measurements={props.measurements}
          loc={props.loc}
        />
        <ValuesBreakdown
          measurements={props.measurements}
          parameters={props.parameters}
          activeParam={getActiveParameterData()}
          onFilterSelect={onFilterSelect}
        />
        <NearbyLoc
          countryData={props.countryData}
          latestMeasurements={props.latestMeasurements}
          loc={props.loc}
          parameters={props.parameters}
          sources={props.sources}
        />

  );
}

Location.propTypes = {
  match: T.object,
  location: T.object,

  _fetchLocationIfNeeded: T.func,
  _fetchLocations: T.func,
  _fetchLatestMeasurements: T.func,
  _fetchMeasurements: T.func,
  _invalidateAllLocationData: T.func,
  _openDownloadModal: T.func,

  countries: T.array,
  sources: T.array,
  parameters: T.array,

  countryData: T.object,

  loc: T.shape({
    fetching: T.bool,
    fetched: T.bool,
    error: T.string,
    data: T.object
  }),

  latestMeasurements: T.shape({
    fetching: T.bool,
    fetched: T.bool,
    error: T.string,
    data: T.object
  }),

  measurements: T.shape({
    fetching: T.bool,
    fetched: T.bool,
    error: T.string,
    data: T.object
  })
};

// /////////////////////////////////////////////////////////////////// //
// Connect functions

function selector (state) {
  return {
    countries: state.baseData.data.countries,
    sources: state.baseData.data.sources,
    parameters: state.baseData.data.parameters,

    countryData: _.find(state.baseData.data.countries, {
      code: (state.location.data || {}).country
    }),

    loc: state.location,
    latestMeasurements: state.latestMeasurements,
    measurements: state.measurements
  };
}

function dispatcher (dispatch) {
  return {
    _fetchLocationIfNeeded: (...args) =>
      dispatch(fetchLocationIfNeeded(...args)),
    _fetchLatestMeasurements: (...args) =>
      dispatch(fetchLatestMeasurements(...args)),
    _fetchMeasurements: (...args) => dispatch(fetchMeasurements(...args)),
    _invalidateAllLocationData: (...args) =>
      dispatch(invalidateAllLocationData(...args)),

    _openDownloadModal: (...args) => dispatch(openDownloadModal(...args))
  };
}

export default connect(selector, dispatcher)(Location);
<|endoftext|>