<commit_before>Alert = {
    open: function (input, options) {
        // Default key
        var prefix  = 'error.';
        var title   = prefix + 'default.title';
        var text    = prefix + 'default.text';
        var type    = 'error';

        // Getting keys
        if (!_.isUndefined(input) && isError(input)) {
            prefix  = 'error.';
            type    = 'error';
            input   = input.error;
            title   = prefix + input + '.title';
            text    = prefix + input + '.text';
        } else if (!_.isUndefined(input) && _.isString(input)) {
            prefix  = null;
            type    = getType(input);
            title   = input + '.title';
            text    = input + '.text';
        }

        // Forging data object
        var data = {
            title:  title   === __(title)   ? input : __(title),
            text:   text    === __(text)    ? null  : __(text),
            type:   type
        };

        // Extending from the options
        if (!_.isUndefined(options)) {
            _.extend(data, options);
        }

        // Opening SweetAlert
        swal(data);
    }
};

function isError (input) {
    return _.isObject(input) && _.has(input, 'error');
}

function getType (input) {
    var type = _.isString(input) ? _.first(input.split('.')) : null;
    if (!type || (type !== 'error' && type !== 'info' && type !== 'success' && type !== 'warning')) {
        type = null;
    }

    return type
}
<commit_msg>Light refactoring<commit_after>Alert = {
    open: function (input, options) {
        var prefix;
        var title;
        var text;
        var type;

        // Getting keys
        if (!_.isUndefined(input) && isError(input)) {
            prefix  = 'error.';
            type    = 'error';
            input   = input.error;
            title   = prefix + input + '.title';
            text    = prefix + input + '.text';
        } else if (!_.isUndefined(input) && _.isString(input)) {
            prefix  = null;
            type    = getType(input);
            title   = input + '.title';
            text    = input + '.text';
        } else {
            prefix  = 'error.';
            title   = prefix + 'default.title';
            text    = prefix + 'default.text';
            type    = 'error';
        }

        // Forging data object
        var data = {
            title:  title   === __(title)   ? input : __(title),
            text:   text    === __(text)    ? null  : __(text),
            type:   type
        };

        // Extending from the options
        if (!_.isUndefined(options)) {
            _.extend(data, options);
        }

        // Opening SweetAlert
        swal(data);
    }
};

function isError (input) {
    return _.isObject(input) && _.has(input, 'error');
}

function getType (input) {
    var type = _.isString(input) ? _.first(input.split('.')) : null;
    if (!type || (type !== 'error' && type !== 'info' && type !== 'success' && type !== 'warning')) {
        type = null;
    }

    return type;
}
<|endoftext|>


<commit_before>var _merge = require('lodash-node/modern/objects/merge');
var data = {
    'ncaa-mens-basketball': {
        '2012': require('./ncaa-mens-basketball/2012.json'),
        '2013': require('./ncaa-mens-basketball/2013.json'),
        'defaults': require('./ncaa-mens-basketball/defaults.json')
    },
    'ncaa-mens-hockey': {
        '2013': require('./ncaa-mens-hockey/2013.json'),
        'defaults': require('./ncaa-mens-hockey/defaults.json')
    }
};

module.exports = function (sport, year) {
    var defaultData = data[sport] && data[sport].defaults || {};
    var yearData = data[sport] && data[sport][year];

    if (yearData) {
        return _merge(defaultData, yearData);
    } else {
        throw new Error('The combination of ' + sport + ' and ' + year + ' does not exist.');
    }
};
<commit_msg>walkdir<commit_after>var _merge = require('lodash-node/modern/objects/merge');
var _each = require('lodash-node/modern/collections/forEach');
var _filter = require('lodash-node/modern/collections/filter');
var _groupBy = require('lodash-node/modern/collections/groupBy');
var data = {};
var path = require('path');
var walkdir = require('walkdir');
var dataPaths = walkdir.sync('./data');
var dataFiles = _filter(dataPaths, function (dataPath) {
    return path.extname(dataPath) === '.json' && path.basename(dataPath, '.json') !== 'defaults';
});
dataFiles = _groupBy(dataFiles, function (dataPath) {
    return path.basename(path.dirname(dataPath));
});

_each(dataFiles, function (files, sport) {
    data[sport] || (data[sport] = {});
    data[sport].defaults = require('./' + sport + '/defaults');
    _each(files, function (file) {
        var year = path.basename(file, '.json');
        data[sport][year] = require('./' + sport + '/' + year);
    });
});

module.exports = function (sport, year) {
    var defaultData = data[sport] && data[sport].defaults || {};
    var yearData = data[sport] && data[sport][year];

    if (yearData) {
        return _merge(defaultData, yearData);
    } else {
        throw new Error('The combination of ' + sport + ' and ' + year + ' does not exist.');
    }
};
<|endoftext|>


<commit_before>/**
 * This is where the setup for the calculator happens. It's all inside an
 * anonymous function, so the vars and the functions will go away at the end.
 */

/*global calculator:false , localStorage:false*/

(function () {

    'use strict';

    var numbers, operators, i, k;

    // First, create click handlers for the buttons

    /**
     * bundNum takes a number button dom element, and attaches calc's
     * enterNumber method to its click event
     *
     * @param {Object}
     *            obj is a dom node of a number button
     * @return {Boolean} just true
     */
    function bindNum(obj) {
        obj.onclick = function () {
            calculator.enterNumber(this.value); // 'this' is obj (a num btn)
        };

        return true;
    }

    /**
     * bundOpp takes a function button dom element, and attaches calc's
     * enterOperator method to its click event
     *
     * @param {Object} obj is a dom node of a function button
     * @return {Boolean} just true
     */
    function bindOpp(obj) {
        obj.onclick = function () {
            calculator.enterOperator(this.value); // 'this' is obj (a fn btn)
        };

        return true;
    }

    // Second, run setup routine, in which page elements are bound to
    // calculator methods.

    // Start by calling the calcuator's init method, passing
    // in an output element to be the display.

    /*jslint browser:true*/

    calculator.setDisplay(document.getElementById('out'));

    // Move onto binding the numbers' click
    // event to the calculator's update method.

    numbers = document.getElementsByClassName('number');

    for (i = 0; i < numbers.length; i += 1) {

        // clicking a number will update the display and
        // the temp variable

        bindNum(numbers[i]);
    }

    operators = document.getElementsByClassName('operator');

    for (k = 0; k < operators.length; k += 1) {

        // clicking an operator will make the calculator
        // perform an operation.

        bindOpp(operators[k]);

    }

    // lastly, bind the clear function to the clear buttons' click event

    document.getElementById('clear').onclick = function () {
        calculator.clear();
    };

    /**
     * Try to install app from firefox if it is not already installed.
     *
     * Note that I have no error handlers, and only handle the first success,
     * because there is nothing to be done in other cases. To do this, the
     * special firefox function and localStorage need to be available.
     *
     * From https://developer.mozilla.org/en-US/docs/DOM/Apps.getSelf Note: Due
     * to Bug 806597, request.result incorrectly returns null even when an app
     * is running on Desktop and Firefox for Android.
     *
     * Because of this bug, I will defer to a flag that I will set in
     * localStorage to inform me if the app is already installed.
     */
    (function () {

        var request, req2;

        if (typeof navigator.mozApps.getSelf === 'function'
                && typeof navigator.mozApps.install === 'function'
                && localStorage
                && localStorage.getItem('alreadyInstalled') !== '1') {

            request = navigator.mozApps.getSelf();

            request.onsuccess = function () {
                // not installed yet, try to
                if (!request.result) {

                    req2 = navigator.mozApps.install(location.protocol + '//' + location.host
                            + '/manifest.webapp');

                    req2.onsuccess = function () {
                        localStorage.setItem('alreadyInstalled', '1');
                    };

                } // otherwise the app is either already installed or cannot
                  // be, so do nothing
            };
        }
    }());

}()); // end the anonymous init function, and invoke it<commit_msg>put agpl stuff at top of setup file<commit_after>/**
 * This is where the setup for the calculator happens. It's all inside an
 * anonymous function, so the vars and the functions will go away at the end.
 *
 * This file is part of Abacus For The Rest Of Us Copyright (C) 2013 Max
 * Galloway-Carson
 *
 * Abacus For The Rest Of Us is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http:*www.gnu.org/licenses/>.
 *
 * email me at: maxvgc@gmail.com
 * source code: https://github.com/maxvgc/abacus-for-the-rest-of-us
 */

/*global calculator:false , localStorage:false*/

(function () {

    'use strict';

    var numbers, operators, i, k;

    // First, create click handlers for the buttons

    /**
     * bundNum takes a number button dom element, and attaches calc's
     * enterNumber method to its click event
     *
     * @param {Object}
     *            obj is a dom node of a number button
     * @return {Boolean} just true
     */
    function bindNum(obj) {
        obj.onclick = function () {
            calculator.enterNumber(this.value); // 'this' is obj (a num btn)
        };

        return true;
    }

    /**
     * bundOpp takes a function button dom element, and attaches calc's
     * enterOperator method to its click event
     *
     * @param {Object} obj is a dom node of a function button
     * @return {Boolean} just true
     */
    function bindOpp(obj) {
        obj.onclick = function () {
            calculator.enterOperator(this.value); // 'this' is obj (a fn btn)
        };

        return true;
    }

    // Second, run setup routine, in which page elements are bound to
    // calculator methods.

    // Start by calling the calcuator's init method, passing
    // in an output element to be the display.

    /*jslint browser:true*/

    calculator.setDisplay(document.getElementById('out'));

    // Move onto binding the numbers' click
    // event to the calculator's update method.

    numbers = document.getElementsByClassName('number');

    for (i = 0; i < numbers.length; i += 1) {

        // clicking a number will update the display and
        // the temp variable

        bindNum(numbers[i]);
    }

    operators = document.getElementsByClassName('operator');

    for (k = 0; k < operators.length; k += 1) {

        // clicking an operator will make the calculator
        // perform an operation.

        bindOpp(operators[k]);

    }

    // lastly, bind the clear function to the clear buttons' click event

    document.getElementById('clear').onclick = function () {
        calculator.clear();
    };

    /**
     * Try to install app from firefox if it is not already installed.
     *
     * Note that I have no error handlers, and only handle the first success,
     * because there is nothing to be done in other cases. To do this, the
     * special firefox function and localStorage need to be available.
     *
     * From https://developer.mozilla.org/en-US/docs/DOM/Apps.getSelf Note: Due
     * to Bug 806597, request.result incorrectly returns null even when an app
     * is running on Desktop and Firefox for Android.
     *
     * Because of this bug, I will defer to a flag that I will set in
     * localStorage to inform me if the app is already installed.
     */
    (function () {

        var request, req2;

        if (typeof navigator.mozApps.getSelf === 'function'
                && typeof navigator.mozApps.install === 'function'
                && localStorage
                && localStorage.getItem('alreadyInstalled') !== '1') {

            request = navigator.mozApps.getSelf();

            request.onsuccess = function () {
                // not installed yet, try to
                if (!request.result) {

                    req2 = navigator.mozApps.install(location.protocol + '//' + location.host
                            + '/manifest.webapp');

                    req2.onsuccess = function () {
                        localStorage.setItem('alreadyInstalled', '1');
                    };

                } // otherwise the app is either already installed or cannot
                  // be, so do nothing
            };
        }
    }());

}()); // end the anonymous init function, and invoke it<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');

function FSCache(config) {
    config = config || {};

    this.cacheRoot = path.resolve(config.cacheRoot || './cache');
    this.pathifyFn = config.pathify || this.relativePathify.bind(this);
    this.verbose = config.verbose || false;
    // cache module required config values
    this.type = config.type || 'file-system';
    this.defaultExpiration = config.defaultExpiration || 900;
    this.checkOnPreviousEmpty = config.checkOnPreviousEmpty || true;
    this.readOnly = config.readOnly || false;
}

// === cache-service API (public) ===

FSCache.prototype.get = function get(key, callback) {
    var self = this;
    log(self, 'get() called', { key: key });
    var name = fullPathify(this, key);
    fs.readFile(name, (err, data) => {
        var result = null;
        if (err) {
            error(self, 'get() read error', { key: key, err: err });
        } else {
            try {
                result = JSON.parse(data.toString());
                // TODO: have to check to see if the data has expired!
                if (result.expires > 0 && result.expires <= Date.now()) {
                    log(self, 'get() data has expired!', { key: key })
                    throw 'data has expired';
                    result = null;
                } else {
                    result = result.data;
                }
            } catch (err) {
                error(self, 'get() JSON error', { key: key, err: err })
            }
        }
        callback(err, result);
    });
};

FSCache.prototype.mget = function mget(keys, callback) {
    var self = this;
    log(self, 'mget() called', { keys: keys });
    var result = {};
    var errors = [];
    var done = 0;
    for (const key of keys) {
        self.get(key, (err, obj) => {
            if (err) {
                error(self, 'mget() error on key', { key: key, err: err })
                errors.push({ key: key, err: err });
            } else {
                result[key] = obj;
            }
            done++;
            if (done === keys.length) {
                callback(null, result);
            }
        });
    }
};

FSCache.prototype.set = function set(key, value, expiration, refresh, callback) {
    var self = this;
    log(self, 'set() called', { key: key, value: value });
    if (arguments.length === 3 && typeof expiration === 'function') {
        callback = expiration;
        expiration = self.defaultExpiration;
    } else if (arguments.length === 4) {
        callback = refresh;
        if (typeof expiration === 'function') {
            refresh = expiration;
            expiration = self.defaultExpiration;
        }
    }
    callback = callback || noop;
    var filePath = fullPathify(self, key);
    // UTC expiration in milliseconds, zero means "never expires".
    var expires = expiration > 0 ? Date.now() + (expiration * 1000) : 0;
    var cacheData = {
        expires: expires,
        data: value,
    };
    var data = JSON.stringify(cacheData);
    mkdirp(path.dirname(filePath), err => {
        fs.writeFile(filePath, data, err => {
            error(self, 'set() error', { key: key, err: err });
            callback(err);
        });
    });
};

FSCache.prototype.mset = function mset(obj, expiration, callback) {
    var self = this;
    log(self, 'mset() called', { obj: obj });
    if (arguments.length === 2 && typeof expiration === 'function') {
        callback = expiration;
        expiration = self.defaultExpiration;
    }
    callback = callback || noop;
    var keys = obj.keys();
    var errors = [];
    var done = 0;
    for (const key of keys) {
        // TODO: see if obj[key] has a cacheValue property?
        self.set(key, obj[key], expiration, err => {
            if (err) {
                error(self, 'mget() error on key', { key: key, err: err })
                errors.push({ key: key, err: err });
            }
            done++;
            if (done === keys.length) {
                callback(null);
            }
        });
    }
};

FSCache.prototype.del = function del(keys, callback) {
    var self = this;
    log(self, 'del() called', { keys: keys });
    callback = callback || noop;
    if (typeof keys === 'string') {
        keys = [keys];
    }
    var succeeded = 0;
    var done = 0;
    for (const key of keys) {
        delKey(self, key, err => {
            if (err) {
                error(self, 'del() err on key', { key: key, err: err });
            } else {
                succeeded++;
            }
            done++;
            if (done === keys.length) {
                // TODO: pass back partial errors?
                callback(null, succeeded);
            }
        });
    }
};

FSCache.prototype.flush = function flush(callback) {
    error(this, 'flush() called... NYI!');
    callback = callback || noop;
    callback('NYI!');
};

FSCache.prototype.db = 'none'; // bogus truthy value, just in case

// relativePathify isn't a part of the cache-service API, but is exposed so
// that custom pathify implementations can use it to get the automatic
// directory beahvior.
FSCache.prototype.relativePathify = function relativePathify(key) {
    var parts = [];
    var remaining = key;
    while (remaining.length > 2) {
        parts.push(remaining.substr(0, 2));
        remaining = remaining.substr(2);
    }
    parts.push(key + '.json');

    return path.join.apply(path, parts);
};

// === internal helpers (private, 'this' value explicity pased as 'self') ===

function delKey(self, key, callback) {
    log(self, 'delKey() called', { key: key });
    var name = fullPathify(self, key);
    fs.unlink(name, callback);
}

function fullPathify(self, key) {
    return path.join(self.cacheRoot, self.pathifyFn(key));
}

function log(self, message, data) {
    _log(self, false, message, data);
};

function error(self, message, data) {
    _log(self, true, message, data);
};

function _log(self, isError, message, data) {
    if (isError || self.verbose) {
        console.log(self.type + ': ' + message, data);
    }
};

function noop() {}

exports = module.exports = FSCache;
<commit_msg>add mgetall() for certain database-like scenarios<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');

function FSCache(config) {
    config = config || {};

    this.cacheRoot = path.resolve(config.cacheRoot || './cache');
    this.pathifyFn = config.pathify || this.relativePathify.bind(this);
    this.verbose = config.verbose || false;
    // cache module required config values
    this.type = config.type || 'file-system';
    this.defaultExpiration = config.defaultExpiration || 900;
    this.checkOnPreviousEmpty = config.checkOnPreviousEmpty || true;
    this.readOnly = config.readOnly || false;
}

// === cache-service API (public) ===

FSCache.prototype.get = function get(key, callback) {
    log(this, 'get() called', { key: key });
    var name = fullPathify(this, key);
    getFile(this, key, name, (err, obj) => {
        if (err) {
            callback(err);
            return;
        }
        callback(null, obj.data);
    });
};

FSCache.prototype.mget = function mget(keys, callback) {
    var self = this;
    log(self, 'mget() called', { keys: keys });
    var result = {};
    var errors = [];
    var done = 0;
    for (const key of keys) {
        self.get(key, (err, obj) => {
            if (err) {
                error(self, 'mget() error on key', { key: key, err: err })
                errors.push({ key: key, err: err });
            } else {
                result[key] = obj;
            }
            done++;
            if (done === keys.length) {
                callback(null, result);
            }
        });
    }
};

FSCache.prototype.set = function set(key, value, expiration, refresh, callback) {
    var self = this;
    log(self, 'set() called', { key: key, value: value });
    if (arguments.length === 3 && typeof expiration === 'function') {
        callback = expiration;
        expiration = self.defaultExpiration;
    } else if (arguments.length === 4) {
        callback = refresh;
        if (typeof expiration === 'function') {
            refresh = expiration;
            expiration = self.defaultExpiration;
        }
    }
    callback = callback || noop;
    var filePath = fullPathify(self, key);
    // UTC expiration in milliseconds, zero means "never expires".
    var expires = expiration > 0 ? Date.now() + (expiration * 1000) : 0;
    var cacheData = {
        key: key,
        expires: expires,
        data: value,
    };
    var data = JSON.stringify(cacheData);
    mkdirp(path.dirname(filePath), err => {
        fs.writeFile(filePath, data, err => {
            error(self, 'set() error', { key: key, err: err });
            callback(err);
        });
    });
};

FSCache.prototype.mset = function mset(obj, expiration, callback) {
    var self = this;
    log(self, 'mset() called', { obj: obj });
    if (arguments.length === 2 && typeof expiration === 'function') {
        callback = expiration;
        expiration = self.defaultExpiration;
    }
    callback = callback || noop;
    var keys = obj.keys();
    var errors = [];
    var done = 0;
    for (const key of keys) {
        // TODO: see if obj[key] has a cacheValue property?
        self.set(key, obj[key], expiration, err => {
            if (err) {
                error(self, 'mget() error on key', { key: key, err: err })
                errors.push({ key: key, err: err });
            }
            done++;
            if (done === keys.length) {
                callback(null);
            }
        });
    }
};

FSCache.prototype.del = function del(keys, callback) {
    var self = this;
    log(self, 'del() called', { keys: keys });
    callback = callback || noop;
    if (typeof keys === 'string') {
        keys = [keys];
    }
    var succeeded = 0;
    var done = 0;
    for (const key of keys) {
        delKey(self, key, err => {
            if (err) {
                error(self, 'del() err on key', { key: key, err: err });
            } else {
                succeeded++;
            }
            done++;
            if (done === keys.length) {
                // TODO: pass back partial errors?
                callback(null, succeeded);
            }
        });
    }
};

FSCache.prototype.flush = function flush(callback) {
    error(this, 'flush() called... NYI!');
    callback = callback || noop;
    callback('NYI!');
};

FSCache.prototype.db = 'none'; // bogus truthy value, just in case

// mgetall and relativePathify aren't a part of the cache-service API, but are
// exposed as supported helpers.
FSCache.prototype.mgetall = function mgetall(callback) {
    var self = this;
    log(self, 'mgetall() called');
    getTreeOrFile(self, self.cacheRoot, {}, (err, data) => {
        log(self, 'mgetall() got', { data: data, err: err })
    });
};

FSCache.prototype.relativePathify = function relativePathify(key) {
    var parts = [];
    var remaining = key;
    while (remaining.length > 2) {
        parts.push(remaining.substr(0, 2));
        remaining = remaining.substr(2);
    }
    parts.push(key + '.json');

    return path.join.apply(path, parts);
};

// === internal helpers (private, 'this' value explicity pased as 'self') ===

function getFile(self, key, name, callback) {
    log(self, 'getFile() called', { key: key, name: name });
    fs.readFile(name, (err, data) => {
        if (err) {
            error(self, 'getFile() read error', { key: key, name: name, err: err });
            callback(err);
            return;
        }

        try {
            var obj = JSON.parse(data.toString());

            if (!!key && obj.key !== key) {
                error(self, 'getFile() key does not match!', { key: key, dataKey: obj.key });
                throw 'key mismatch';
            }

            if (fullPathify(self, obj.key) !== name) {
                error(self, 'getFile() key does not match path!');
                throw 'key/path mismatch';
            }

            if (obj.expires > 0 && obj.expires <= Date.now()) {
                log(self, 'getFile() data has expired!', { key: key });
                throw 'data has expired';
            }

            callback(null, obj);
        } catch (err) {
            error(self, 'getFile() JSON error', { key: key, err: err });
            callback(err);
        }
    });
}

function getTreeOrFile(self, curPath, results, callback) {
    log(self, 'getTreeOrFile() called', { curPath: curPath })
    fs.readdir(curPath, (err, files) => {
        if (err) {
            // if file, try to load it directly!... and return the key/value in
            // an object
            log(self, 'getTreeOrFile() readdir error', { curPath: curPath, err: err });
            getFile(self, null, curPath, (err, obj) => {
                if (err) {
                    error(self, 'getTreeOrFile() file error', { curPath: curPath, err: err });
                    callback(err);
                    return;
                }
                results[obj.key] = obj.data;
                callback(null, results);
            });
            return;
        }

        // successful means we need to recurse on each item...
        log(self, 'getTreeOrFile() got', { files: files, err: err });
        var done = 0;
        for (const file of files) {
            getTreeOrFile(self, path.join(curPath, file), results, (err, data) => {
                if (err) {
                    error(self, 'getTreeOrFile() dir error', { curPath: curPath, file: file, err: err });
                    callback(err);
                    return;
                }
                done++;
                if (done === files.length) {
                    callback(null, data);
                }
            });
        }
    });
}

function delKey(self, key, callback) {
    log(self, 'delKey() called', { key: key });
    var name = fullPathify(self, key);
    fs.unlink(name, callback);
}

function fullPathify(self, key) {
    return path.join(self.cacheRoot, self.pathifyFn(key));
}

function log(self, message, data) {
    _log(self, false, message, data);
};

function error(self, message, data) {
    _log(self, true, message, data);
};

function _log(self, isError, message, data) {
    if (isError || self.verbose) {
        console.log(self.type + ': ' + message, data);
    }
};

function noop() {}

exports = module.exports = FSCache;
<|endoftext|>


<commit_before>

ApplyResult = function(name){
	this.init = function(name){
		this.name = name;
		this.m = {};
		this.l = {};
		this.m.add = [];
		this.m.del = [];
	}
	this.mark = function(name,id){
		this.l[name] = id;
	}
	this.get = function(name){
		return this.l[name];
	}
	this.map  = function(oldid,newid){
		if(isUndefined(newid)) return;
		if(newid == null){
			this.m.del.push(oldid);
			return;
		}
		if(oldid == null){
			this.m.add.push(newid);
			return;
		}
		this.m[newid] = oldid;
	}
	this.to = function(old_id){
		var res = [];
		for(id in this.m){
			if(id != "del" && id != "add" && this.m[id] == old_id){
				res.push(id)
			}
		}
		if(res.length == 0){
			for(var i=0; i < this.m.del.length; i++){
				if(this.m.del[i] == old_id){
					return null;
				}
			}
			return undefined;
		}
		return res;
	}
	this.from = function(new_id){
		if(!(new_id in this.m)){
			for(var i=0; i < this.m.add.length; i++){
				if(this.m.add[i] == new_id){
					return null;
				}
			}
			return undefined;
		}
		return this.m[new_id];
	}
	this.new_ids = function(){
		return this.m.add
	}
	this.del_ids = function(){
		return this.m.del;
	}
	this.init(name);
}

Transform = function(){
	/*
	find all possible applications of this transformation
	*/
	this.make_checker = function(filter){
		var sexpr = filter.split(' ');
		var dict = {};
		for(var i =0; i < sexpr.length; i++){
			var args = sexpr[i].split(':');
			if(args.length >= 2){
				if(dict.hasOwnProperty(args[0])){
					if (dict[args[0]] instanceof Array) {
						dict[args[0]].push(args[1]);
					}
					else{
						dict[args[0]] = [dict[args[0]], args[1]];
					}
				}
				else{
					dict[args[0]] = args[1];
				}
			}

		}

		return dict;
	}
	this.get_name = function(){
		return this.name;
	}
	/*

	*/
	this.find = function(filter, form){

	}
	this.apply = function(params, form){

	}
}

Transforms = {};
MoveTermSearchResults = function(){
	this.data = {};
	this.add = function(eq,t_move, t_after){
		var res = r.find('op:eq');
		var len = 0;
		for(var q in res){
			var has_movable;
			len++;
		}
		if(!this.data.hasOwnProperty(len)){
			this.data[len] = [];
		}
		this.data[0].push({eq:eq,src:t_move,after:t_after});
	}
	this.print = function(){

	}

}
Transforms.MoveTerm = function(){

}
Transforms.MoveTerm.prototype = new Transform();

SimplifyConstantsSearchResults = function(){
	this.data = {};
	this.add = function(r,chl){
		var len = 0;
		var res = r.find('type:number');
		for(var q in res){
			len++;
		}
		if(!this.data.hasOwnProperty(len)){
			this.data[len] = [];
		}
		this.data[len].push({node:r,children:chl});
	}
	this.print = function(){
		for(var q in this.data){
			console.log("Number Constants: ",q);
			for(var r = 0; r < this.data[q].length; r++){
				console.log("> ", this.data[q][r].node.print());
			}
		}
	}
	this.get = function(i){
		var k=0;
		for(var q in this.data){
			for(var r = 0; r < this.data[q].length; r++){
				if(i == k) return this.data[q][r];
				k++;
			}
		}
		return null;
	}
	this.foreach = function(cbk){
		for(var q in this.data){
			for(var r=0; r < this.data[q].length; r++){
				cbk(this.data[q][r].node, this.data[q][r].children, (q), r);
			}
		}
	}
}

Transforms.SimplifyConstants = function SimplifyConstants(){
	/*
	params: term:XXX term:XXX
	*/
	this.init = function(){

	}
	this.test = function(params,node){
		var factor = null;
		var numbers = [];
		node.foreach_child(function(c){
			if(c.data('type') == 'number'){
				numbers.push(c);
			}
			else if(c.data('type') == 'op'){
				var res = c.find('type:variable'); //if the child
				var cnt = 0;
				for(var r in res){
					cnt++;
				}
				if(cnt == 0) numbers.push(c);
			}
		})
		if(numbers.length < 1) return {ok:false, children:numbers, node:node};
		//ensure all the desired terms are in it
		if(params.hasOwnProperty('term')){
			var t = params.term;
			if (!(params.term instanceof Array)) t = [params.term];
			for(var i=0; i < t.length; i++){
				var res = node.find("#"+t[i]);
				if(res.length == 0) return {ok:false, children:numbers, node:node};
			}
		}
		return {ok:true, children:numbers, node:node};

	}
	this.find = function(filter, form){
		var params = this.make_checker(filter);
		var unfilt = form.find('type:op');
		var result = new SimplifyConstantsSearchResults();
		for(var i in unfilt){
			var r = this.test(params,unfilt[i]);
			if(r.ok){
				result.add(r.node, r.children);
			}
		}
		return result;
	}
	this.apply = function(res){
		var node = res.node;
		var children = res.children;
		var res = new ApplyResult();
		var finalval = node.eval();
		var form = node.get_formula();

		var newconst = form.add('NUMBER');
		newconst.set('value', finalval);
		newconst.set('code', ""+finalval);
		console.log(finalval);
		if(children.length == node.children.length){
			node.replace(newconst.id);
			res.map(node.id, newconst.id);

		}
		else{
			for(var i=0; i < children.length; i++){
				//remove child with this id.
				children[i].remove();
				res.map(children[i].id, newconst.id);
			}
			node.add_child(newconst.id, true);
			res.map(node.id, newconst.id);

		}
		form.cleanup();
		return res;

	}
	this.init();
}
Transforms.SimplifyConstants.prototype = new Transform();

this.DistributeSearchResult = function(){
	this.data = {};
	this._len = 0;
	this.add = function(i,s,j,d){
		var dist = Math.abs(i-j);
		if(!this.data.hasOwnProperty(dist))
			this.data[dist] = [];
		this.data[dist].push({src:s,dest:d});
		this._len+=1;
	}

	this.get = function(id){
		var k=0;
		for(var dist in this.data){
			for(var i=0; i < this.data[dist].length; i++){
				if(k == id){
					return {src:this.data[dist][i].src, dest:this.data[dist][i].dest, dist:dist};
				}
				k++;
			}
		}
	}
	this.foreach = function(cbk){
		for(var dist in this.data){
			for(var i=0; i < this.data[dist].length; i++){
				cbk(this.data[dist][i].src, this.data[dist][i].dest, dist, i);
			}
		}
	}
	this.print = function(){
		for(var i in this.data){
			console.log("## Distance: ",i);
			for(var j = 0; j < this.data[i].length; j++){
				var c = this.data[i][j];
				console.log("   > src: ",c.src.print(), ", dest: ",c.dest.print());
			}
		}
	}
}

Transforms.Distribute = function Distribute(){
	this.init = function(){

	}
	/*
	params: src:XXX src:XXX dest:XXX
	*/
	this.test = function(params,node){
		var test_param = function(n,t,mparan){
			var result = {};
			var result_count = 0;
			var found = {};
			n.foreach_child(function(c,idx){
				var isOk = true;
				//ensure contains all children.
				for(var i=0; i < t.length; i++){
					var res = c.find("#"+t[i]);
					if(countKeys(res) == 0) isOk = false;
				}
				//make sure contains all the terms, and if we require parenthesis, require
				if(isOk && (!mparan || c.data('op') == 'paren')){ //this node contains all sources.
					result[idx] = c;
					result_count++;
				}
			})
			return {data:result, count:result_count};
		}

		if(!params.hasOwnProperty('src')){
			params.src = [];
		}
		else if (!(params.src instanceof Array)){
			params.src = [params.src];
		}

		if(!params.hasOwnProperty('dest')){
			params.dest = [];
		}
		else if (!(params.dest instanceof Array)){
			params.dest = [params.dest];
		}

		var sources = test_param(node,params.src,false);
		var dests = test_param(node,params.dest,true);

		return {src:sources, dest:dests, ok:(dests.count != 0 && sources.count != 0)};

	}
	this.find = function(filter, form){
		var params = this.make_checker(filter);
		var unfilt = form.find('type:op op:mult');
		var result = new DistributeSearchResult();

		for(var i in unfilt){
			var res = this.test(params,unfilt[i]);
			if(res.ok){
				for(var si in res.src.data){
					for(var sj in res.dest.data){
						var i = parseInt(si);
						var j = parseInt(sj);
						if(i != j){
							result.add(i,res.src.data[si],j,res.dest.data[sj]);
						}
					}
				}
			}
		}
		//print results
		return result;
	}
	this.apply = function(res){
		var factor;
		var form = res.dest.get_formula();
		var log = new ApplyResult("distribute");

		var dest = res.dest.child(0);  //get inside the parenthesis
		var dest_op =dest.data("op");
		var src = res.src;
		var top = src.parent();
		log.mark('paren',dest.id);
		log.mark('top',top.id);
		//distribute over dest;
		if(dest_op== "mult"){
			dest.foreach_child(function(c,i){
				var nc = src.copy();
				mul.add_child_before(nc.id, c.id);
				log.map(src.id, nc.id);
			})
		}
		else if(dest_op == "sub" || dest_op == "plus"){
			dest.foreach_child(function(c,i){
				var mul = form.add("MULT");
				var nc = src.copy();

				c.replace(mul.id);

				mul.add_child(nc.id);
				mul.add_child(c.id);
				//add mappings
				log.map(src.id, nc.id);
				log.map(c.id,c.id);
				log.map(null, mul.id);
				//done
			})
		}
		else {
			var mul = form.add("MULT");
			var nc = src.copy();
			dest.replace(mul.id);
			mul.add_child(dest);
			mul.add_child(nc);
			log.map(src.id, nc.id);
			log.map(null, mul.id);
		}
		//remove the source from the products.
		src.remove();
		form.cleanup();
		return log;

	}
	this.init();
};
Transforms.Distribute.prototype = new Transform();

<commit_msg>working again - slight changes to simpl.js<commit_after>

ApplyResult = function(name){
	this.init = function(name){
		this.name = name;
		this.m = {};
		this.l = {};
		this.m.add = [];
		this.m.del = [];
	}
	this.mark = function(name,id){
		this.l[name] = id;
	}
	this.get = function(name){
		return this.l[name];
	}
	this.map  = function(oldid,newid){
		if(isUndefined(newid)) return;
		if(newid == null){
			this.m.del.push(oldid);
			return;
		}
		if(oldid == null){
			this.m.add.push(newid);
			return;
		}
		this.m[newid] = oldid;
	}
	this.to = function(old_id){
		var res = [];
		for(id in this.m){
			if(id != "del" && id != "add" && this.m[id] == old_id){
				res.push(id)
			}
		}
		if(res.length == 0){
			for(var i=0; i < this.m.del.length; i++){
				if(this.m.del[i] == old_id){
					return null;
				}
			}
			return undefined;
		}
		return res;
	}
	this.from = function(new_id){
		if(!(new_id in this.m)){
			for(var i=0; i < this.m.add.length; i++){
				if(this.m.add[i] == new_id){
					return null;
				}
			}
			//return undefined;
			return new_id;
		}
		return this.m[new_id];
	}
	this.new_ids = function(){
		return this.m.add
	}
	this.del_ids = function(){
		return this.m.del;
	}
	this.init(name);
}

Transform = function(){
	/*
	find all possible applications of this transformation
	*/
	this.make_checker = function(filter){
		var sexpr = filter.split(' ');
		var dict = {};
		for(var i =0; i < sexpr.length; i++){
			var args = sexpr[i].split(':');
			if(args.length >= 2){
				if(dict.hasOwnProperty(args[0])){
					if (dict[args[0]] instanceof Array) {
						dict[args[0]].push(args[1]);
					}
					else{
						dict[args[0]] = [dict[args[0]], args[1]];
					}
				}
				else{
					dict[args[0]] = args[1];
				}
			}

		}

		return dict;
	}
	this.get_name = function(){
		return this.name;
	}
	/*

	*/
	this.find = function(filter, form){

	}
	this.apply = function(params, form){

	}
}

Transforms = {};
MoveTermSearchResults = function(){
	this.data = {};
	this.add = function(eq,t_move, t_after){
		var res = r.find('op:eq');
		var len = 0;
		for(var q in res){
			var has_movable;
			len++;
		}
		if(!this.data.hasOwnProperty(len)){
			this.data[len] = [];
		}
		this.data[0].push({eq:eq,src:t_move,after:t_after});
	}
	this.print = function(){

	}

}
Transforms.MoveTerm = function(){

}
Transforms.MoveTerm.prototype = new Transform();

SimplifyConstantsSearchResults = function(){
	this.data = {};
	this.add = function(r,chl){
		var len = 0;
		var res = r.find('type:number');
		for(var q in res){
			len++;
		}
		if(!this.data.hasOwnProperty(len)){
			this.data[len] = [];
		}
		this.data[len].push({node:r,children:chl});
	}
	this.print = function(){
		for(var q in this.data){
			console.log("Number Constants: ",q);
			for(var r = 0; r < this.data[q].length; r++){
				console.log("> ", this.data[q][r].node.print());
			}
		}
	}
	this.get = function(i){
		var k=0;
		for(var q in this.data){
			for(var r = 0; r < this.data[q].length; r++){
				if(i == k) return this.data[q][r];
				k++;
			}
		}
		return null;
	}
	this.foreach = function(cbk){
		for(var q in this.data){
			for(var r=0; r < this.data[q].length; r++){
				cbk(this.data[q][r].node, this.data[q][r].children, (q), r);
			}
		}
	}
}

Transforms.SimplifyConstants = function SimplifyConstants(){
	/*
	params: term:XXX term:XXX
	*/
	this.init = function(){

	}
	this.test = function(params,node){
		var factor = null;
		var numbers = [];
		node.foreach_child(function(c){
			if(c.data('type') == 'number'){
				numbers.push(c);
			}
			else if(c.data('type') == 'op'){
				var res = c.find('type:variable'); //if the child
				var cnt = 0;
				for(var r in res){
					cnt++;
				}
				if(cnt == 0) numbers.push(c);
			}
		})
		if(numbers.length < 1) return {ok:false, children:numbers, node:node};
		//ensure all the desired terms are in it
		if(params.hasOwnProperty('term')){
			var t = params.term;
			if (!(params.term instanceof Array)) t = [params.term];
			for(var i=0; i < t.length; i++){
				var res = node.find("#"+t[i]);
				if(res.length == 0) return {ok:false, children:numbers, node:node};
			}
		}
		return {ok:true, children:numbers, node:node};

	}
	this.find = function(filter, form){
		var params = this.make_checker(filter);
		var unfilt = form.find('type:op');
		var result = new SimplifyConstantsSearchResults();
		for(var i in unfilt){
			var r = this.test(params,unfilt[i]);
			if(r.ok){
				result.add(r.node, r.children);
			}
		}
		return result;
	}
	this.apply = function(res){
		var node = res.node;
		var children = res.children;
		var res = new ApplyResult();
		var finalval = node.eval();
		var form = node.get_formula();

		var newconst = form.add('NUMBER');
		newconst.set('value', finalval);
		newconst.set('code', ""+finalval);
		console.log(finalval);
		if(children.length == node.children.length){
			node.replace(newconst.id);
			res.map(node.id, newconst.id);

		}
		else{
			for(var i=0; i < children.length; i++){
				//remove child with this id.
				children[i].remove();
				res.map(children[i].id, newconst.id);
			}
			node.add_child(newconst.id, true);
			res.map(node.id, newconst.id);

		}
		form.cleanup();
		return res;

	}
	this.init();
}
Transforms.SimplifyConstants.prototype = new Transform();

this.DistributeSearchResult = function(){
	this.data = {};
	this._len = 0;
	this.add = function(i,s,j,d){
		var dist = Math.abs(i-j);
		if(!this.data.hasOwnProperty(dist))
			this.data[dist] = [];
		this.data[dist].push({src:s,dest:d});
		this._len+=1;
	}

	this.get = function(id){
		var k=0;
		for(var dist in this.data){
			for(var i=0; i < this.data[dist].length; i++){
				if(k == id){
					return {src:this.data[dist][i].src, dest:this.data[dist][i].dest, dist:dist};
				}
				k++;
			}
		}
	}
	this.foreach = function(cbk){
		for(var dist in this.data){
			for(var i=0; i < this.data[dist].length; i++){
				cbk(this.data[dist][i].src, this.data[dist][i].dest, dist, i);
			}
		}
	}
	this.print = function(){
		for(var i in this.data){
			console.log("## Distance: ",i);
			for(var j = 0; j < this.data[i].length; j++){
				var c = this.data[i][j];
				console.log("   > src: ",c.src.print(), ", dest: ",c.dest.print());
			}
		}
	}
}

Transforms.Distribute = function Distribute(){
	this.init = function(){

	}
	/*
	params: src:XXX src:XXX dest:XXX
	*/
	this.test = function(params,node){
		var test_param = function(n,t,mparan){
			var result = {};
			var result_count = 0;
			var found = {};
			n.foreach_child(function(c,idx){
				var isOk = true;
				//ensure contains all children.
				for(var i=0; i < t.length; i++){
					var res = c.find("#"+t[i]);
					if(countKeys(res) == 0) isOk = false;
				}
				//make sure contains all the terms, and if we require parenthesis, require
				if(isOk && (!mparan || c.data('op') == 'paren')){ //this node contains all sources.
					result[idx] = c;
					result_count++;
				}
			})
			return {data:result, count:result_count};
		}

		if(!params.hasOwnProperty('src')){
			params.src = [];
		}
		else if (!(params.src instanceof Array)){
			params.src = [params.src];
		}

		if(!params.hasOwnProperty('dest')){
			params.dest = [];
		}
		else if (!(params.dest instanceof Array)){
			params.dest = [params.dest];
		}

		var sources = test_param(node,params.src,false);
		var dests = test_param(node,params.dest,true);

		return {src:sources, dest:dests, ok:(dests.count != 0 && sources.count != 0)};

	}
	this.find = function(filter, form){
		var params = this.make_checker(filter);
		var unfilt = form.find('type:op op:mult');
		var result = new DistributeSearchResult();

		for(var i in unfilt){
			var res = this.test(params,unfilt[i]);
			if(res.ok){
				for(var si in res.src.data){
					for(var sj in res.dest.data){
						var i = parseInt(si);
						var j = parseInt(sj);
						if(i != j){
							result.add(i,res.src.data[si],j,res.dest.data[sj]);
						}
					}
				}
			}
		}
		//print results
		return result;
	}
	this.apply = function(res){
		var factor;
		var form = res.dest.get_formula();
		var log = new ApplyResult("distribute");

		var dest = res.dest.child(0);  //get inside the parenthesis
		var dest_op =dest.data("op");
		var src = res.src;
		//var top = src.parent();
		log.mark('paren',dest.id);
		log.mark('top',src.id);
		//distribute over dest;
		if(dest_op== "mult"){
			dest.foreach_child(function(c,i){
				var nc = src.copy();
				mul.add_child_before(nc.id, c.id);
				log.map(src.id, nc.id);
			})
		}
		else if(dest_op == "sub" || dest_op == "plus"){
			dest.foreach_child(function(c,i){
				var mul = form.add("MULT");
				var nc = src.copy();

				c.replace(mul.id);

				mul.add_child(nc.id);
				mul.add_child(c.id);
				//add mappings
				log.map(src.id, nc.id);
				log.map(c.id,c.id);
				log.map(null, mul.id);
				//done
			})
		}
		else {
			var mul = form.add("MULT");
			var nc = src.copy();
			dest.replace(mul.id);
			mul.add_child(dest);
			mul.add_child(nc);
			log.map(src.id, nc.id);
			log.map(null, mul.id);
		}
		//remove the source from the products.
		src.remove();
		form.cleanup();
		return log;

	}
	this.init();
};
Transforms.Distribute.prototype = new Transform();

<|endoftext|>


<commit_before>var root = "http://localhost:8080/api";

app.service('ApartamentosService',['$http',function($http){
	var results = [];
	var item;
	this.buscarAparta = function(){
	console.log("buscando... "+this.item);
	$http({method: 'GET', url: root + "/apartamentos/search",
	  headers:{ 'Accept':'*/*'},
	  data: item }).
	  success(function(data, status, headers, config) {
	    console.log("POST Sucess");
	    console.log();
	  }).
	  error(function(data, status, headers, config) {
	    console.log("POST error");
	    console.log(status);
	    console.log(data);
	  });
    };
}]);

app.controller('ApartamentoCtrl', ['$scope', '$routeParams',
  function($scope, $routeParams) {
      //Falta hay q hacer lo de facebook

  }]);

app.controller('AgregarApartamentoCtrl', ['$scope', 'geolocation', 'camera','$routeParams', '$http','toaster',
  function($scope, geolocation, $routeParams, $http,toaster) {
    //$scope.item = ApartamentosAPIService.CREATE;
    $scope.item = {	genero: 'unisex',
    				opcion_agua: false,
    				opcion_electricidad: false,
    				opcion_internet: false,
    				opcion_seguridad: false,
    				fotos:[
						{src: 'img/add_img.png'},
						{src: 'img/add_img.png'},
						{src: 'img/add_img.png'},
						{src: 'img/add_img.png'}
			    	]
    };
	    $scope.map = {
	    center: {
	        latitude: 9.855756503226328,
	        longitude: -83.91060333698988
	    },
	    zoom: 17
	};

 geolocation.getCurrentPosition(function(position) {
            $scope.$apply(function() {
			$scope.item.ubicacion_latitud =  position.coords.latitude;
	    	$scope.item.ubicacion_longitud =  position.coords.longitude;
            });
        }, function(error) {
            $scope.$apply(function() {
                $scope.error = error;
            });
        }, {});

	$scope.getPhoto = function(index){
		camera.getPicture(function(image) {
			    $scope.$apply(function() {
				$scope.item.fotos[index].src = "data:image/jpeg;base64," + image;
			    });
			}, function(error) {
			    $scope.$apply(function() {
				$scope.error = error;
			    });
			}, {
			    destinationType: Camera.DestinationType.DATA_URL,
			    sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
			    encodingType: Camera.EncodingType.JPEG,
			    quality: 50
			});
	}
    $scope.crearAparta = function(){
      console.debug($scope.item);
      $http({method: 'POST', url: "http://localhost:8080/api/apartamentos",
	headers:{ 'Accept':'*/*'},
	data: $scope.item }).
	success(function(data, status, headers, config) {
	  console.log("POST Sucess");
	  toaster.pop('success', "??Genial!", 'Se han guardado los cambios', null, 'trustedHtml');
	}).
	error(function(data, status, headers, config) {
	  console.log("POST error");
		  console.log('$scope.crearAparta: status:'+status);
		  toaster.pop('error', "Error", 'No se pudo crear el apartamento', null, 'trustedHtml');
	});
    };
  }]);

app.controller('BuscarApartamentoCtrl', ['$scope', '$routeParams','$http','ApartamentosService',
  function($scope, $routeParams,$http, ApartamentosService) {
     $scope.item = {	genero: 	'unisex',
			calificacion: 	3,
			cercania_tec: 	5
		};
	$scope.demo2 = {
	    range: {
		min: 0,
		max: 10050
	    },
	    minPrice: 1000,
	    maxPrice: 4000
	};
	ApartamentosService.item = $scope.item;
	$scope.buscarAparta = ApartamentosService.buscarAparta;
	console.log("BuscarApartamentoCtrl/buscarAparta: ",ApartamentosService.item);
}]);

app.controller('ResultadosCtrl', ['$scope', '$routeParams',
  function($scope, $routeParams) {
	$scope.order = 'calificacion';
	$scope.reverse = true;
	console.log('results: '+ApartamentosService.results);
	$scope.results = [
	    {'titulo': 'Barato y espacioso',
	     'calificacion': '3',
	     'area': '220',
	     'habitaciones': '5',
	     'sexo': 'male',
	     'cercania_tec': '1.8',
	     'mensualidad': 150000,
	     'descripcion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin at lectus ligula. Nunc massa nisl, accumsan nec molestie eu.',
	     'fotos':[
			{src: 'http://lorempixel.com/250/200/city/'},
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/transport/'},
			{src: 'http://lorempixel.com/250/200/technics/'}
		    	]},
	    {'titulo': 'Oferta!!',
	     'calificacion': '5',
	     'area': '220',
	     'habitaciones': '3',
	     'sexo': 'unisex',
	     'cercania_tec': '2.1',
	     'mensualidad': 70000,
	     'descripcion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin at lectus ligula. Nunc massa nisl, accumsan nec molestie eu.',
	     'fotos':[
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/technics/'},
			{src: 'http://lorempixel.com/250/200/transport/'},
			{src: 'http://lorempixel.com/250/200/technics/'}
		    	]},
	    {'titulo': 'Primeros ingresos',
	     'calificacion': '1',
	     'area': '320',
	     'habitaciones': '4',
	     'sexo': 'female',
	     'cercania_tec': '7.2',
	     'mensualidad': 320000,
	     'descripcion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin at lectus ligula. Nunc massa nisl, accumsan nec molestie eu.',
	     'fotos':[
			{src: 'http://lorempixel.com/250/200/transport/'},
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/technics/'}
		    	]},
	  ];
  }]);

app.controller('VerApartamentoCtrl', ['$scope', '$routeParams',
  function($scope, $routeParams) {
     $scope.item = {	descripcion: 		'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi rhoncus dolor non fermentum imperdiet. Phasellus adipiscing tellus in nibh rhoncus, ac convallis erat ullamcorper. Nullam interdum mi et ultrices iaculis. Mauris placerat dolor massa, eget aliquet elit aliquet id.',
			direccion_fisica: 	'direccion del aparta',
			area: 			230,
			ubicacion_latitud: 	5.342,
			ubicacion_longitud: 	10.2323,
			cercania_tec: 		5,
			calificacion: 		4,
			mensualidad: 		70000,
			habitaciones: 		5,
			titulo: 		'Titulo del aparta',
			genero: 		'male',
			opcion_agua: 		true,
			opcion_electricidad: 	true,
			opcion_seguridad: 	true,
			opcion_internet: 	true,
			fotos: 		[
							{src: 'http://lorempixel.com/250/200/city/'},
							{src: 'http://lorempixel.com/250/200/abstract/'},
							{src: 'http://lorempixel.com/250/200/transport/'},
							{src: 'http://lorempixel.com/250/200/technics/'}
					],
			comentarios: 	[
						{
							contenido: 'Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate',
							fecha_publicacion: "2014-02-08 09:30",
							autor: {
								nombre: 	'Bairon',
								apellido: 	'Perez',
								oauth_id: 	'1763484990',
								}
						},
						{
							contenido: 'Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. ',
							fecha_publicacion: "2014-05-08 09:30",
							autor: {
								nombre: 	'Karla',
								apellido: 	'Madrigal',
								oauth_id: 	'100001429851672',
								}
						},
						{
							contenido: 'Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. ',
							fecha_publicacion: "2013-02-08 09:30",
							autor: {
								nombre: 	'Emmanuel',
								apellido: 	'Mora',
								oauth_id: 	'1287630773',
								}
						}
				    	]
		};

    $scope.nueva_calificacion = 5;
    $scope.nuevo_comentario = "";
    $scope.max_len_comentario = 140;

    // initial image index
    $scope._Index = 0;

    // if a current image is the same as requested image
    $scope.isActive = function (index) {
        return $scope._Index === index;
    };

    // show prev image
    $scope.showPrev = function () {
        $scope._Index = ($scope._Index > 0) ? --$scope._Index : $scope.photos.length - 1;
    };

    // show next image
    $scope.showNext = function () {
        $scope._Index = ($scope._Index < $scope.photos.length - 1) ? ++$scope._Index : 0;
    };

    // show a certain image
    $scope.showPhoto = function (index) {
        $scope._Index = index;
    };

  }]);

app.controller('MisApartamentosCtrl', ['$scope', '$routeParams',
  function($scope, $routeParams) {
	$scope.order = 'calificacion';
	$scope.reverse = true;
	$scope.results = [
	    {'titulo': 'Barato y espacioso',
	     'calificacion': '3',
	     'area': '220',
	     'habitaciones': '5',
	     'sexo': 'male',
	     'cercania_tec': '1.8',
	     'descripcion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin at lectus ligula. Nunc massa nisl, accumsan nec molestie eu.',
	     'fotos':[
			{src: 'http://lorempixel.com/250/200/city/'},
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/transport/'},
			{src: 'http://lorempixel.com/250/200/technics/'}
		    	]},
	    {'titulo': 'Oferta!!',
	     'calificacion': '5',
	     'area': '220',
	     'habitaciones': '3',
	     'sexo': 'unisex',
	     'cercania_tec': '2.1',
	     'descripcion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin at lectus ligula. Nunc massa nisl, accumsan nec molestie eu.',
	     'fotos':[
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/technics/'},
			{src: 'http://lorempixel.com/250/200/transport/'},
			{src: 'http://lorempixel.com/250/200/technics/'}
		    	]},
	    {'titulo': 'Primeros ingresos',
	     'calificacion': '1',
	     'area': '320',
	     'habitaciones': '4',
	     'sexo': 'female',
	     'cercania_tec': '7.2',
	     'descripcion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin at lectus ligula. Nunc massa nisl, accumsan nec molestie eu.',
	     'fotos':[
			{src: 'http://lorempixel.com/250/200/transport/'},
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/technics/'}
		    	]},
	  ];
  }]);

app.controller('EditarApartamentoCtrl', ['$scope', '$routeParams', 'toaster',
  function($scope, $routeParams, toaster) {

     $scope.save = function(){
        toaster.pop('success', "??Genial!", 'Se han guardado los cambios', null, 'trustedHtml');
    };

     $scope.item = {	descripcion: 		'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi rhoncus dolor non fermentum imperdiet. Phasellus adipiscing tellus in nibh rhoncus, ac convallis erat ullamcorper. Nullam interdum mi et ultrices iaculis. Mauris placerat dolor massa, eget aliquet elit aliquet id.',
			direccion_fisica: 	'direccion del aparta',
			area: 			230,
			ubicacion_latitud: 	5.342,
			ubicacion_longitud: 	10.2323,
			cercania_tec: 		5,
			//comentarios: 	[Comentario],
			//calificaciones: 	[Calificacion],
			mensualidad: 		70000,
			habitaciones: 		5,
			titulo: 		'Titulo aparta',
			genero: 		'male',
			opcion_agua: 		true,
			opcion_electricidad: 	true,
			opcion_seguridad: 	true,
			opcion_internet: 	true,
			fotos: 		[
							{src: 'http://lorempixel.com/250/200/city/'},
							{src: 'http://lorempixel.com/250/200/abstract/'},
							{src: 'http://lorempixel.com/250/200/transport/'},
							{src: 'http://lorempixel.com/250/200/technics/'}
					    	]
		};

  }]);
<commit_msg>dependencias<commit_after>var root = "http://localhost:8080/api";

app.service('ApartamentosService',['$http',function($http){
	var results = [];
	var item;
	this.buscarAparta = function(){
	console.log("buscando... "+this.item);
	$http({method: 'GET', url: root + "/apartamentos/search",
	  headers:{ 'Accept':'*/*'},
	  data: item }).
	  success(function(data, status, headers, config) {
	    console.log("POST Sucess");
	    console.log();
	  }).
	  error(function(data, status, headers, config) {
	    console.log("POST error");
	    console.log(status);
	    console.log(data);
	  });
    };
}]);

app.controller('ApartamentoCtrl', ['$scope', '$routeParams',
  function($scope, $routeParams) {
      //Falta hay q hacer lo de facebook

  }]);

app.controller('AgregarApartamentoCtrl', ['$scope', 'geolocation', 'camera','$routeParams', '$http','toaster',
  function($scope, geolocation, camera, $routeParams, $http, toaster) {
    //$scope.item = ApartamentosAPIService.CREATE;
    $scope.item = {	genero: 'unisex',
    				opcion_agua: false,
    				opcion_electricidad: false,
    				opcion_internet: false,
    				opcion_seguridad: false,
    				fotos:[
						{src: 'img/add_img.png'},
						{src: 'img/add_img.png'},
						{src: 'img/add_img.png'},
						{src: 'img/add_img.png'}
			    	]
    };
	$scope.map = {
	    center: {
	        latitude: 9.855756503226328,
	        longitude: -83.91060333698988
	    },
	    zoom: 17
	};

 	geolocation.getCurrentPosition(function(position) {
            $scope.$apply(function() {
			$scope.item.ubicacion_latitud =  position.coords.latitude;
	    	$scope.item.ubicacion_longitud =  position.coords.longitude;
            });
        }, function(error) {
            $scope.$apply(function() {
                $scope.error = error;
            });
        }, {});

	$scope.getPhoto = function(index){
		camera.getPicture(function(image) {
			    $scope.$apply(function() {
				$scope.item.fotos[index].src = "data:image/jpeg;base64," + image;
			    });
			}, function(error) {
			    $scope.$apply(function() {
				$scope.error = error;
			    });
			}, {
			    destinationType: Camera.DestinationType.DATA_URL,
			    sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
			    encodingType: Camera.EncodingType.JPEG,
			    quality: 50
			});
	}
    $scope.crearAparta = function(){
      console.debug($scope.item);
      $http({method: 'POST', url: "http://localhost:8080/api/apartamentos",
		headers:{ 'Accept':'*/*'},
		data: $scope.item }).
		success(function(data, status, headers, config) {
		  console.log("POST Sucess");
		  toaster.pop('success', "??Genial!", 'Se han guardado los cambios', null, 'trustedHtml');
		}).
		error(function(data, status, headers, config) {
		  console.log("POST error");
			  console.log('$scope.crearAparta: status:'+status);
			  toaster.pop('error', "Error", 'No se pudo crear el apartamento', null, 'trustedHtml');
		});
	    };
  }]);

app.controller('BuscarApartamentoCtrl', ['$scope', '$routeParams','$http','ApartamentosService',
  function($scope, $routeParams,$http, ApartamentosService) {
     $scope.item = {	genero: 	'unisex',
			calificacion: 	3,
			cercania_tec: 	5
		};
	$scope.demo2 = {
	    range: {
		min: 0,
		max: 10050
	    },
	    minPrice: 1000,
	    maxPrice: 4000
	};
	ApartamentosService.item = $scope.item;
	$scope.buscarAparta = ApartamentosService.buscarAparta;
	console.log("BuscarApartamentoCtrl/buscarAparta: ",ApartamentosService.item);
}]);

app.controller('ResultadosCtrl', ['$scope', '$routeParams',
  function($scope, $routeParams) {
	$scope.order = 'calificacion';
	$scope.reverse = true;
	console.log('results: '+ApartamentosService.results);
	$scope.results = [
	    {'titulo': 'Barato y espacioso',
	     'calificacion': '3',
	     'area': '220',
	     'habitaciones': '5',
	     'sexo': 'male',
	     'cercania_tec': '1.8',
	     'mensualidad': 150000,
	     'descripcion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin at lectus ligula. Nunc massa nisl, accumsan nec molestie eu.',
	     'fotos':[
			{src: 'http://lorempixel.com/250/200/city/'},
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/transport/'},
			{src: 'http://lorempixel.com/250/200/technics/'}
		    	]},
	    {'titulo': 'Oferta!!',
	     'calificacion': '5',
	     'area': '220',
	     'habitaciones': '3',
	     'sexo': 'unisex',
	     'cercania_tec': '2.1',
	     'mensualidad': 70000,
	     'descripcion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin at lectus ligula. Nunc massa nisl, accumsan nec molestie eu.',
	     'fotos':[
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/technics/'},
			{src: 'http://lorempixel.com/250/200/transport/'},
			{src: 'http://lorempixel.com/250/200/technics/'}
		    	]},
	    {'titulo': 'Primeros ingresos',
	     'calificacion': '1',
	     'area': '320',
	     'habitaciones': '4',
	     'sexo': 'female',
	     'cercania_tec': '7.2',
	     'mensualidad': 320000,
	     'descripcion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin at lectus ligula. Nunc massa nisl, accumsan nec molestie eu.',
	     'fotos':[
			{src: 'http://lorempixel.com/250/200/transport/'},
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/technics/'}
		    	]},
	  ];
  }]);

app.controller('VerApartamentoCtrl', ['$scope', '$routeParams',
  function($scope, $routeParams) {
     $scope.item = {	descripcion: 		'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi rhoncus dolor non fermentum imperdiet. Phasellus adipiscing tellus in nibh rhoncus, ac convallis erat ullamcorper. Nullam interdum mi et ultrices iaculis. Mauris placerat dolor massa, eget aliquet elit aliquet id.',
			direccion_fisica: 	'direccion del aparta',
			area: 			230,
			ubicacion_latitud: 	5.342,
			ubicacion_longitud: 	10.2323,
			cercania_tec: 		5,
			calificacion: 		4,
			mensualidad: 		70000,
			habitaciones: 		5,
			titulo: 		'Titulo del aparta',
			genero: 		'male',
			opcion_agua: 		true,
			opcion_electricidad: 	true,
			opcion_seguridad: 	true,
			opcion_internet: 	true,
			fotos: 		[
							{src: 'http://lorempixel.com/250/200/city/'},
							{src: 'http://lorempixel.com/250/200/abstract/'},
							{src: 'http://lorempixel.com/250/200/transport/'},
							{src: 'http://lorempixel.com/250/200/technics/'}
					],
			comentarios: 	[
						{
							contenido: 'Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate',
							fecha_publicacion: "2014-02-08 09:30",
							autor: {
								nombre: 	'Bairon',
								apellido: 	'Perez',
								oauth_id: 	'1763484990',
								}
						},
						{
							contenido: 'Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. ',
							fecha_publicacion: "2014-05-08 09:30",
							autor: {
								nombre: 	'Karla',
								apellido: 	'Madrigal',
								oauth_id: 	'100001429851672',
								}
						},
						{
							contenido: 'Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. ',
							fecha_publicacion: "2013-02-08 09:30",
							autor: {
								nombre: 	'Emmanuel',
								apellido: 	'Mora',
								oauth_id: 	'1287630773',
								}
						}
				    	]
		};

    $scope.nueva_calificacion = 5;
    $scope.nuevo_comentario = "";
    $scope.max_len_comentario = 140;

    // initial image index
    $scope._Index = 0;

    // if a current image is the same as requested image
    $scope.isActive = function (index) {
        return $scope._Index === index;
    };

    // show prev image
    $scope.showPrev = function () {
        $scope._Index = ($scope._Index > 0) ? --$scope._Index : $scope.photos.length - 1;
    };

    // show next image
    $scope.showNext = function () {
        $scope._Index = ($scope._Index < $scope.photos.length - 1) ? ++$scope._Index : 0;
    };

    // show a certain image
    $scope.showPhoto = function (index) {
        $scope._Index = index;
    };

  }]);

app.controller('MisApartamentosCtrl', ['$scope', '$routeParams',
  function($scope, $routeParams) {
	$scope.order = 'calificacion';
	$scope.reverse = true;
	$scope.results = [
	    {'titulo': 'Barato y espacioso',
	     'calificacion': '3',
	     'area': '220',
	     'habitaciones': '5',
	     'sexo': 'male',
	     'cercania_tec': '1.8',
	     'descripcion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin at lectus ligula. Nunc massa nisl, accumsan nec molestie eu.',
	     'fotos':[
			{src: 'http://lorempixel.com/250/200/city/'},
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/transport/'},
			{src: 'http://lorempixel.com/250/200/technics/'}
		    	]},
	    {'titulo': 'Oferta!!',
	     'calificacion': '5',
	     'area': '220',
	     'habitaciones': '3',
	     'sexo': 'unisex',
	     'cercania_tec': '2.1',
	     'descripcion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin at lectus ligula. Nunc massa nisl, accumsan nec molestie eu.',
	     'fotos':[
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/technics/'},
			{src: 'http://lorempixel.com/250/200/transport/'},
			{src: 'http://lorempixel.com/250/200/technics/'}
		    	]},
	    {'titulo': 'Primeros ingresos',
	     'calificacion': '1',
	     'area': '320',
	     'habitaciones': '4',
	     'sexo': 'female',
	     'cercania_tec': '7.2',
	     'descripcion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin at lectus ligula. Nunc massa nisl, accumsan nec molestie eu.',
	     'fotos':[
			{src: 'http://lorempixel.com/250/200/transport/'},
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/abstract/'},
			{src: 'http://lorempixel.com/250/200/technics/'}
		    	]},
	  ];
  }]);

app.controller('EditarApartamentoCtrl', ['$scope', '$routeParams', 'toaster',
  function($scope, $routeParams, toaster) {

     $scope.save = function(){
        toaster.pop('success', "??Genial!", 'Se han guardado los cambios', null, 'trustedHtml');
    };

     $scope.item = {	descripcion: 		'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi rhoncus dolor non fermentum imperdiet. Phasellus adipiscing tellus in nibh rhoncus, ac convallis erat ullamcorper. Nullam interdum mi et ultrices iaculis. Mauris placerat dolor massa, eget aliquet elit aliquet id.',
			direccion_fisica: 	'direccion del aparta',
			area: 			230,
			ubicacion_latitud: 	5.342,
			ubicacion_longitud: 	10.2323,
			cercania_tec: 		5,
			//comentarios: 	[Comentario],
			//calificaciones: 	[Calificacion],
			mensualidad: 		70000,
			habitaciones: 		5,
			titulo: 		'Titulo aparta',
			genero: 		'male',
			opcion_agua: 		true,
			opcion_electricidad: 	true,
			opcion_seguridad: 	true,
			opcion_internet: 	true,
			fotos: 		[
							{src: 'http://lorempixel.com/250/200/city/'},
							{src: 'http://lorempixel.com/250/200/abstract/'},
							{src: 'http://lorempixel.com/250/200/transport/'},
							{src: 'http://lorempixel.com/250/200/technics/'}
					    	]
		};

  }]);
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var argscheck = require('cordova/argscheck'),
    DirectoryEntry = require('./DirectoryEntry'),
    FileEntry = require('./FileEntry'),
    FileError = require('./FileError'),
    exec = require('cordova/exec');
var fileSystems = require('./fileSystems');

/**
 * Look up file system Entry referred to by local URI.
 * @param {DOMString} uri  URI referring to a local file or directory
 * @param successCallback  invoked with Entry object corresponding to URI
 * @param errorCallback    invoked if error occurs retrieving file system entry
 */
module.exports.resolveLocalFileSystemURL = function(uri, successCallback, errorCallback) {
    argscheck.checkArgs('sFF', 'resolveLocalFileSystemURI', arguments);
    // error callback
    var fail = function(error) {
        errorCallback && errorCallback(new FileError(error));
    };
    // sanity check for 'not:valid:filename' or '/not:valid:filename'
    // file.spec.12 window.resolveLocalFileSystemURI should error (ENCODING_ERR) when resolving invalid URI with leading /.
    if(!uri || uri.split(":").length > 2 || uri.indexOf('/') == 0) {
        setTimeout( function() {
            fail(FileError.ENCODING_ERR);
        },0);
        return;
    }
    // if successful, return either a file or directory entry
    var success = function(entry) {
        if (entry) {
            if (successCallback) {
                // create appropriate Entry object
                // The entry should have either a filesystemName property, or a filesystem property with a name
                // For backwards compatibility, also accept window.PERSISTENT (0)
                var fsName = entry.filesystemName || (entry.filesystem && entry.filesystem.name) || (entry.filesystem == window.PERSISTENT ? 'persistent' : 'temporary');
                fileSystems.getFs(fsName, function(fs) {
                    if (!fs) {
                        fs = new FileSystem(fsName, {name:"", fullPath:"/"});
                    }
                    var result = (entry.isDirectory) ? new DirectoryEntry(entry.name, entry.fullPath, fs, entry.nativeURL) : new FileEntry(entry.name, entry.fullPath, fs, entry.nativeURL);
                    successCallback(result);
                });
            }
        }
        else {
            // no Entry object returned
            fail(FileError.NOT_FOUND_ERR);
        }
    };

    exec(success, fail, "File", "resolveLocalFileSystemURI", [uri]);
};
module.exports.resolveLocalFileSystemURI = function() {
    console.log("resolveLocalFileSystemURI is deprecated. Please call resolveLocalFileSystemURL instead.");
    module.exports.resolveLocalFileSystemURL.apply(this, arguments);
};
<commit_msg>CB-7375: Partial revert to resolve WP8 failures<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var argscheck = require('cordova/argscheck'),
    DirectoryEntry = require('./DirectoryEntry'),
    FileEntry = require('./FileEntry'),
    FileError = require('./FileError'),
    exec = require('cordova/exec');
var fileSystems = require('./fileSystems');

/**
 * Look up file system Entry referred to by local URI.
 * @param {DOMString} uri  URI referring to a local file or directory
 * @param successCallback  invoked with Entry object corresponding to URI
 * @param errorCallback    invoked if error occurs retrieving file system entry
 */
module.exports.resolveLocalFileSystemURL = function(uri, successCallback, errorCallback) {
    argscheck.checkArgs('sFF', 'resolveLocalFileSystemURI', arguments);
    // error callback
    var fail = function(error) {
        errorCallback && errorCallback(new FileError(error));
    };
    // sanity check for 'not:valid:filename' or '/not:valid:filename'
    // file.spec.12 window.resolveLocalFileSystemURI should error (ENCODING_ERR) when resolving invalid URI with leading /.
    if(!uri || uri.split(":").length > 2 || uri.indexOf('/') == 0) {
        setTimeout( function() {
            fail(FileError.ENCODING_ERR);
        },0);
        return;
    }
    // if successful, return either a file or directory entry
    var success = function(entry) {
        if (entry) {
            if (successCallback) {
                // create appropriate Entry object
                var fsName = (entry.filesystem && entry.filesystem.name) || (entry.filesystem == window.PERSISTENT ? 'persistent' : 'temporary');
                fileSystems.getFs(fsName, function(fs) {
                    if (!fs) {
                        fs = new FileSystem(fsName, {name:"", fullPath:"/"});
                    }
                    var result = (entry.isDirectory) ? new DirectoryEntry(entry.name, entry.fullPath, fs, entry.nativeURL) : new FileEntry(entry.name, entry.fullPath, fs, entry.nativeURL);
                    successCallback(result);
                });
            }
        }
        else {
            // no Entry object returned
            fail(FileError.NOT_FOUND_ERR);
        }
    };

    exec(success, fail, "File", "resolveLocalFileSystemURI", [uri]);
};
module.exports.resolveLocalFileSystemURI = function() {
    console.log("resolveLocalFileSystemURI is deprecated. Please call resolveLocalFileSystemURL instead.");
    module.exports.resolveLocalFileSystemURL.apply(this, arguments);
};
<|endoftext|>


<commit_before>var createIssue = require('gitlab-create-issue')
var _ = require('underscore')
var parseSlug = require('../../utils/utils.js').parseSlug

module.exports = function (publishItem, gitLabDone) {
  if (_.isEmpty(publishItem.creds)) {
    return gitLabDone(new Error('Not logged in. Please use `microplan login`'))
  }
  var parseSlugResult = parseSlug(publishItem.config.slug)
  var token = _.findWhere(publishItem.creds.loginOpts, {optName: 'token'}).answer
  if (_.isEmpty(token)) {
    return gitLabDone(new Error('Token mandatory'))
  }
  if (_.isEmpty(parseSlugResult.namespace) || _.isEmpty(parseSlugResult.project) ||
                  _.isEmpty(publishItem.plan.title)) {
    return gitLabDone(new Error('namespace, project, title mandatory'))
  }

  var manPayload =
    {
      namespace: parseSlugResult.namespace,
      project: parseSlugResult.project,
      title: publishItem.plan.title,
      privateToken: token
    }
  var optPayload = publishItem.plan
  createIssue(manPayload, optPayload, function (err, res) {
    if (err) {
      gitLabDone(err)
    } else {
      gitLabDone(null, res)
    }
  })
}
<commit_msg>normalizes assignee name<commit_after>var createIssue = require('gitlab-create-issue')
var _ = require('underscore')
var parseSlug = require('../../utils/utils.js').parseSlug

module.exports = function (publishItem, gitLabDone) {
  if (_.isEmpty(publishItem.creds)) {
    return gitLabDone(new Error('Not logged in. Please use `microplan login`'))
  }
  var parseSlugResult = parseSlug(publishItem.config.slug)
  var token = _.findWhere(publishItem.creds.loginOpts, {optName: 'token'}).answer
  if (_.isEmpty(token)) {
    return gitLabDone(new Error('Token mandatory'))
  }
  if (_.isEmpty(parseSlugResult.namespace) || _.isEmpty(parseSlugResult.project) ||
                  _.isEmpty(publishItem.plan.title)) {
    return gitLabDone(new Error('namespace, project, title mandatory'))
  }

  var manPayload =
    {
      namespace: parseSlugResult.namespace,
      project: parseSlugResult.project,
      title: publishItem.plan.title,
      privateToken: token
    }

  var optPayload = publishItem.plan
  if (!_.isEmpty(publishItem.plan.assignee)) {
    optPayload.assignee_name = publishItem.plan.assignee
  }
  createIssue(manPayload, optPayload, function (err, res) {
    if (err) {
      gitLabDone(err)
    } else {
      gitLabDone(null, res)
    }
  })
}
<|endoftext|>


<commit_before>import { connect } from 'react-redux'
import { playVideo } from '../actions'
import Player from '../components/Player'

function mapStateToProps(state) {
    return state.player
}

const VisiblePlayer = connect(mapStateToProps)(Player)

export default VisiblePlayer
<commit_msg>delete<commit_after>import { connect } from 'react-redux'
import Player from '../components/Player'

function mapStateToProps(state) {
    return state.player
}

const VisiblePlayer = connect(mapStateToProps)(Player)

export default VisiblePlayer
<|endoftext|>


<commit_before>function run (socket, userService) {
  console.log(`current user: ${userService.userSid}`);
  socket.connect(userService.userSid);
}

run.$inject = ['socketService', 'userService'];

export { run }
<commit_msg>Removed unused c.log().<commit_after>function run (socket, userService) {
  socket.connect(userService.userSid);
}

run.$inject = ['socketService', 'userService'];

export { run }
<|endoftext|>


<commit_before>const protobuf = require('./protobuf');
const protobufJS = require('@apollo/protobufjs/minimal');

// Remove Long support.  Our uint64s tend to be small (less
// than 104 days).
// https://github.com/protobufjs/protobuf.js/issues/1253
protobufJS.util.Long = undefined;
protobufJS.configure();

// Override the generated protobuf Traces.encode function so that it will look
// for Traces that are already encoded to Buffer as well as unencoded
// Traces. This amortizes the protobuf encoding time over each generated Trace
// instead of bunching it all up at once at sendReport time. In load tests, this
// change improved p99 end-to-end HTTP response times by a factor of 11 without
// a casually noticeable effect on p50 times. This also makes it easier for us
// to implement maxUncompressedReportSize as we know the encoded size of traces
// as we go.
const originalTracesEncode = protobuf.Traces.encode;
protobuf.Traces.encode = function(message, originalWriter) {
  const writer = originalTracesEncode(message, originalWriter);
  const encodedTraces = message.encodedTraces;
  if (encodedTraces != null && encodedTraces.length) {
    for (let i = 0; i < encodedTraces.length; ++i) {
      writer.uint32(/* id 1, wireType 2 =*/ 10);
      writer.bytes(encodedTraces[i]);
    }
  }
  return writer;
};

module.exports = protobuf;
<commit_msg>Fix protobuf type error<commit_after>const protobuf = require('./protobuf');
const protobufJS = require('@apollo/protobufjs/minimal');

// Remove Long support.  Our uint64s tend to be small (less
// than 104 days).
// https://github.com/protobufjs/protobuf.js/issues/1253
protobufJS.util.Long = undefined;
protobufJS.configure();

// Override the generated protobuf Traces.encode function so that it will look
// for Traces that are already encoded to Buffer as well as unencoded
// Traces. This amortizes the protobuf encoding time over each generated Trace
// instead of bunching it all up at once at sendReport time. In load tests, this
// change improved p99 end-to-end HTTP response times by a factor of 11 without
// a casually noticeable effect on p50 times. This also makes it easier for us
// to implement maxUncompressedReportSize as we know the encoded size of traces
// as we go.
const originalTracesEncode = protobuf.TracesAndStats.encode;
protobuf.TracesAndStats.encode = function(message, originalWriter) {
  const writer = originalTracesEncode(message, originalWriter);
  const encodedTraces = message.encodedTraces;
  if (encodedTraces != null && encodedTraces.length) {
    for (let i = 0; i < encodedTraces.length; ++i) {
      writer.uint32(/* id 1, wireType 2 =*/ 10);
      writer.bytes(encodedTraces[i]);
    }
  }
  return writer;
};

module.exports = protobuf;
<|endoftext|>


<commit_before>// @ts-nocheck
/*
 * Copyright 2017, Red Hat, Inc. and individual contributors
 *  as indicated by the @author tags. See the copyright.txt file in the
 *  distribution for a full listing of individual contributors.
 *
 *  This is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU Lesser General Public License as
 *  published by the Free Software Foundation; either version 2.1 of
 *  the License, or (at your option) any later version.
 *
 *  This software is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this software; if not, write to the Free
 *  Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 *  02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

import React from 'react'
import { Component } from 'react'
import * as PropTypes from 'prop-types'
import {connect} from 'react-redux'
import TMXExportModal from '../../components/TMX/TMXExportModal'
import { isAdmin } from '../../config'
import Helmet from 'react-helmet'

import {
  showExportTMXModal
} from '../../actions/tmx-actions'

/**
 * Root component for Admin Page
 */
class Admin extends Component {
  static propTypes = {
    toggleTMXExportModal: PropTypes.func.isRequired
  }

  render () {
    if (!isAdmin) {
      return (

          <Helmet title='Administration' />

You are not authorised to access to this page

      )
    }
    return (

        <Helmet title='Administration' />

            <TMXExportModal />

    )
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    toggleTMXExportModal: (show) => {
      dispatch(showExportTMXModal(show))
    }
  }
}

export default connect(undefined, mapDispatchToProps)(Admin)
<commit_msg>Revert "fix(ZNTA-2313) add Helmet to admin/home"<commit_after>// @ts-nocheck
/*
 * Copyright 2017, Red Hat, Inc. and individual contributors
 *  as indicated by the @author tags. See the copyright.txt file in the
 *  distribution for a full listing of individual contributors.
 *
 *  This is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU Lesser General Public License as
 *  published by the Free Software Foundation; either version 2.1 of
 *  the License, or (at your option) any later version.
 *
 *  This software is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this software; if not, write to the Free
 *  Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 *  02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

import React from 'react'
import { Component } from 'react'
import * as PropTypes from 'prop-types'
import {connect} from 'react-redux'
import TMXExportModal from '../../components/TMX/TMXExportModal'
import { isAdmin } from '../../config'

import {
  showExportTMXModal
} from '../../actions/tmx-actions'

/**
 * Root component for Admin Page
 */
class Admin extends Component {
  static propTypes = {
    toggleTMXExportModal: PropTypes.func.isRequired
  }

  render () {
    if (!isAdmin) {
      return (

You are not authorised to access to this page

      )
    }
    return (

          <TMXExportModal />

    )
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    toggleTMXExportModal: (show) => {
      dispatch(showExportTMXModal(show))
    }
  }
}

export default connect(undefined, mapDispatchToProps)(Admin)
<|endoftext|>


<commit_before>DevBox.controller( 'ToolsShowCtrl', [ '$scope' , '$resource', '$http', '$location', '$routeParams', '$rootScope', 'showdown',
 function( $scope, $resource, $http, $location, $routeParams, $rootScope, showdown ){
  $rootScope.isAuthenticated;
  // console.log('New Tools Ctrl Loaded');
  $scope.favorited = false;

  $scope.number = 5;
  $scope.getNumber = function(num) {
      return new Array(num);
  }

  $scope.addTool = function( toolId ){
    if ( $scope.tool.favorited === false ) {
      $http.post('/api/users/' + toolId + '/tool').success( function( data ){
        if (data.result === true){
          $scope.tool.favorited = true;
          Materialize.toast( 'added to toolbox', 4000)
        }
      } )
    } else if ( $scope.tool.favorited === true ) {
      $http.delete( '/api/users/delete/tool/' + toolId ).success( function( data ){
        if (data.result === true){
          $scope.tool.favorited = false;
          Materialize.toast( 'removed from toolbox', 4000)
        }
      } )
    }
  }

  Tool = $resource('/api/tools/:id', null, {
    'update': { method:'PUT' }
  });

// <<<<<<< HEAD
  Review = $resource('/api/tools/' + $routeParams.id + '/reviews', null, {
    'update': { method:'PUT' }
  });

  // console.log("RouteParams:", $routeParams.id);
  // Tool.get({id:$routeParams.id},function(data) {
  //   // $rootScope.loading = false;
  //   console.log("Tool.get call running");
  //   console.log(data);
  //   $scope.tool = data.result;
  // },function(err){
  //   console.log(err);
  // });
// =======

  var init = function(){
      Tool.get({id:$routeParams.id},function(data) {
        // $rootScope.loading = false;
        $scope.categories = data.navCats;
        $scope.tags = data.navTags;
        $scope.tool = data.result;
        console.log($scope.tags)
      },function(err){
        console.log(err);
      });
    }

    init()
// >>>>>>> master

  $scope.saveReview = function() {
    console.log("Add Review Function");
    var content = editor.exportFile();
    var review = new Review();
    review.post = content;
    review.tool_id = $routeParams.id;
    review.$save(function(data) {
      console.log(data);
      // Add new comment to list
      $scope.tool.reviews_users.unshift(data.result);

      // Clear the editor
      editor.edit();
      editor.getElement('editor').body.innerHTML = '';
    })
  }

}])
<commit_msg>Remove commented code from old merge<commit_after>DevBox.controller( 'ToolsShowCtrl', [ '$scope' , '$resource', '$http', '$location', '$routeParams', '$rootScope', 'showdown',
 function( $scope, $resource, $http, $location, $routeParams, $rootScope, showdown ){
  $rootScope.isAuthenticated;

  $scope.favorited = false;
  $scope.number = 5;

  $scope.getNumber = function(num) {
      return new Array(num);
  }

  $scope.addTool = function( toolId ){
    if ( $scope.tool.favorited === false ) {
      $http.post('/api/users/' + toolId + '/tool').success( function( data ){
        if (data.result === true){
          $scope.tool.favorited = true;
          Materialize.toast( 'added to toolbox', 4000)
        }
      } )
    } else if ( $scope.tool.favorited === true ) {
      $http.delete( '/api/users/delete/tool/' + toolId ).success( function( data ){
        if (data.result === true){
          $scope.tool.favorited = false;
          Materialize.toast( 'removed from toolbox', 4000)
        }
      } )
    }
  }

  Tool = $resource('/api/tools/:id', null, {
    'update': { method:'PUT' }
  });

  Review = $resource('/api/tools/' + $routeParams.id + '/reviews', null, {
    'update': { method:'PUT' }
  });

  var init = function(){
      Tool.get({id:$routeParams.id},function(data) {
        // $rootScope.loading = false;
        $scope.categories = data.navCats;
        $scope.tags = data.navTags;
        $scope.tool = data.result;
        console.log($scope.tags)
      },function(err){
        console.log(err);
      });
    }

  init()

  $scope.saveReview = function() {
    console.log("Add Review Function");
    var content = editor.exportFile();
    var review = new Review();
    review.post = content;
    review.tool_id = $routeParams.id;
    review.$save(function(data) {
      console.log(data);
      // Add new comment to list
      $scope.tool.reviews_users.unshift(data.result);

      // Clear the editor
      editor.edit();
      editor.getElement('editor').body.innerHTML = '';
    })
  }

}])
<|endoftext|>