<commit_before>
/**
 * Module dependencies.
 */
module.exports = function(ukiyoe, app) {

var Image = ukiyoe.db.model("Image"),
    utils = require("../../lib/utils"),
    _ = require("lodash"),
    exports = {};

Image.prototype.getURL = function(locale) {
    return app.genURL(locale, "/images/" + this._id);
};

Image.prototype.getOriginalURL = function(locale) {
    return app.dataURL(this.source._id || this.source,
        "images/" + this.imageName + ".jpg");
};

Image.prototype.getScaledURL = function(locale) {
    return app.dataURL(this.source._id || this.source,
        "scaled/" + this.imageName + ".jpg");
};

Image.prototype.getThumbURL = function(locale) {
    return app.dataURL(this.source._id || this.source,
        "thumbs/" + this.imageName + ".jpg");
};

exports.load = function(req, res, next, imageName) {
    Image.findById(req.params.sourceId + "/" + imageName)
        .populate("similar.image")
        .populate("artists.artist")
        .populate("source") // TODO: Don't do this.
        .exec(function(err, image) {
            if (err) {
                return next(err);
            }
            if (!image) {
                console.log("not found")
                return next(new Error("not found"));
            }
            req.image = image;
            next();
        });
};

exports.search = function(req, res) {
    var page = (req.param("page") > 0 ? req.param("page") : 1) - 1;
    var perPage = 100;
    var q = req.param("q") || "";

    var query = {
        query_string: {
            query: q
        },
        filtered: {
            filter: {},
            size: perPage,
            from: page * perPage,
            "sort": [
                {
                    "dateCreated.start": {
                        "order": "asc"
                    }
                },
                {
                    "dateCreated.end": {
                        "order": "asc"
                    }
                }
            ]
        }
    };

    if (req.param("startDate") && req.param("endDate")) {
        query.filtered.filter.and = [
            {
                range: {
                    "dateCreated.start": {
                        gte: parseFloat(req.param("startDate")),
                        lte: parseFloat(req.param("endDate"))
                    }
                }
            },
            {
                range: {
                    "dateCreated.end": {
                        gte: parseFloat(req.param("startDate")),
                        lte: parseFloat(req.param("endDate"))
                    }
                }
            }
        ];
    }

    Image.search({query: query}, {hydrate: true, hydrateOptions: {populate: "artists.artist"}}, function(err, results){
        if (err) {
            console.error(err);
            return res.render("500");
        }

        res.render("images/index", {
            title: "Images",
            q: req.param("q"),
            startDate: req.param("startDate") || "1765",
            endDate: req.param("endDate") || "1868",
            images: results.hits,
            page: page + 1,
            pages: Math.ceil(results.total / perPage)
        });
    });
};

/**
 * List
 */

exports.index = function(req, res) {
    var page = (req.param("page") > 0 ? req.param("page") : 1) - 1;
    var perPage = 100;
    var options = {
        query: "fish",
        size: perPage,
        from: page * perPage
    };

    // , hydrateOptions: {populate: "bios"}
    Image.search(options, {hydrate: true}, function(err, results){
        if (err) {
            return res.render("500");
        }

        res.render("images/index", {
            title: "Images",
            images: results.hits,
            page: page + 1,
            pages: Math.ceil(results.total / perPage)
        });
    });
};

/**
 * New image
 */

exports.new = function(req, res) {
    res.render("images/new", {
        title: "New Image",
        image: new Image({})
    });
};

/**
 * Create an image
 */

exports.create = function(req, res) {
    var image = new Image(req.body);
    image.user = req.user;

    image.save(function(err) {
        if (!err) {
            req.flash("success", "Successfully created image!");
            return res.redirect("/images/" + image._id);
        }

        res.render("images/new", {
            title: "New Image",
            image: image,
            errors: utils.errors(err.errors || err)
        });
    });
};

/**
 * Edit an image
 */

exports.edit = function(req, res) {
    res.render("images/edit", {
        title: "Edit " + req.image.title,
        image: req.image
    });
};

/**
 * Update image
 */

exports.update = function(req, res) {
    var image = req.image;
    image = _.extend(image, req.body);

    image.save(function(err) {
        if (!err) {
            return res.redirect("/images/" + image._id);
        }

        res.render("images/edit", {
            title: "Edit Image",
            image: image,
            errors: err.errors
        });
    });
};

/**
 * Show
 */

exports.show = function(req, res) {
    res.render("images/show", {
        //title: req.image.title,
        image: req.image,
        results: req.image.similar
    });
};

/**
 * Delete an image
 */

exports.destroy = function(req, res) {
    var image = req.image;
    image.remove(function(err) {
        req.flash("info", "Deleted successfully")
        res.redirect("/images")
    });
};

return exports;
};<commit_msg>Start to write logic for handling image uploads.<commit_after>
/**
 * Module dependencies.
 */
module.exports = function(ukiyoe, app) {

var Image = ukiyoe.db.model("Image"),
    utils = require("../../lib/utils"),
    _ = require("lodash"),
    exports = {};

Image.prototype.getURL = function(locale) {
    return app.genURL(locale, "/images/" + this._id);
};

exports.load = function(req, res, next, imageName) {
    Image.findById(req.params.sourceId + "/" + imageName)
        .populate("similar.image")
        .populate("artists.artist")
        .populate("source") // TODO: Don't do this.
        .exec(function(err, image) {
            if (err) {
                return next(err);
            }
            if (!image) {
                console.log("not found")
                return next(new Error("not found"));
            }
            req.image = image;
            next();
        });
};

exports.search = function(req, res) {
    var page = (req.param("page") > 0 ? req.param("page") : 1) - 1;
    var perPage = 100;
    var q = req.param("q") || "";

    var query = {
        query_string: {
            query: q
        },
        filtered: {
            filter: {},
            size: perPage,
            from: page * perPage,
            "sort": [
                {
                    "dateCreated.start": {
                        "order": "asc"
                    }
                },
                {
                    "dateCreated.end": {
                        "order": "asc"
                    }
                }
            ]
        }
    };

    if (req.param("startDate") && req.param("endDate")) {
        query.filtered.filter.and = [
            {
                range: {
                    "dateCreated.start": {
                        gte: parseFloat(req.param("startDate")),
                        lte: parseFloat(req.param("endDate"))
                    }
                }
            },
            {
                range: {
                    "dateCreated.end": {
                        gte: parseFloat(req.param("startDate")),
                        lte: parseFloat(req.param("endDate"))
                    }
                }
            }
        ];
    }

    Image.search({query: query}, {hydrate: true, hydrateOptions: {populate: "artists.artist"}}, function(err, results){
        if (err) {
            console.error(err);
            return res.render("500");
        }

        res.render("images/index", {
            title: "Images",
            q: req.param("q"),
            startDate: req.param("startDate") || "1765",
            endDate: req.param("endDate") || "1868",
            images: results.hits,
            page: page + 1,
            pages: Math.ceil(results.total / perPage)
        });
    });
};

var handleUpload = function(req, baseDir, callback) {
    var url = req.body.url || req.query.url;

    // Handle the user accidentally hitting enter
    if (url && url === "http://") {
        return callback();
    }

    var stream;

    if (url) {
        stream = request({
            url: url,
            timeout: 30000
        });
    } else {
        stream = fs.createReadStream(req.files.file.path)
    }

    ukiyoe.images.downloadStream(stream, baseDir, true, callback);
};

exports.searchUpload = function(req, res) {
    // TODO: Get baseDir for the image
    handleUpload(req, "...", function() {

    });
};

/**
 * List
 */

exports.index = function(req, res) {
    var page = (req.param("page") > 0 ? req.param("page") : 1) - 1;
    var perPage = 100;
    var options = {
        query: "fish",
        size: perPage,
        from: page * perPage
    };

    // , hydrateOptions: {populate: "bios"}
    Image.search(options, {hydrate: true}, function(err, results){
        if (err) {
            return res.render("500");
        }

        res.render("images/index", {
            title: "Images",
            images: results.hits,
            page: page + 1,
            pages: Math.ceil(results.total / perPage)
        });
    });
};

/**
 * New image
 */

exports.new = function(req, res) {
    res.render("images/new", {
        title: "New Image",
        image: new Image({})
    });
};

/**
 * Create an image
 */

exports.create = function(req, res) {
    var image = new Image(req.body);
    image.user = req.user;

    image.save(function(err) {
        if (!err) {
            req.flash("success", "Successfully created image!");
            return res.redirect("/images/" + image._id);
        }

        res.render("images/new", {
            title: "New Image",
            image: image,
            errors: utils.errors(err.errors || err)
        });
    });
};

/**
 * Edit an image
 */

exports.edit = function(req, res) {
    res.render("images/edit", {
        title: "Edit " + req.image.title,
        image: req.image
    });
};

/**
 * Update image
 */

exports.update = function(req, res) {
    var image = req.image;
    image = _.extend(image, req.body);

    image.save(function(err) {
        if (!err) {
            return res.redirect("/images/" + image._id);
        }

        res.render("images/edit", {
            title: "Edit Image",
            image: image,
            errors: err.errors
        });
    });
};

/**
 * Show
 */

exports.show = function(req, res) {
    res.render("images/show", {
        //title: req.image.title,
        image: req.image,
        results: req.image.similar
    });
};

/**
 * Delete an image
 */

exports.destroy = function(req, res) {
    var image = req.image;
    image.remove(function(err) {
        req.flash("info", "Deleted successfully")
        res.redirect("/images")
    });
};

return exports;
};<|endoftext|>


<commit_before>Package.describe({
  name: 'simple:rest',
  version: '0.1.2',
  // Brief, one-line summary of the package.
  summary: 'The easiest way to add a REST API to your Meteor app',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/stubailo/meteor-rest',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');

  api.use([
    "underscore",
    "ddp",
    "meteor",
    "webapp",
    "simple:json-routes@1.0.1",
    "minimongo",
    "ejson"
  ], "server");

  api.use([
    "accounts-base"
  ], "server", {weak: true});

  api.addFiles([
    'http-connection.js',
    'http-subscription.js',
    'rest.js',
    'list-api.js'
  ], "server");
});

Package.onTest(function(api) {
  api.use("simple:rest-accounts-password");
  api.use("underscore");
  api.use("test-helpers");
  api.use("mongo");
  api.use("random");
  api.imply("http");
  api.use('tinytest');
  api.use('simple:rest');
  api.use('simple:json-routes');
  api.addFiles('rest-tests.js');
});
<commit_msg>Update github URL<commit_after>Package.describe({
  name: 'simple:rest',
  version: '0.1.2',
  // Brief, one-line summary of the package.
  summary: 'The easiest way to add a REST API to your Meteor app',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/stubailo/meteor-rest/blob/master/packages/rest/',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');

  api.use([
    "underscore",
    "ddp",
    "meteor",
    "webapp",
    "simple:json-routes@1.0.1",
    "minimongo",
    "ejson"
  ], "server");

  api.use([
    "accounts-base"
  ], "server", {weak: true});

  api.addFiles([
    'http-connection.js',
    'http-subscription.js',
    'rest.js',
    'list-api.js'
  ], "server");
});

Package.onTest(function(api) {
  api.use("simple:rest-accounts-password");
  api.use("underscore");
  api.use("test-helpers");
  api.use("mongo");
  api.use("random");
  api.imply("http");
  api.use('tinytest');
  api.use('simple:rest');
  api.use('simple:json-routes');
  api.addFiles('rest-tests.js');
});
<|endoftext|>


<commit_before>import $ from 'jquery';
import Controller, {inject as controller} from '@ember/controller';
import RSVP from 'rsvp';
import ValidationEngine from 'ghost-admin/mixins/validation-engine';
import {alias} from '@ember/object/computed';
import {isArray as isEmberArray} from '@ember/array';
import {isVersionMismatchError} from 'ghost-admin/services/ajax';
import {inject as service} from '@ember/service';
import {task} from 'ember-concurrency';

export default Controller.extend(ValidationEngine, {
    application: controller(),
    ajax: service(),
    config: service(),
    ghostPaths: service(),
    notifications: service(),
    session: service(),
    settings: service(),

    submitting: false,
    loggingIn: false,
    authProperties: null,

    flowErrors: '',
    // ValidationEngine settings
    validationType: 'signin',

    init() {
        this._super(...arguments);
        this.authProperties = ['identification', 'password'];
    },

    signin: alias('model'),

    actions: {
        authenticate() {
            this.validateAndAuthenticate.perform();
        }
    },

    authenticate: task(function* (authStrategy, authentication) {
        try {
            let authResult = yield this.session
                .authenticate(authStrategy, ...authentication);
            let promises = [];

            promises.pushObject(this.settings.fetch());
            promises.pushObject(this.config.fetchAuthenticated());

            // fetch settings and private config for synchronous access
            yield RSVP.all(promises);

            return authResult;
        } catch (error) {
            if (isVersionMismatchError(error)) {
                return this.notifications.showAPIError(error);
            }

            if (error && error.payload && error.payload.errors) {
                let [mainError] = error.payload.errors;

                mainError.message = (mainError.message || '').htmlSafe();
                mainError.context = (mainError.context || '').htmlSafe();

                this.set('flowErrors', (mainError.context.string || mainError.message.string));

                if (mainError.context.string.match(/user with that email/i)) {
                    this.get('signin.errors').add('identification', '');
                }

                if (mainError.context.string.match(/password is incorrect/i)) {
                    this.get('signin.errors').add('password', '');
                }
            } else {
                // Connection errors don't return proper status message, only req.body
                this.notifications.showAlert(
                    'There was a problem on the server.',
                    {type: 'error', key: 'session.authenticate.failed'}
                );
            }
        }
    }).drop(),

    validateAndAuthenticate: task(function* () {
        let signin = this.signin;
        let authStrategy = 'authenticator:cookie';

        this.set('flowErrors', '');
        // Manually trigger events for input fields, ensuring legacy compatibility with
        // browsers and password managers that don't send proper events on autofill
        $('#login').find('input').trigger('change');

        // This is a bit dirty, but there's no other way to ensure the properties are set as well as 'signin'
        this.hasValidated.addObjects(this.authProperties);

        try {
            yield this.validate({property: 'signin'});
            return yield this.authenticate
                .perform(authStrategy, [signin.get('identification'), signin.get('password')]);
        } catch (error) {
            this.set('flowErrors', 'Please fill out the form to sign in.');
        }
    }).drop(),

    forgotten: task(function* () {
        let email = this.get('signin.identification');
        let forgottenUrl = this.get('ghostPaths.url').api('authentication', 'passwordreset');
        let notifications = this.notifications;

        this.set('flowErrors', '');
        // This is a bit dirty, but there's no other way to ensure the properties are set as well as 'forgotPassword'
        this.hasValidated.addObject('identification');

        try {
            yield this.validate({property: 'forgotPassword'});
            yield this.ajax.post(forgottenUrl, {data: {passwordreset: [{email}]}});
            notifications.showAlert(
                'Please check your email for instructions.',
                {type: 'info', key: 'forgot-password.send.success'}
            );
            return true;
        } catch (error) {
            // ValidationEngine throws "undefined" for failed validation
            if (!error) {
                return this.set('flowErrors', 'We need your email address to reset your password!');
            }

            if (isVersionMismatchError(error)) {
                return notifications.showAPIError(error);
            }

            if (error && error.payload && error.payload.errors && isEmberArray(error.payload.errors)) {
                let [{message}] = error.payload.errors;

                this.set('flowErrors', message);

                if (message.match(/no user with that email/)) {
                    this.get('signin.errors').add('identification', '');
                }
            } else {
                notifications.showAPIError(error, {defaultErrorText: 'There was a problem with the reset, please try again.', key: 'forgot-password.send'});
            }
        }
    })
});
<commit_msg>Fixed highlight of email field for "unknown user" in forgot password flow<commit_after>import $ from 'jquery';
import Controller, {inject as controller} from '@ember/controller';
import RSVP from 'rsvp';
import ValidationEngine from 'ghost-admin/mixins/validation-engine';
import {alias} from '@ember/object/computed';
import {isArray as isEmberArray} from '@ember/array';
import {isVersionMismatchError} from 'ghost-admin/services/ajax';
import {inject as service} from '@ember/service';
import {task} from 'ember-concurrency';

export default Controller.extend(ValidationEngine, {
    application: controller(),
    ajax: service(),
    config: service(),
    ghostPaths: service(),
    notifications: service(),
    session: service(),
    settings: service(),

    submitting: false,
    loggingIn: false,
    authProperties: null,

    flowErrors: '',
    // ValidationEngine settings
    validationType: 'signin',

    init() {
        this._super(...arguments);
        this.authProperties = ['identification', 'password'];
    },

    signin: alias('model'),

    actions: {
        authenticate() {
            this.validateAndAuthenticate.perform();
        }
    },

    authenticate: task(function* (authStrategy, authentication) {
        try {
            let authResult = yield this.session
                .authenticate(authStrategy, ...authentication);
            let promises = [];

            promises.pushObject(this.settings.fetch());
            promises.pushObject(this.config.fetchAuthenticated());

            // fetch settings and private config for synchronous access
            yield RSVP.all(promises);

            return authResult;
        } catch (error) {
            if (isVersionMismatchError(error)) {
                return this.notifications.showAPIError(error);
            }

            if (error && error.payload && error.payload.errors) {
                let [mainError] = error.payload.errors;

                mainError.message = (mainError.message || '').htmlSafe();
                mainError.context = (mainError.context || '').htmlSafe();

                this.set('flowErrors', (mainError.context.string || mainError.message.string));

                if (mainError.context.string.match(/user with that email/i)) {
                    this.get('signin.errors').add('identification', '');
                }

                if (mainError.context.string.match(/password is incorrect/i)) {
                    this.get('signin.errors').add('password', '');
                }
            } else {
                // Connection errors don't return proper status message, only req.body
                this.notifications.showAlert(
                    'There was a problem on the server.',
                    {type: 'error', key: 'session.authenticate.failed'}
                );
            }
        }
    }).drop(),

    validateAndAuthenticate: task(function* () {
        let signin = this.signin;
        let authStrategy = 'authenticator:cookie';

        this.set('flowErrors', '');
        // Manually trigger events for input fields, ensuring legacy compatibility with
        // browsers and password managers that don't send proper events on autofill
        $('#login').find('input').trigger('change');

        // This is a bit dirty, but there's no other way to ensure the properties are set as well as 'signin'
        this.hasValidated.addObjects(this.authProperties);

        try {
            yield this.validate({property: 'signin'});
            return yield this.authenticate
                .perform(authStrategy, [signin.get('identification'), signin.get('password')]);
        } catch (error) {
            this.set('flowErrors', 'Please fill out the form to sign in.');
        }
    }).drop(),

    forgotten: task(function* () {
        let email = this.get('signin.identification');
        let forgottenUrl = this.get('ghostPaths.url').api('authentication', 'passwordreset');
        let notifications = this.notifications;

        this.set('flowErrors', '');
        // This is a bit dirty, but there's no other way to ensure the properties are set as well as 'forgotPassword'
        this.hasValidated.addObject('identification');

        try {
            yield this.validate({property: 'forgotPassword'});
            yield this.ajax.post(forgottenUrl, {data: {passwordreset: [{email}]}});
            notifications.showAlert(
                'Please check your email for instructions.',
                {type: 'info', key: 'forgot-password.send.success'}
            );
            return true;
        } catch (error) {
            // ValidationEngine throws "undefined" for failed validation
            if (!error) {
                return this.set('flowErrors', 'We need your email address to reset your password!');
            }

            if (isVersionMismatchError(error)) {
                return notifications.showAPIError(error);
            }

            if (error && error.payload && error.payload.errors && isEmberArray(error.payload.errors)) {
                let [{message}] = error.payload.errors;

                this.set('flowErrors', message);

                if (message.match(/no user|not found/)) {
                    this.get('signin.errors').add('identification', '');
                }
            } else {
                notifications.showAPIError(error, {defaultErrorText: 'There was a problem with the reset, please try again.', key: 'forgot-password.send'});
            }
        }
    })
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import ENV from 'plenario-explorer/config/environment';

export default Ember.Controller.extend({
  modelArrived: Ember.observer('model', function() {
    const nodeList = this.get('model.nodes');
    const nodeTuples = nodeList.map(node => {
      return [node.properties.id, node.properties];
    });
    const nodeMap = new Map(nodeTuples);
    this.set('nodeMap', nodeMap);
    // TODO: Move magic node id to environment config
    this.set('selectedNode', nodeMap.get(ENV.defaultNode));
  }),

  actions: {
    onSelect(nodeId) {
      const newNode = this.get('nodeMap').get(nodeId);
      this.set('selectedNode', newNode);
    }
  }
});
<commit_msg>Set default node as first returned from API<commit_after>import Ember from 'ember';
// import ENV from 'plenario-explorer/config/environment';

export default Ember.Controller.extend({
  modelArrived: Ember.observer('model', function() {
    const nodeList = this.get('model.nodes');
    const nodeTuples = nodeList.map(node => {
      return [node.properties.id, node.properties];
    });
    const nodeMap = new Map(nodeTuples);
    this.set('nodeMap', nodeMap);
    this.set('selectedNode', nodeList[0].properties);
  }),

  actions: {
    onSelect(nodeId) {
      const newNode = this.get('nodeMap').get(nodeId);
      this.set('selectedNode', newNode);
    }
  }
});
<|endoftext|>


<commit_before>/*
 * The contents of this file are subject to the OpenMRS Public License
 * Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
define(openhmis.url.backboneBase + "js/openhmis",
	[
		openhmis.url.backboneBase + 'js/lib/jquery',
		openhmis.url.backboneBase + 'js/lib/underscore',
		openhmis.url.backboneBase + 'js/lib/backbone',
		openhmis.url.backboneBase + 'js/lib/i18n',
		openhmis.url.backboneBase + 'js/lib/backbone-forms'
	],
	function($, _, Backbone, __) {

		// Use <? ?> for template tags.
		_.templateSettings = {
			evaluate:  /<\?(.+?)\?>/g,
			interpolate: /<\?=(.+?)\?>/g
		};

		var openhmis = window.openhmis || {};
		openhmis.templates = {};

		openhmis.url.getPage = function (moduleBaseName) {
			return openhmis.url.page + openhmis.url[moduleBaseName];
		};

		//TODO: Better system for identifying specific errors
		openhmis.error = function (model, resp) {
			var handleErrorResp = function (resp) {
				var o = (typeof resp === "string") ? $.parseJSON(resp).error : resp;
				if (o.detail.indexOf("ContextAuthenticationException") !== -1) {
					alert(__("Your session has timed out.  You will be redirected to the login page."));
					window.location.reload();
				}
				else if (o.detail.indexOf("AccessControlException") !== -1) {
					if (o.detail.indexOf("refund") !== -1) {
						alert(__("The total of the bill is negative and you do not have the required privileges to process a refund.\n\nPlease contact your supervisor about processing refunds."));
					}
					else if (o.detail.indexOf("adjust") !== -1) {
						alert(__("You do not have the required privileges to adjust a bill.\n\nPlease contact your supervisor about adjusting a bill."));
					}
				}
				else if (o.message && o.message.indexOf("no rounding item ID") !== -1) {
					alert(__(o.message + "\n\nPlease specify a rounding item or disable rounding."));
				}
				else {
					var firstLfPos = o.detail.indexOf('\n');
					if (firstLfPos !== -1)
						o.detail = o.detail.substring(0, firstLfPos);
					alert('An error occurred during the request.\n\n' + o.message + '\n\nCode: ' + o.code + '\n\n' + o.detail);
				}
			};

			if (!(model instanceof Backbone.Model)) {
				if (model.responseText)
					handleErrorResp(model.responseText);
				else
					handleErrorResp(model);
			} else if (resp !== undefined) {
				handleErrorResp(resp.responseText);
				//var str = "";
				//for (var i in resp) {
				//	if (str.length > 0) str += ",\n";
				//	str += i + ": " + resp[i];
				//}
				//alert(str);
			}
		};

		openhmis.getQueryStringParameter = function (name) {
			name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
			var regexS = "[\\?&]" + name + "=([^&#]*)";
			var regex = new RegExp(regexS);
			var results = regex.exec(window.location.search);
			if (results == null)
				return "";
			else
				return decodeURIComponent(results[1].replace(/\+/g, " "));
		};

		openhmis.addQueryStringParameter = function (queryString, parameter) {
			return queryString ? queryString + "&" + parameter : parameter;
		};

		openhmis.padZero = function (n) {
			return n < 10 ? "0" + n : n;
		};

		openhmis.pad2Zeros = function (n) {
			if (n < 100) n = '0' + n;
			if (n < 10) n = '0' + n;
			return n;
		};

		openhmis.dateFormat = function (date, includeTime) {
			if (typeof date === "string") {
				date = new Date(date);
			}

			var padZero = openhmis.padZero;
			var day = date.getDate();
			var month = date.getMonth() + 1;
			var year = date.getFullYear();
			day = padZero(day);
			month = padZero(month);
			var strDate = day + '-' + month + '-' + year;
			if (includeTime === true) {
				strDate += " " + padZero(date.getHours())
					+ ":" + padZero(date.getMinutes());
			}
			return strDate;
		};

		openhmis.dateFormatWithSeconds = function (date) {
			if (typeof date === "string") {
				date = new Date(date);
			}

			var padZero = openhmis.padZero;
			var day = date.getDate();
			var month = date.getMonth() + 1;
			var year = date.getFullYear();
			day = padZero(day);
			month = padZero(month);
			var hours = padZero(date.getHours());
			var minutes = padZero(date.getMinutes());
			var seconds= padZero(date.getSeconds());
			return day + '-' + month + '-' + year + " " + hours + ":" + minutes + ":" + seconds;
		};

		openhmis.dateFormatLocale = function (date) {
			if (typeof date === "string") {
				date = new Date(date);
			}

			return date ? date.toLocaleDateString() : "";
		};

		openhmis.dateTimeFormatLocale = function (date) {
			if (typeof date === "string") {
				date = new Date(date);
			}

			return date ? date.toLocaleString() : "";
		};

		openhmis.timeFormatLocale = function(date) {
			if (typeof date === "string") {
				date = new Date(date);
			}

			return date ? date.toLocaleTimeString() : "";
		};

		openhmis.iso8601Date = function (d) {
			var padZero = openhmis.padZero;
			var pad2Zeros = openhmis.pad2Zeros;
			return d.getUTCFullYear() + '-' + padZero(d.getUTCMonth() + 1) + '-' + padZero(d.getUTCDate()) + 'T' + padZero(d.getUTCHours()) + ':' + padZero(d.getUTCMinutes()) + ':' + padZero(d.getUTCSeconds()) + '.' + pad2Zeros(d.getUTCMilliseconds()) + '+0000';
		};

		openhmis.tryParsingFuzzyDate = function (fuzzyString) {
			var numberOfSomething = /^([0-9]+)\s?(\w+)(\s+.*)?$/;
			var matches = fuzzyString.match(numberOfSomething);
			var number;
			if (matches && matches[2] && !isNaN(number = parseInt(matches[1]))) {
				matches[1] = number;
				return matches;
			}
			return null;
		};

		openhmis.toFuzzyDate = function (seconds) {
			var timeChunks = [
				[31536000, __("year")],
				[604800, __("week")],
				[86400, __("day")]
			];
			for (var i in timeChunks) {
				var chunk = timeChunks[i]
				var numberOfChunks;
				if ((numberOfChunks = Math.floor(seconds / chunk[0])) >= 1) {
					var string = numberOfChunks === 1
						? __("%d %s", numberOfChunks, chunk[1])
						: __("%d %s", numberOfChunks, openhmis.pluralize(chunk[1]));
					var remainder = seconds % chunk[0];
					if (remainder > 0)
						return string + " " + openhmis.toFuzzyDate(remainder);
					else
						return string;
				}
			}
			return null;
		};

		openhmis.fromFuzzyDate = function (fuzzyString, carry) {
			var timeChunks = [
				["year", 31536000],
				["week", 604800],
				["day", 86400]
			];
			var matches = openhmis.tryParsingFuzzyDate($.trim(fuzzyString))
			if (matches) {
				for (var i in timeChunks) {
					var chunk = timeChunks[i];
					if (matches[2] === chunk[0] || matches[2] === (chunk[0] + "s")) {
						var seconds = matches[1] * chunk[1];
						if (matches[3])
							return openhmis.fromFuzzyDate(matches[3], seconds + (carry || 0));
						else
							return seconds + (carry || 0);
					}
				}
			}

			return carry;
		};

		openhmis.validationMessage = function (parentEl, message, inputEl) {
			if ($(parentEl).length > 1) parentEl = $(parentEl)[0];
			if ($(parentEl).find('.validation').length > 0) return;
			var prevPosition = $(parentEl).css("position");
			$(parentEl).css("position", "relative");
			var el = $('

');
			el.text(message);
			$(parentEl).append(el);
			if (inputEl !== undefined) $(inputEl).focus();
			setTimeout(function () {
				$(el).remove();
				if (prevPosition !== "static")
					$(parentEl).css("position", prevPosition);
			}, 5000);
		};

		openhmis.round = function (val, nearest, mode) {
			nearest = nearest ? nearest : 1;
			if (nearest === 0) return val;
			var factor = 1 / nearest;
			switch (mode) {
				case 'FLOOR':
					return Math.floor(val * factor) / factor;
				case 'CEILING':
					return Math.ceil(val * factor) / factor;
				default:
					return Math.round(val * factor) / factor;
			}
		};

		openhmis.isNumeric = function (n) {
			return !isNaN(parseFloat(n)) && isFinite(n);
		};

		openhmis.toCamelCase = function (str, firstCapital) {
			firstCapital = firstCapital !== undefined ? firstCapital : false;
			str.replace(
				/\b(\S)(\S*)/g,
				function (match, first, rest) {
					return first.toUpperCase() + rest.toLowerCase();
				}
			);
			if (!firstCapital)
				str = str.charAt(0).toLowerCase() + str.substring(1);
			return str;
		};

		// Use uuid for id
		Backbone.Model.prototype.idAttribute = 'uuid';

		/**
		 * Template helper function
		 *
		 * Fetches a template from a remote URI unless it has been previously fetched
		 * and cached.
		 */
		Backbone.View.prototype.tmplFileRoot = openhmis.url.resources;
		Backbone.View.prototype.getTemplate = function(tmplFile, tmplSelector) {
			tmplFile = tmplFile ? tmplFile : this.tmplFile;
			tmplSelector = tmplSelector ? tmplSelector : this.tmplSelector;
			var view = this;
			if (openhmis.templates[tmplFile] === undefined) {
				var uri = view.tmplFileRoot === undefined ? tmplFile : view.tmplFileRoot + tmplFile;
				$.ajax({
					url: uri,
					async: false,
					dataType: "html",
					success: function(data, status, jq) {
						openhmis.templates[tmplFile] = $("
").html(data);
					}
				});
			}

			var template = _.template($(openhmis.templates[tmplFile]).find(tmplSelector).html());
			var augmentedTemplate = function(context) {
				if (context !== undefined) {
					context.__ = context.__ ? context.__ : __;
					context.urls = context.urls ? context.urls : openhmis.url;
					context.helpers = context.helpers ? context.helpers : Backbone.Form.helpers
					context.pluralize = openhmis.pluralize;
				}

				return template.call(this, context);
			};

			return augmentedTemplate;
		};

		return openhmis;
	}
);
<commit_msg>null check on date<commit_after>/*
 * The contents of this file are subject to the OpenMRS Public License
 * Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
define(openhmis.url.backboneBase + "js/openhmis",
	[
		openhmis.url.backboneBase + 'js/lib/jquery',
		openhmis.url.backboneBase + 'js/lib/underscore',
		openhmis.url.backboneBase + 'js/lib/backbone',
		openhmis.url.backboneBase + 'js/lib/i18n',
		openhmis.url.backboneBase + 'js/lib/backbone-forms'
	],
	function($, _, Backbone, __) {

		// Use <? ?> for template tags.
		_.templateSettings = {
			evaluate:  /<\?(.+?)\?>/g,
			interpolate: /<\?=(.+?)\?>/g
		};

		var openhmis = window.openhmis || {};
		openhmis.templates = {};

		openhmis.url.getPage = function (moduleBaseName) {
			return openhmis.url.page + openhmis.url[moduleBaseName];
		};

		//TODO: Better system for identifying specific errors
		openhmis.error = function (model, resp) {
			var handleErrorResp = function (resp) {
				var o = (typeof resp === "string") ? $.parseJSON(resp).error : resp;
				if (o.detail.indexOf("ContextAuthenticationException") !== -1) {
					alert(__("Your session has timed out.  You will be redirected to the login page."));
					window.location.reload();
				}
				else if (o.detail.indexOf("AccessControlException") !== -1) {
					if (o.detail.indexOf("refund") !== -1) {
						alert(__("The total of the bill is negative and you do not have the required privileges to process a refund.\n\nPlease contact your supervisor about processing refunds."));
					}
					else if (o.detail.indexOf("adjust") !== -1) {
						alert(__("You do not have the required privileges to adjust a bill.\n\nPlease contact your supervisor about adjusting a bill."));
					}
				}
				else if (o.message && o.message.indexOf("no rounding item ID") !== -1) {
					alert(__(o.message + "\n\nPlease specify a rounding item or disable rounding."));
				}
				else {
					var firstLfPos = o.detail.indexOf('\n');
					if (firstLfPos !== -1)
						o.detail = o.detail.substring(0, firstLfPos);
					alert('An error occurred during the request.\n\n' + o.message + '\n\nCode: ' + o.code + '\n\n' + o.detail);
				}
			};

			if (!(model instanceof Backbone.Model)) {
				if (model.responseText)
					handleErrorResp(model.responseText);
				else
					handleErrorResp(model);
			} else if (resp !== undefined) {
				handleErrorResp(resp.responseText);
				//var str = "";
				//for (var i in resp) {
				//	if (str.length > 0) str += ",\n";
				//	str += i + ": " + resp[i];
				//}
				//alert(str);
			}
		};

		openhmis.getQueryStringParameter = function (name) {
			name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
			var regexS = "[\\?&]" + name + "=([^&#]*)";
			var regex = new RegExp(regexS);
			var results = regex.exec(window.location.search);
			if (results == null)
				return "";
			else
				return decodeURIComponent(results[1].replace(/\+/g, " "));
		};

		openhmis.addQueryStringParameter = function (queryString, parameter) {
			return queryString ? queryString + "&" + parameter : parameter;
		};

		openhmis.padZero = function (n) {
			return n < 10 ? "0" + n : n;
		};

		openhmis.pad2Zeros = function (n) {
			if (n < 100) n = '0' + n;
			if (n < 10) n = '0' + n;
			return n;
		};

		openhmis.dateFormat = function (date, includeTime) {
			if(date == null) {
				return null;
			}

			if (typeof date === "string") {
				date = new Date(date);
			}

			var padZero = openhmis.padZero;
			var day = date.getDate();
			var month = date.getMonth() + 1;
			var year = date.getFullYear();
			day = padZero(day);
			month = padZero(month);
			var strDate = day + '-' + month + '-' + year;
			if (includeTime === true) {
				strDate += " " + padZero(date.getHours())
					+ ":" + padZero(date.getMinutes());
			}
			return strDate;
		};

		openhmis.dateFormatWithSeconds = function (date) {
			if (typeof date === "string") {
				date = new Date(date);
			}

			var padZero = openhmis.padZero;
			var day = date.getDate();
			var month = date.getMonth() + 1;
			var year = date.getFullYear();
			day = padZero(day);
			month = padZero(month);
			var hours = padZero(date.getHours());
			var minutes = padZero(date.getMinutes());
			var seconds= padZero(date.getSeconds());
			return day + '-' + month + '-' + year + " " + hours + ":" + minutes + ":" + seconds;
		};

		openhmis.dateFormatLocale = function (date) {
			if (typeof date === "string") {
				date = new Date(date);
			}

			return date ? date.toLocaleDateString() : "";
		};

		openhmis.dateTimeFormatLocale = function (date) {
			if (typeof date === "string") {
				date = new Date(date);
			}

			return date ? date.toLocaleString() : "";
		};

		openhmis.timeFormatLocale = function(date) {
			if (typeof date === "string") {
				date = new Date(date);
			}

			return date ? date.toLocaleTimeString() : "";
		};

		openhmis.iso8601Date = function (d) {
			var padZero = openhmis.padZero;
			var pad2Zeros = openhmis.pad2Zeros;
			return d.getUTCFullYear() + '-' + padZero(d.getUTCMonth() + 1) + '-' + padZero(d.getUTCDate()) + 'T' + padZero(d.getUTCHours()) + ':' + padZero(d.getUTCMinutes()) + ':' + padZero(d.getUTCSeconds()) + '.' + pad2Zeros(d.getUTCMilliseconds()) + '+0000';
		};

		openhmis.tryParsingFuzzyDate = function (fuzzyString) {
			var numberOfSomething = /^([0-9]+)\s?(\w+)(\s+.*)?$/;
			var matches = fuzzyString.match(numberOfSomething);
			var number;
			if (matches && matches[2] && !isNaN(number = parseInt(matches[1]))) {
				matches[1] = number;
				return matches;
			}
			return null;
		};

		openhmis.toFuzzyDate = function (seconds) {
			var timeChunks = [
				[31536000, __("year")],
				[604800, __("week")],
				[86400, __("day")]
			];
			for (var i in timeChunks) {
				var chunk = timeChunks[i]
				var numberOfChunks;
				if ((numberOfChunks = Math.floor(seconds / chunk[0])) >= 1) {
					var string = numberOfChunks === 1
						? __("%d %s", numberOfChunks, chunk[1])
						: __("%d %s", numberOfChunks, openhmis.pluralize(chunk[1]));
					var remainder = seconds % chunk[0];
					if (remainder > 0)
						return string + " " + openhmis.toFuzzyDate(remainder);
					else
						return string;
				}
			}
			return null;
		};

		openhmis.fromFuzzyDate = function (fuzzyString, carry) {
			var timeChunks = [
				["year", 31536000],
				["week", 604800],
				["day", 86400]
			];
			var matches = openhmis.tryParsingFuzzyDate($.trim(fuzzyString))
			if (matches) {
				for (var i in timeChunks) {
					var chunk = timeChunks[i];
					if (matches[2] === chunk[0] || matches[2] === (chunk[0] + "s")) {
						var seconds = matches[1] * chunk[1];
						if (matches[3])
							return openhmis.fromFuzzyDate(matches[3], seconds + (carry || 0));
						else
							return seconds + (carry || 0);
					}
				}
			}

			return carry;
		};

		openhmis.validationMessage = function (parentEl, message, inputEl) {
			if ($(parentEl).length > 1) parentEl = $(parentEl)[0];
			if ($(parentEl).find('.validation').length > 0) return;
			var prevPosition = $(parentEl).css("position");
			$(parentEl).css("position", "relative");
			var el = $('

');
			el.text(message);
			$(parentEl).append(el);
			if (inputEl !== undefined) $(inputEl).focus();
			setTimeout(function () {
				$(el).remove();
				if (prevPosition !== "static")
					$(parentEl).css("position", prevPosition);
			}, 5000);
		};

		openhmis.round = function (val, nearest, mode) {
			nearest = nearest ? nearest : 1;
			if (nearest === 0) return val;
			var factor = 1 / nearest;
			switch (mode) {
				case 'FLOOR':
					return Math.floor(val * factor) / factor;
				case 'CEILING':
					return Math.ceil(val * factor) / factor;
				default:
					return Math.round(val * factor) / factor;
			}
		};

		openhmis.isNumeric = function (n) {
			return !isNaN(parseFloat(n)) && isFinite(n);
		};

		openhmis.toCamelCase = function (str, firstCapital) {
			firstCapital = firstCapital !== undefined ? firstCapital : false;
			str.replace(
				/\b(\S)(\S*)/g,
				function (match, first, rest) {
					return first.toUpperCase() + rest.toLowerCase();
				}
			);
			if (!firstCapital)
				str = str.charAt(0).toLowerCase() + str.substring(1);
			return str;
		};

		// Use uuid for id
		Backbone.Model.prototype.idAttribute = 'uuid';

		/**
		 * Template helper function
		 *
		 * Fetches a template from a remote URI unless it has been previously fetched
		 * and cached.
		 */
		Backbone.View.prototype.tmplFileRoot = openhmis.url.resources;
		Backbone.View.prototype.getTemplate = function(tmplFile, tmplSelector) {
			tmplFile = tmplFile ? tmplFile : this.tmplFile;
			tmplSelector = tmplSelector ? tmplSelector : this.tmplSelector;
			var view = this;
			if (openhmis.templates[tmplFile] === undefined) {
				var uri = view.tmplFileRoot === undefined ? tmplFile : view.tmplFileRoot + tmplFile;
				$.ajax({
					url: uri,
					async: false,
					dataType: "html",
					success: function(data, status, jq) {
						openhmis.templates[tmplFile] = $("
").html(data);
					}
				});
			}

			var template = _.template($(openhmis.templates[tmplFile]).find(tmplSelector).html());
			var augmentedTemplate = function(context) {
				if (context !== undefined) {
					context.__ = context.__ ? context.__ : __;
					context.urls = context.urls ? context.urls : openhmis.url;
					context.helpers = context.helpers ? context.helpers : Backbone.Form.helpers
					context.pluralize = openhmis.pluralize;
				}

				return template.call(this, context);
			};

			return augmentedTemplate;
		};

		return openhmis;
	}
);
<|endoftext|>


<commit_before>QB.init(QBApp.appId, QBApp.authKey, QBApp.authSecret, true);

$(document).ready(function(){

QB.createSession(QBUser, function(err, result) {
	var token = result.token;
		user_id = result.id;
		uploadPages = 0;
		filesCount = 0;
		finished = false;

	if (err) {
		console.log('Something went wrong: ' + err);
	} else {
		console.log('Session created with id ' + result.id);

		uploadingFiles(token);

		// uploading files scroll event
		$(window).scroll(function() {
			if  ($(window).scrollTop() == $(document).height() - $(window).height())
			{
				uploadingFiles(token);
			}
		});

		// loading image click event
		$("#loading-btn").click(function(e){
			e.preventDefault();

			var inputFile = $("input[type=file]")[0].files[0];
			console.log(inputFile);
				if (inputFile) {
					$("#progress").show(0);
				}
			// uploading image
			QB.content.createAndUpload({name: inputFile.name, file: inputFile, type: inputFile.type, size: inputFile.size, 'public': true}, function(err, response){
				if (err) {
					console.log(err);
				} else {
					console.log(response);
					$("#progress").fadeOut(400);

					var uploadedFile = response;

					insertImage(uploadedFile.id, uploadedFile.name, token, false);
				}
			});

		});
	}
});
});
// add images
function insertImage(fileId, fileName, token, toAppend){
	var imageHTML = "";
	if (toAppend) {
		$('#pictures').append(imageHTML);
		console.log(token);
	} else {
		$('#pictures').prepend(imageHTML);
	}
}
// get content files
function uploadingFiles(token) {
	if (finished != true) {
		$("#loadwnd").show(0);
		uploadPages = uploadPages + 1;

		QB.content.list({page: uploadPages, per_page: '9'}, function(error, response) {
		$.each(response.items, function(index, item){
			var cur = this.blob;

			insertImage(cur.id, cur.name, token, true);
		});
			if (error) {
				console.log(error);
			} else {
				console.log(response);
				$("#loadwnd").delay(1000).fadeOut(1000);
			}

			var totalEntries = response.total_entries;
				entries = response.items.length;
				filesCount = filesCount + entries;

			if (filesCount >= totalEntries) {
				finished = true;
			}
		});
	}
}<commit_msg>refactored a bit<commit_after>QB.init(QBApp.appId, QBApp.authKey, QBApp.authSecret, true);

$(document).ready(function(){

QB.createSession(QBUser, function(err, result) {
	if (err) {
		console.log('Something went wrong: ' + err);
	} else {
		var token = result.token;
			user_id = result.id;
			uploadPages = 0;
			filesCount = 0;
			finished = false;

		console.log('Session created with id ' + result.id);

		retrieveFiles(token);

		// uploading files scroll event
		$(window).scroll(function() {
			if  ($(window).scrollTop() == $(document).height() - $(window).height()){
				retrieveFiles(token);
			}
		});

		// loading image click event
		$("#loading-btn").click(function(e){
			e.preventDefault();

			var inputFile = $("input[type=file]")[0].files[0];
			console.log(inputFile);
			if (inputFile) {
				$("#progress").show(0);
			}

			// uploade image
			QB.content.createAndUpload({name: inputFile.name, file: inputFile, type: inputFile.type, size: inputFile.size, 'public': false}, function(err, response){
				if (err) {
					console.log(err);
				} else {
					console.log(response);

					$("#progress").fadeOut(400);

					var uploadedFile = response;

					showImage(uploadedFile.id, uploadedFile.name, token, false);
				}
			});
		});
	}
});
});

// show image
function showImage(fileId, fileName, token, toAppend){
	var imageHTML = "";
	if (toAppend) {
		$('#pictures').append(imageHTML);
		console.log(token);
	} else {
		$('#pictures').prepend(imageHTML);
	}
}

// get content files
function retrieveFiles(token) {
	if (finished != true) {
		$("#loadwnd").show(0);
		uploadPages = uploadPages + 1;

		QB.content.list({page: uploadPages, per_page: '9'}, function(error, response) {
			if (error) {
				console.log(error);
			} else {
				$.each(response.items, function(index, item){
					var cur = this.blob;
					showImage(cur.id, cur.name, token, true);
				});

				console.log(response);
				$("#loadwnd").delay(1000).fadeOut(1000);

				var totalEntries = response.total_entries;
				entries = response.items.length;
				filesCount = filesCount + entries;

				if (filesCount >= totalEntries) {
					finished = true;
				}
			}
		});
	}
}<|endoftext|>


<commit_before>define(['jquery'], function ($) {
    var publishNotebook = function() {
        var anacondacloudid = IPython.notebook.metadata.anacondaCloudID,
            notebookName = IPython.notebook.notebook_name,
            nbj = IPython.notebook.toJSON(),
            interval;

        if (!IPython.notebook) return;
        $.ajax({
            url: "/ac-publish",
            method: 'POST',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            processData: false,
            data: JSON.stringify({
                name: notebookName,
                content: nbj
            })
        }).done(function(data) {
            IPython.notification_area.get_widget("notebook").
                set_message("Your notebook has been uploaded.", 4000);
        }).fail(function(jqXHR, textStatus) {
            var msg = '';
            if (jqXHR.status == 401) {
                msg = 'You must login though anaconda client.';
            } else {
                msg = 'There has been a problem. Try again.';
            }
            IPython.notification_area.get_widget("notebook").
                danger(msg, 4000);
        }).always(function(data, textStatus) {
            clearInterval(interval);
        });
        interval = uploadingNotification();
    };

    var uploadingNotification = function() {
        var index = 0,
            pattern = ['-', '\\', '|', '/'],
            _updateString = function(i) {
                IPython.notification_area.
                    get_widget('notebook').
                    warning('Uploading ' + pattern[i]);
            }
        _updateString(index);
        return setInterval(function() {
            index+=1;
            if (index > 3) { index = 0 };
            _updateString(index);
        }, 250);
    };

    var updateUploadLink = function(anacondaCloudID) {
        if (!IPython.notebook) return;
        if (!anacondaCloudID) {
            anacondaCloudID = IPython.notebook.metadata.anacondaCloudID;
        } else {
            IPython.notebook.metadata.anacondaCloudId = anacondaCloudID;
        }
        if (!anacondaCloudID) {
            return;
        }
        var toolbar = IPython.toolbar.element;
        var link = toolbar.find("a#nbviewer");
        if (!link.length) {
            link = $('');
            toolbar.append(
                $('').append(link)
            );
        }
        link.attr("href", "http://notebooks.anaconda.org/" + anacondaCloudID);
        link.text("http://notebooks.anaconda.org/" + anacondaCloudID);
    };

    var publishButton = function() {
        if (!IPython.toolbar) {
            $([IPython.events]).on("app_initialized.NotebookApp", publishButton);
            return;
        }
        if ($("#publish_notebook").length === 0) {
            IPython.toolbar.add_buttons_group([
                {
                    'label'   : 'Publish your notebook into Anaconda.org',
                    'icon'    : 'fa-cloud-upload',
                    'callback': publishNotebook,
                    'id'      : 'publish_notebook'
                },
            ]);
        }
        updateUploadLink();
    };

    var load_ipython_extension = function () {
        publishButton();
    };

    return {
        load_ipython_extension : load_ipython_extension,
    };
});
<commit_msg>Save notebook and show link<commit_after>define(['jquery'], function ($) {
    var publishNotebook = function() {
        var anacondacloudid = IPython.notebook.metadata.anacondaCloudID,
            notebookName = IPython.notebook.notebook_name,
            nbj = IPython.notebook.toJSON(),
            interval;

        if (!IPython.notebook) return;
        $.ajax({
            url: "/ac-publish",
            method: 'POST',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            processData: false,
            data: JSON.stringify({
                name: notebookName,
                content: nbj
            })
        }).done(function(data) {
            IPython.notification_area.get_widget("notebook").
                set_message("Your notebook has been uploaded.", 4000);
            updateUploadLink(data.url);
        }).fail(function(jqXHR, textStatus) {
            var msg = '';
            if (jqXHR.status == 401) {
                msg = 'You must login though anaconda client.';
            } else {
                msg = 'There has been a problem. Try again.';
            }
            IPython.notification_area.get_widget("notebook").
                danger(msg, 4000);
        }).always(function(data, textStatus) {
            clearInterval(interval);
        });
        interval = uploadingNotification();
    };

    var uploadingNotification = function() {
        var index = 0,
            pattern = ['-', '\\', '|', '/'],
            _updateString = function(i) {
                IPython.notification_area.
                    get_widget('notebook').
                    warning('Uploading ' + pattern[i]);
            }
        _updateString(index);
        return setInterval(function() {
            index+=1;
            if (index > 3) { index = 0 };
            _updateString(index);
        }, 250);
    };

    var updateUploadLink = function(anacondaCloudURL) {
        if (!IPython.notebook) return;
        if (!anacondaCloudURL) {
            anacondaCloudURL = IPython.notebook.metadata.anacondaCloudURL;
        } else {
            IPython.notebook.metadata.anacondaCloudURL = anacondaCloudURL;
        }
        if (!anacondaCloudURL) {
            return;
        }
        var toolbar = IPython.toolbar.element;
        var link = toolbar.find("a#nbviewer");
        if (!link.length) {
            link = $('');
            toolbar.append(
                $('').append(link)
            );
        }
        link.attr("href", + anacondaCloudURL);
        link.text(anacondaCloudURL);
        IPython.notebook.save_notebook();
    };

    var publishButton = function() {
        if (!IPython.toolbar) {
            $([IPython.events]).on("app_initialized.NotebookApp", publishButton);
            return;
        }
        if ($("#publish_notebook").length === 0) {
            IPython.toolbar.add_buttons_group([
                {
                    'label'   : 'Publish your notebook into Anaconda.org',
                    'icon'    : 'fa-cloud-upload',
                    'callback': publishNotebook,
                    'id'      : 'publish_notebook'
                },
            ]);
        }
        updateUploadLink();
    };

    var load_ipython_extension = function () {
        publishButton();
    };

    return {
        load_ipython_extension : load_ipython_extension,
    };
});
<|endoftext|>


<commit_before>var subs = (function () {

var exports = {};

var stream_list_hash = [];

function case_insensitive_subscription_index(stream_name) {
    var i;
    var name = stream_name.toLowerCase();

    for (i = 1; i < stream_list.length; i++) {
        if (name === stream_list[i].toLowerCase()) {
            return i;
        }
    }
    return -1;
}

function add_to_stream_list(stream_name) {
    if (!exports.have(stream_name)) {
        stream_list.push(stream_name);
        stream_list_hash[stream_name.toLowerCase()] = true;
    }
}

function remove_from_stream_list(stream_name) {
    delete stream_list_hash[stream_name.toLowerCase()];
    var removal_index = case_insensitive_subscription_index(stream_name);
    if (removal_index !== -1) {
        stream_list.splice(removal_index, 1);
    }
}

exports.fetch = function () {
    $.ajax({
        type:     'POST',
        url:      'json/subscriptions/list',
        dataType: 'json',
        timeout:  10*1000,
        success: function (data) {
            $('#subscriptions_table tr').remove();
            if (data) {
                $.each(data.subscriptions, function (index, name) {
                    $('#subscriptions_table').append(templates.subscription({subscription: name}));
                });
            }
            $('#streams').focus().select();
        },
        error: function (xhr) {
            report_error("Error listing subscriptions", xhr, $("#subscriptions-status"));
        }
    });
};

function add_for_send_success(stream_name, prompt_button) {
    add_to_stream_list(stream_name);
    compose.finish();
    prompt_button.stop(true).fadeOut(500);
}

exports.add_for_send = function (stream, prompt_button) {
    $.ajax({
        type:     'POST',
        url:      '/json/subscriptions/add',
        data:      {streams: stream},
        dataType: 'json',
        timeout:  10*60*1000, // 10 minutes in ms
        success: function (response) {
            add_for_send_success(response.data, prompt_button);
        },
        error: function (xhr, error_type, exn) {
            if ($.parseJSON(xhr.responseText).msg === "Subscription already exists") {
                // If we're already subscribed, the issue here was
                // actually that the client didn't know we were
                // already subscribed -- so just send the message.
                add_for_send_success(stream, prompt_button);
            } else {
                report_error("Unable to subscribe", xhr, $("#home-error"));
            }
        }
    });
};

exports.have = function (stream_name) {
    return (stream_list_hash[stream_name.toLowerCase()] === true);
};

$(function () {
    var i;
    // Populate stream_list_hash with data handed over to client-side template.
    for (i = 0; i < stream_list.length; i++) {
        stream_list_hash[stream_list[i].toLowerCase()] = true;
    }

    // FIXME: It would be nice to move the UI setup into ui.js.

    $("#current_subscriptions").ajaxForm({
        dataType: 'json', // This seems to be ignored. We still get back an xhr.
        success: function (resp, statusText, xhr, form) {
            var name = $.parseJSON(xhr.responseText).data;
            $('#subscriptions_table').find('button[value="' + name + '"]').parents('tr').remove();
            remove_from_stream_list(name);
            update_autocomplete();
            report_success("Successfully removed subscription to " + name,
                           $("#subscriptions-status"));
        },
        error: function (xhr) {
            report_error("Error removing subscription", xhr, $("#subscriptions-status"));
        }
    });

    $("#add_new_subscription").ajaxForm({
        dataType: 'json', // This seems to be ignored. We still get back an xhr.
        success: function (resp, statusText, xhr, form) {
            $("#streams").val("");
            var name = $.parseJSON(xhr.responseText).data;
            $('#subscriptions_table').prepend(templates.subscription({subscription: name}));
            add_to_stream_list(name);
            report_success("Successfully added subscription to " + name,
                           $("#subscriptions-status"));
            $("#streams").focus();
        },
        error: function (xhr) {
            report_error("Error adding subscription", xhr, $("#subscriptions-status"));
            $("#streams").focus();
        }
    });
});

return exports;

}());
<commit_msg>Don't add duplicate entries to subscriptions_table.<commit_after>var subs = (function () {

var exports = {};

var stream_list_hash = [];

function case_insensitive_subscription_index(stream_name) {
    var i;
    var name = stream_name.toLowerCase();

    for (i = 1; i < stream_list.length; i++) {
        if (name === stream_list[i].toLowerCase()) {
            return i;
        }
    }
    return -1;
}

function add_to_stream_list(stream_name) {
    if (!exports.have(stream_name)) {
        stream_list.push(stream_name);
        stream_list_hash[stream_name.toLowerCase()] = true;
        $('#subscriptions_table').prepend(templates.subscription({subscription: stream_name}));
    }
}

function remove_from_stream_list(stream_name) {
    delete stream_list_hash[stream_name.toLowerCase()];
    var removal_index = case_insensitive_subscription_index(stream_name);
    if (removal_index !== -1) {
        stream_list.splice(removal_index, 1);
    }
}

exports.fetch = function () {
    $.ajax({
        type:     'POST',
        url:      'json/subscriptions/list',
        dataType: 'json',
        timeout:  10*1000,
        success: function (data) {
            $('#subscriptions_table tr').remove();
            if (data) {
                $.each(data.subscriptions, function (index, name) {
                    $('#subscriptions_table').append(templates.subscription({subscription: name}));
                });
            }
            $('#streams').focus().select();
        },
        error: function (xhr) {
            report_error("Error listing subscriptions", xhr, $("#subscriptions-status"));
        }
    });
};

function add_for_send_success(stream_name, prompt_button) {
    add_to_stream_list(stream_name);
    compose.finish();
    prompt_button.stop(true).fadeOut(500);
}

exports.add_for_send = function (stream, prompt_button) {
    $.ajax({
        type:     'POST',
        url:      '/json/subscriptions/add',
        data:      {streams: stream},
        dataType: 'json',
        timeout:  10*60*1000, // 10 minutes in ms
        success: function (response) {
            add_for_send_success(response.data, prompt_button);
        },
        error: function (xhr, error_type, exn) {
            if ($.parseJSON(xhr.responseText).msg === "Subscription already exists") {
                // If we're already subscribed, the issue here was
                // actually that the client didn't know we were
                // already subscribed -- so just send the message.
                add_for_send_success(stream, prompt_button);
            } else {
                report_error("Unable to subscribe", xhr, $("#home-error"));
            }
        }
    });
};

exports.have = function (stream_name) {
    return (stream_list_hash[stream_name.toLowerCase()] === true);
};

$(function () {
    var i;
    // Populate stream_list_hash with data handed over to client-side template.
    for (i = 0; i < stream_list.length; i++) {
        stream_list_hash[stream_list[i].toLowerCase()] = true;
    }

    // FIXME: It would be nice to move the UI setup into ui.js.

    $("#current_subscriptions").ajaxForm({
        dataType: 'json', // This seems to be ignored. We still get back an xhr.
        success: function (resp, statusText, xhr, form) {
            var name = $.parseJSON(xhr.responseText).data;
            $('#subscriptions_table').find('button[value="' + name + '"]').parents('tr').remove();
            remove_from_stream_list(name);
            update_autocomplete();
            report_success("Successfully removed subscription to " + name,
                           $("#subscriptions-status"));
        },
        error: function (xhr) {
            report_error("Error removing subscription", xhr, $("#subscriptions-status"));
        }
    });

    $("#add_new_subscription").ajaxForm({
        dataType: 'json', // This seems to be ignored. We still get back an xhr.
        success: function (resp, statusText, xhr, form) {
            $("#streams").val("");
            var name = $.parseJSON(xhr.responseText).data;
            add_to_stream_list(name);
            report_success("Successfully added subscription to " + name,
                           $("#subscriptions-status"));
            $("#streams").focus();
        },
        error: function (xhr) {
            report_error("Error adding subscription", xhr, $("#subscriptions-status"));
            $("#streams").focus();
        }
    });
});

return exports;

}());
<|endoftext|>


<commit_before>window.ChannelView = Backbone.View.extend({

  el: $("#main-wrapper"),
  tmpl: $('#channel_overview').html(),

  initialize: function(opts) {
  },

  setChannel: function(channel) {
    this.channel = channel;

    return this;
  },

  render: function() {
    var self = this;

    if ( self.channel ) {
      self.channel.trigger('loading');

      this.$( this.el )
        .html( $.mustache(this.tmpl, this.channel.toJSON() ));
      if ( this.jqXHR ) {
        this.jqXHR.abort();
      }

      this.jqXHR = $.ajax({
        url: self.channel.url() + '/facts',
        method: "GET",
        success: function( data ) {
          self.el.find('#facts_for_channel > div.loading').hide().parent().append(data);
          self.el.find('.fact-block').factlink();

          self.channel.trigger('loaded')
                      .trigger('activate', self.channel);
        }
      });
    }

    return this;
  }
});

<commit_msg>Replaced loading indicators, left side spinner now only shows while loading the template<commit_after>window.ChannelView = Backbone.View.extend({

  el: $("#main-wrapper"),
  tmpl: $('#channel_overview').html(),

  initialize: function(opts) {
  },

  setChannel: function(channel) {
    this.channel = channel;

    return this;
  },

  render: function() {
    var self = this;

    if ( self.channel ) {
      self.channel.trigger('loading');

      this.$( this.el )
        .html( $.mustache(this.tmpl, this.channel.toJSON() ));

      self.channel.trigger('loaded')
                  .trigger('activate', self.channel);

      if ( this.jqXHR ) {
        this.jqXHR.abort();
      }

      this.jqXHR = $.ajax({
        url: self.channel.url() + '/facts',
        method: "GET",
        success: function( data ) {
          self.el.find('#facts_for_channel > div.loading').hide().parent().append(data);
          self.el.find('.fact-block').factlink();
        }
      });
    }

    return this;
  }
});

<|endoftext|>


<commit_before>//TODO: refactor hardcoded dates //former FIXME
//TODO: remove date formatting from here //former FIXME

define([
    'lodash',
    'd3',
    'base/tool'
], function(_, d3, Tool) {

    var bubbleChart = Tool.extend({
        /**
         * Initialized the tool
         * @param config tool configurations, such as placeholder div
         * @param options tool options, such as state, data, etc
         */
        init: function(config, options) {

            this.name = 'bubble-chart';
            this.template = "tools/_examples/bubble-chart/bubble-chart";

            //instantiating components
            this.components = [{
                component: '_gapminder/header',
                placeholder: '.vzb-tool-title'
            }, {
                component: '_examples/bubble-chart',
                placeholder: '.vzb-tool-viz', //div to render
                model: ["state.time", "state.entities", "state.marker", "data"]
            }, {
                component: '_gapminder/timeslider',
                placeholder: '.vzb-tool-timeslider', //div to render
                model: ["state.time"]
            }, {
                component: '_gapminder/buttonlist',
                placeholder: '.vzb-tool-buttonlist',
                model: ['state', 'data'],
                buttons: ['colors', 'size', 'more-options']
            }];

            this._super(config, options);

        },

        /**
         * Validating the tool model
         * @param model the current tool model to be validated
         */
        toolModelValidation: function(model) {

            var time = model.state.time,
                markers = model.state.marker.label;

            //don't validate anything if data hasn't been loaded
            if (!markers.getItems() || markers.getItems().length < 1) {
                return;
            }

            var dateMin = markers.getLimits('time').min,
                dateMax = markers.getLimits('time').max;

            if (time.start < dateMin) {
                time.start = dateMin;
            }
            if (time.end > dateMax) {
                time.end = dateMax;
            }
        }
    });

    return bubbleChart;
});<commit_msg>remove irrelevant TODOs<commit_after>define([
    'lodash',
    'd3',
    'base/tool'
], function(_, d3, Tool) {

    var bubbleChart = Tool.extend({
        /**
         * Initialized the tool
         * @param config tool configurations, such as placeholder div
         * @param options tool options, such as state, data, etc
         */
        init: function(config, options) {

            this.name = 'bubble-chart';
            this.template = "tools/_examples/bubble-chart/bubble-chart";

            //instantiating components
            this.components = [{
                component: '_gapminder/header',
                placeholder: '.vzb-tool-title'
            }, {
                component: '_examples/bubble-chart',
                placeholder: '.vzb-tool-viz', //div to render
                model: ["state.time", "state.entities", "state.marker", "data"]
            }, {
                component: '_gapminder/timeslider',
                placeholder: '.vzb-tool-timeslider', //div to render
                model: ["state.time"]
            }, {
                component: '_gapminder/buttonlist',
                placeholder: '.vzb-tool-buttonlist',
                model: ['state', 'data'],
                buttons: ['colors', 'size', 'more-options']
            }];

            this._super(config, options);

        },

        /**
         * Validating the tool model
         * @param model the current tool model to be validated
         */
        toolModelValidation: function(model) {

            var time = model.state.time,
                markers = model.state.marker.label;

            //don't validate anything if data hasn't been loaded
            if (!markers.getItems() || markers.getItems().length < 1) {
                return;
            }

            var dateMin = markers.getLimits('time').min,
                dateMax = markers.getLimits('time').max;

            if (time.start < dateMin) {
                time.start = dateMin;
            }
            if (time.end > dateMax) {
                time.end = dateMax;
            }
        }
    });

    return bubbleChart;
});
<|endoftext|>