<commit_before>/*---------------------------------------------------------
 * OpenERP Web Boostrap Code
 *---------------------------------------------------------*/

/**
 * @name openerp
 * @namespace openerp
 *
 * Each module can return a deferred. In that case, the module is marked as loaded
 * only when the deferred is resolved, and its value is equal to the resolved value.
 * The module can be rejected (unloaded). This will be logged in the console as info.
 *
 * logs:
 *      Missing dependencies:
 *          These modules do not appear in the page. It is possible that the
 *          JavaScript file is not in the page or that the module name is wrong
 *      Failed modules:
 *          A javascript error is detected
 *      Rejected modules:
 *          The module returns a rejected deferred. It (and its dependent modules)
 *          is not loaded.
 *      Rejected linked modules:
 *          Modules who depend on a rejected module
 *      Non loaded modules:
 *          Modules who depend on a missing or a failed module
 *      Debug:
 *          Non loaded or failed module informations for debugging
 */

(function() {
    "use strict";

    var jobs = [];
    var factories = Object.create(null);
    var job_names = [];
    var job_deps = [];
    var job_deferred = [];

    var services = Object.create({
        qweb: new QWeb2.Engine(),
        $: $,
        _: _,
    });

    var commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg;
    var cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g;

    var debug = ($.deparam($.param.querystring()).debug !== undefined);

    var odoo = window.odoo = {
        testing: typeof QUnit === "object",
        debug: debug,
        remaining_jobs: jobs,

        __DEBUG__: {
            get_dependencies: function (name, transitive) {
                var deps = name instanceof Array ? name: [name],
                    changed;
                do {
                    changed = false;
                    _.each(job_deps, function (dep) {
                        if (_.contains(deps, dep.to) && (!_.contains(deps, dep.from))) {
                            deps.push(dep.from);
                            changed = true;
                        }
                    });
                } while (changed && transitive);
                return deps;
            },
            get_dependents: function (name) {
                return _.pluck(_.where(job_deps, {from: name}), 'to');
            },
            get_waited_jobs: function () {
                return _.uniq(_.map(jobs, function(job) {return job.name;}));
            },
            get_missing_jobs: function () {
                var self = this;
                var waited = this.get_waited_jobs();
                var missing = [];
                _.each(waited, function(job) {
                    _.each(self.get_dependencies(job), function(job) {
                        if (!(job in self.services)) {
                            missing.push(job);
                        }
                    });
                });
                return _.filter(_.difference(_.uniq(missing), waited), function (job) {return !job.error;});
            },
            get_failed_jobs: function () {
                return _.filter(jobs, function (job) {return !!job.error;});
            },
            factories: factories,
            services: services,
        },
        define: function () {
            var args = Array.prototype.slice.call(arguments);
            var name = typeof args[0] === 'string' ? args.shift() : _.uniqueId('__job');
            var factory = args[args.length - 1];
            var deps;
            if (args[0] instanceof Array) {
                deps = args[0];
            } else {
                deps = [];
                factory.toString()
                    .replace(commentRegExp, '')
                    .replace(cjsRequireRegExp, function (match, dep) {
                        deps.push(dep);
                    });
            }

            if (odoo.debug) {
                if (!(deps instanceof Array)) {
                    throw new Error ('Dependencies should be defined by an array', deps);
                }
                if (typeof factory !== 'function') {
                    throw new Error ('Factory should be defined by a function', factory);
                }
                if (typeof name !== 'string') {
                    throw new Error("Invalid name definition (should be a string", name);
                }
                if (name in factories) {
                    throw new Error("Service " + name + " already defined");
                }
            }

            factory.deps = deps;
            factories[name] = factory;

            jobs.push({
                name: name,
                factory: factory,
                deps: deps,
            });

            job_names.push(name);
            _.each(deps, function (dep) {
                job_deps.push({from:dep, to:name});
            });

            this.process_jobs(jobs, services);
        },
        log: function () {
            if (jobs.length) {
                var debug_jobs = {};
                var rejected = [];
                var rejected_linked = [];
                var job;
                var jobdep;

                for (var k=0; k<jobs.length; k++) {
                    debug_jobs[jobs[k].name] = job = {
                        dependencies: jobs[k].deps,
                        dependents: odoo.__DEBUG__.get_dependents(jobs[k].name),
                        name: jobs[k].name
                    };
                    if (jobs[k].error) {
                        job.error = jobs[k].error;
                    }
                    if (jobs[k].rejected) {
                        job.rejected = jobs[k].rejected;
                        rejected.push(job.name);
                    }
                    var deps = odoo.__DEBUG__.get_dependencies( job.name );
                    for (var i=0; i<deps.length; i++) {
                        if (job.name !== deps[i] && !(deps[i] in services)) {
                            jobdep = debug_jobs[deps[i]] || (deps[i] in factories && _.find(jobs, function (job) { return job.name === deps[i];}));
                            if (jobdep && jobdep.rejected) {
                                if (!job.rejected) {
                                    job.rejected = [];
                                    rejected_linked.push(job.name);
                                }
                                job.rejected.push(deps[i]);
                            } else {
                                if (!job.missing) {
                                    job.missing = [];
                                }
                                job.missing.push(deps[i]);
                            }
                        }
                    }
                }
                var missing = odoo.__DEBUG__.get_missing_jobs();
                var failed = odoo.__DEBUG__.get_failed_jobs();
                var unloaded = _.filter(debug_jobs, function (job) { return job.missing; });

                var log = [(_.isEmpty(failed) ? (_.isEmpty(unloaded) ? 'info' : 'warning' ) : 'error') + ':', 'Some modules could not be started'];
                if (missing.length)             log.push('\nMissing dependencies:   ', missing);
                if (!_.isEmpty(failed))         log.push('\nFailed modules:         ', _.pluck(failed, 'name'));
                if (!_.isEmpty(rejected))       log.push('\nRejected modules:       ', rejected);
                if (!_.isEmpty(rejected_linked))log.push('\nRejected linked modules:', rejected_linked);
                if (!_.isEmpty(unloaded))       log.push('\nNon loaded modules:     ', _.pluck(unloaded, 'name'));
                if (odoo.debug && !_.isEmpty(debug_jobs)) log.push('\nDebug:                  ', debug_jobs);

                if (odoo.debug || !_.isEmpty(failed) || !_.isEmpty(unloaded)) {
                    console[_.isEmpty(unloaded) ? 'info' : 'error'].apply(console, log);
                }
            }
        },
        process_jobs: function (jobs, services) {
            var job;
            var require;
            var time;

            function process_job (job) {
                var require = make_require(job);
                try {
                    var def = $.Deferred();
                    $.when(job.factory.call(null, require)).then(
                        function (data) {
                            services[job.name] = data;
                            clearTimeout(time);
                            time = _.defer(odoo.process_jobs, jobs, services);
                            def.resolve();
                        }, function (e) {
                            job.rejected = e || true;
                            jobs.push(job);
                            def.resolve();
                        });
                    jobs.splice(jobs.indexOf(job), 1);
                    job_deferred.push(def);
                } catch (e) {
                    job.error = e;
                }
            }

            function is_ready (job) {
                return !job.error && !job.rejected && _.every(job.factory.deps, function (name) { return name in services; });
            }

            function make_require (job) {
                var deps = _.pick(services, job.deps);

                function require (name) {
                    if (!(name in deps)) {
                        console.error('Undefined dependency: ', name);
                    } else {
                        require.__require_calls++;
                    }
                    return deps[name];
                }

                require.__require_calls = 0;
                return require;
            }

            while (jobs.length && (job = _.find(jobs, is_ready))) {
                process_job(job);
            }

            return services;
        }
    };

    // automatically log errors detected when loading modules
    var log_when_loaded = function () {
        _.delay(function () {
            var len = job_deferred.length;
            $.when.apply($, job_deferred).then(function () {
                if (len === job_deferred.length) {
                    odoo.log();
                } else {
                    log_when_loaded();
                }
            });
        }, 100);
    };
    $(log_when_loaded);

})();
<commit_msg>[FIX] web: increase log timer<commit_after>/*---------------------------------------------------------
 * OpenERP Web Boostrap Code
 *---------------------------------------------------------*/

/**
 * @name openerp
 * @namespace openerp
 *
 * Each module can return a deferred. In that case, the module is marked as loaded
 * only when the deferred is resolved, and its value is equal to the resolved value.
 * The module can be rejected (unloaded). This will be logged in the console as info.
 *
 * logs:
 *      Missing dependencies:
 *          These modules do not appear in the page. It is possible that the
 *          JavaScript file is not in the page or that the module name is wrong
 *      Failed modules:
 *          A javascript error is detected
 *      Rejected modules:
 *          The module returns a rejected deferred. It (and its dependent modules)
 *          is not loaded.
 *      Rejected linked modules:
 *          Modules who depend on a rejected module
 *      Non loaded modules:
 *          Modules who depend on a missing or a failed module
 *      Debug:
 *          Non loaded or failed module informations for debugging
 */

(function() {
    "use strict";

    var jobs = [];
    var factories = Object.create(null);
    var job_names = [];
    var job_deps = [];
    var job_deferred = [];

    var services = Object.create({
        qweb: new QWeb2.Engine(),
        $: $,
        _: _,
    });

    var commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg;
    var cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g;

    var debug = ($.deparam($.param.querystring()).debug !== undefined);

    var odoo = window.odoo = {
        testing: typeof QUnit === "object",
        debug: debug,
        remaining_jobs: jobs,

        __DEBUG__: {
            get_dependencies: function (name, transitive) {
                var deps = name instanceof Array ? name: [name],
                    changed;
                do {
                    changed = false;
                    _.each(job_deps, function (dep) {
                        if (_.contains(deps, dep.to) && (!_.contains(deps, dep.from))) {
                            deps.push(dep.from);
                            changed = true;
                        }
                    });
                } while (changed && transitive);
                return deps;
            },
            get_dependents: function (name) {
                return _.pluck(_.where(job_deps, {from: name}), 'to');
            },
            get_waited_jobs: function () {
                return _.uniq(_.map(jobs, function(job) {return job.name;}));
            },
            get_missing_jobs: function () {
                var self = this;
                var waited = this.get_waited_jobs();
                var missing = [];
                _.each(waited, function(job) {
                    _.each(self.get_dependencies(job), function(job) {
                        if (!(job in self.services)) {
                            missing.push(job);
                        }
                    });
                });
                return _.filter(_.difference(_.uniq(missing), waited), function (job) {return !job.error;});
            },
            get_failed_jobs: function () {
                return _.filter(jobs, function (job) {return !!job.error;});
            },
            factories: factories,
            services: services,
        },
        define: function () {
            var args = Array.prototype.slice.call(arguments);
            var name = typeof args[0] === 'string' ? args.shift() : _.uniqueId('__job');
            var factory = args[args.length - 1];
            var deps;
            if (args[0] instanceof Array) {
                deps = args[0];
            } else {
                deps = [];
                factory.toString()
                    .replace(commentRegExp, '')
                    .replace(cjsRequireRegExp, function (match, dep) {
                        deps.push(dep);
                    });
            }

            if (odoo.debug) {
                if (!(deps instanceof Array)) {
                    throw new Error ('Dependencies should be defined by an array', deps);
                }
                if (typeof factory !== 'function') {
                    throw new Error ('Factory should be defined by a function', factory);
                }
                if (typeof name !== 'string') {
                    throw new Error("Invalid name definition (should be a string", name);
                }
                if (name in factories) {
                    throw new Error("Service " + name + " already defined");
                }
            }

            factory.deps = deps;
            factories[name] = factory;

            jobs.push({
                name: name,
                factory: factory,
                deps: deps,
            });

            job_names.push(name);
            _.each(deps, function (dep) {
                job_deps.push({from:dep, to:name});
            });

            this.process_jobs(jobs, services);
        },
        log: function () {
            if (jobs.length) {
                var debug_jobs = {};
                var rejected = [];
                var rejected_linked = [];
                var job;
                var jobdep;

                for (var k=0; k<jobs.length; k++) {
                    debug_jobs[jobs[k].name] = job = {
                        dependencies: jobs[k].deps,
                        dependents: odoo.__DEBUG__.get_dependents(jobs[k].name),
                        name: jobs[k].name
                    };
                    if (jobs[k].error) {
                        job.error = jobs[k].error;
                    }
                    if (jobs[k].rejected) {
                        job.rejected = jobs[k].rejected;
                        rejected.push(job.name);
                    }
                    var deps = odoo.__DEBUG__.get_dependencies( job.name );
                    for (var i=0; i<deps.length; i++) {
                        if (job.name !== deps[i] && !(deps[i] in services)) {
                            jobdep = debug_jobs[deps[i]] || (deps[i] in factories && _.find(jobs, function (job) { return job.name === deps[i];}));
                            if (jobdep && jobdep.rejected) {
                                if (!job.rejected) {
                                    job.rejected = [];
                                    rejected_linked.push(job.name);
                                }
                                job.rejected.push(deps[i]);
                            } else {
                                if (!job.missing) {
                                    job.missing = [];
                                }
                                job.missing.push(deps[i]);
                            }
                        }
                    }
                }
                var missing = odoo.__DEBUG__.get_missing_jobs();
                var failed = odoo.__DEBUG__.get_failed_jobs();
                var unloaded = _.filter(debug_jobs, function (job) { return job.missing; });

                var log = [(_.isEmpty(failed) ? (_.isEmpty(unloaded) ? 'info' : 'warning' ) : 'error') + ':', 'Some modules could not be started'];
                if (missing.length)             log.push('\nMissing dependencies:   ', missing);
                if (!_.isEmpty(failed))         log.push('\nFailed modules:         ', _.pluck(failed, 'name'));
                if (!_.isEmpty(rejected))       log.push('\nRejected modules:       ', rejected);
                if (!_.isEmpty(rejected_linked))log.push('\nRejected linked modules:', rejected_linked);
                if (!_.isEmpty(unloaded))       log.push('\nNon loaded modules:     ', _.pluck(unloaded, 'name'));
                if (odoo.debug && !_.isEmpty(debug_jobs)) log.push('\nDebug:                  ', debug_jobs);

                if (odoo.debug || !_.isEmpty(failed) || !_.isEmpty(unloaded)) {
                    console[_.isEmpty(unloaded) ? 'info' : 'error'].apply(console, log);
                }
            }
        },
        process_jobs: function (jobs, services) {
            var job;
            var require;
            var time;

            function process_job (job) {
                var require = make_require(job);
                try {
                    var def = $.Deferred();
                    $.when(job.factory.call(null, require)).then(
                        function (data) {
                            services[job.name] = data;
                            clearTimeout(time);
                            time = _.defer(odoo.process_jobs, jobs, services);
                            def.resolve();
                        }, function (e) {
                            job.rejected = e || true;
                            jobs.push(job);
                            def.resolve();
                        });
                    jobs.splice(jobs.indexOf(job), 1);
                    job_deferred.push(def);
                } catch (e) {
                    job.error = e;
                }
            }

            function is_ready (job) {
                return !job.error && !job.rejected && _.every(job.factory.deps, function (name) { return name in services; });
            }

            function make_require (job) {
                var deps = _.pick(services, job.deps);

                function require (name) {
                    if (!(name in deps)) {
                        console.error('Undefined dependency: ', name);
                    } else {
                        require.__require_calls++;
                    }
                    return deps[name];
                }

                require.__require_calls = 0;
                return require;
            }

            while (jobs.length && (job = _.find(jobs, is_ready))) {
                process_job(job);
            }

            return services;
        }
    };

    // automatically log errors detected when loading modules
    var log_when_loaded = function () {
        _.delay(function () {
            var len = job_deferred.length;
            $.when.apply($, job_deferred).then(function () {
                if (len === job_deferred.length) {
                    odoo.log();
                } else {
                    log_when_loaded();
                }
            });
        }, 1000);
    };
    $(log_when_loaded);

})();
<|endoftext|>


<commit_before>/**
 * Tatoeba Project, free collaborative creation of multilingual corpuses project
 * Copyright (C) 2011  HO Ngoc Phuong Trang <tranglich@gmail.com>
 *
 * This program 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/>.
 */

function translationLink(action, sentenceId, translationId, langFilter)
{
    var rootUrl = get_tatoeba_root_url();

    // Show the loading icon
    $('#link_' + sentenceId + '_' + translationId).blur().html(
        "

"
    );
    $("#_" + sentenceId + "_message").remove();

    $.post(
        rootUrl + "/links/" + action + "/" + sentenceId + "/" + translationId,
        {
            'returnTranslations': true,
            'langFilter' : langFilter
        },
        function(data){
            $("#_" + sentenceId + "_translations").replaceWith(data).show();
        },
        'html'
    );
}
<commit_msg>Keep 'expanded' status after {un,}linking<commit_after>/**
 * Tatoeba Project, free collaborative creation of multilingual corpuses project
 * Copyright (C) 2011  HO Ngoc Phuong Trang <tranglich@gmail.com>
 *
 * This program 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/>.
 */

function translationLink(action, sentenceId, translationId, langFilter)
{
    var rootUrl = get_tatoeba_root_url();

    // Show the loading icon
    $('#link_' + sentenceId + '_' + translationId).blur().html(
        "

"
    );
    $("#_" + sentenceId + "_message").remove();

    $.post(
        rootUrl + "/links/" + action + "/" + sentenceId + "/" + translationId,
        {
            'returnTranslations': true,
            'langFilter' : langFilter
        },
        function(data){
            var wasExpanded = !$("#_" + sentenceId + "_translations .showLink").is(":visible");
            $("#_" + sentenceId + "_translations").replaceWith(data).show();
            if (wasExpanded) {
                $("#_" + sentenceId + "_translations .showLink").trigger("click");
            }
        },
        'html'
    );
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013, Twitter Inc. and other contributors
 * Released under the MIT License
 */

var vows = require('vows'),
    assert = require('assert');

var WebPageTest = require('../lib/webpagetest'),
    NockServer = require('./helpers/nock-server'),
    ResponseObjects = require('./helpers/response-objects');

var wptNockServer = new NockServer('http://example.com');

vows.describe('Dry Run').addBatch({
  'An Example WebPageTest Nock Server': {
    topic: new WebPageTest('example.com'),

    'gets a test status request': {
      topic: function (wpt) {
        wpt.getTestStatus('120816_V2_2', this.callback);
      },
      'returns the test status object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testStatus);
      }
    },

    'gets a test results request': {
      topic: function (wpt) {
        wpt.getTestResults('120816_V2_2', this.callback);
      },
      'returns the test results object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testResults);
      }
    },

    'gets a test results for multi runs with default median metric request': {
      topic: function (wpt) {
        wpt.getTestResults('130619_KK_6A2', this.callback);
      },
      'returns the test results object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testResultsMultiRunsDefaultMedianMetric);
      }
    },

    'gets a test results for multi runs with custom median metric request': {
      topic: function (wpt) {
        wpt.getTestResults('130619_KK_6A2', {medianMetric: 'TTFB'}, this.callback);
      },
      'returns the test results object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testResultsMultiRunsTTFBMedianMetric);
      }
    },

    'gets the locations list request': {
      topic: function (wpt) {
        wpt.getLocations(this.callback);
      },
      'returns the locations list object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.locations);
      }
    },

    'gets the testers list request': {
      topic: function (wpt) {
        wpt.getTesters(this.callback);
      },
      'returns the testers list object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testers);
      }
    },

    'gets a simple test request': {
      topic: function (wpt) {
        wpt.runTest('http://twitter.com/marcelduran', this.callback);
      },
      'returns the run test object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.runTest);
      }
    },

    'gets a custom test request': {
      topic: function (wpt) {
        wpt.runTest('http://twitter.com/marcelduran', {
          'location': 'Local_Firefox_Chrome:Chrome',
          label: 'test 123',
          runs: 3,
          firstViewOnly: true,
          timeline: true,
          netLog: true,
          fullResolutionScreenshot: true
        }, this.callback);
      },
      'returns the run test object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.runTest);
      }
    },

    'gets a script test request': {
      topic: function (wpt) {
        var script = wpt.scriptToString([
          {logData:    0                           },
          {navigate:   'http://foo.com/login'      },
          '// log some data',
          {logData:    1                           },
          {setValue:   ['name=username', 'johndoe']},
          {setValue:   ['name=password', '12345']  },
          {submitForm: 'action=http://foo.com/main'},
          'waitForComplete'
        ]);

        wpt.runTest(script, this.callback);
      },
      'returns the run test object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.runTest);
      }
    },

    'gets a cancel test request': {
      topic: function (wpt) {
        wpt.cancelTest('120816_V2_2', this.callback);
      },
      'returns the test cancelled object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.cancel);
      }
    },

    'gets page speed data request': {
      topic: function (wpt) {
        wpt.getPageSpeedData('120816_V2_2', this.callback);
      },
      'returns the page speed object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.pageSpeed);
      }
    },

    'gets HAR data request': {
      topic: function (wpt) {
        wpt.getHARData('120816_V2_2', this.callback);
      },
      'returns the HAR object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.har);
      }
    },

    'gets utilization data request': {
      topic: function (wpt) {
        wpt.getUtilizationData('120816_V2_2', this.callback);
      },
      'returns the utilization object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.utilization);
      }
    },

    'gets request data request': {
      topic: function (wpt) {
        wpt.getRequestData('120816_V2_2', this.callback);
      },
      'returns the request object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.request);
      }
    },

    'gets timeline data request': {
      topic: function (wpt) {
        wpt.getTimelineData('120816_V2_2', this.callback);
      },
      'returns the timeline object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.timeline);
      }
    },

    'gets net log data request': {
      topic: function (wpt) {
        wpt.getNetLogData('120816_V2_2', this.callback);
      },
      'returns the net log object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.netLog);
      }
    },

    'gets console log data request': {
      topic: function (wpt) {
        wpt.getConsoleLogData('120816_V2_2', this.callback);
      },
      'returns the console log object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.consoleLog);
      }
    },

    'gets test info request': {
      topic: function (wpt) {
        wpt.getTestInfo('120816_V2_2', this.callback);
      },
      'returns the test info object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testInfo);
      }
    },

    'gets a waterfall image request': {
      topic: function (wpt) {
        wpt.getWaterfallImage('120816_V2_2', {dataURI: true}, this.callback);
      },
      'returns the waterfall data URI string': function (err, data, info) {
        if (err) throw err;
        assert.equal(data, ResponseObjects.waterfall);
        assert.deepEqual(info, {type: 'image/png', encoding: 'utf8'});
      }
    },

    'gets a waterfall thumbnail request': {
      topic: function (wpt) {
        wpt.getWaterfallImage('120816_V2_2', {
          thumbnail: true,
          dataURI: true
        }, this.callback);
      },
      'returns the waterfall thumbnail data URI string':
        function (err, data, info) {
          if (err) throw err;
          assert.equal(data, ResponseObjects.waterfallThumbnail);
          assert.deepEqual(info, {type: 'image/png', encoding: 'utf8'});
        }
    },

    'gets a screenshot request': {
      topic: function (wpt) {
        wpt.getScreenshotImage('120816_V2_2', {dataURI: true}, this.callback);
      },
      'returns the screenshot data URI string':
        function (err, data, info) {
          if (err) throw err;
          assert.equal(data, ResponseObjects.screenshot);
          assert.deepEqual(info, {type: 'image/jpeg', encoding: 'utf8'});
        }
    },

    'gets a screenshot thumbnail request': {
      topic: function (wpt) {
        wpt.getScreenshotImage('120816_V2_2', {
          thumbnail: true,
          dataURI: true
        }, this.callback);
      },
      'returns the screenshot thumbail data URI string':
        function (err, data, info) {
          if (err) throw err;
          assert.equal(data, ResponseObjects.screenshotThumbnail);
          assert.deepEqual(info, {type: 'image/jpeg', encoding: 'utf8'});
        }
    },

    'gets a screenshot in full resolution request': {
      topic: function (wpt) {
        wpt.getScreenshotImage('120816_V2_2', {
          fullResolution: true,
          dataURI: true
        }, this.callback);
      },
      'returns the screenshot in full resolution data URI string':
        function (err, data, info) {
          if (err) throw err;
          assert.equal(data, ResponseObjects.screenshotFullResolution);
          assert.deepEqual(info, {type: 'image/png', encoding: 'utf8'});
        }
    },

    // not found / invalid

    'gets an invalid test status request': {
      topic: function (wpt) {
        wpt.getTestStatus('120816_V2_3', this.callback);
      },
      'returns a not found test status object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testStatusNotFound);
      }
    },

    'gets an invalid test results request': {
      topic: function (wpt) {
        wpt.getTestResults('120816_V2_3', this.callback);
      },
      'returns a not found test results object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testResultsNotFound);
      }
    },

    'gets an invalid test request': {
      topic: function (wpt) {
        wpt.runTest(undefined, this.callback);
      },
      'returns an invalid run test object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.runTestInvalid);
      }
    },

    'gets an invalid file request': {
      topic: function (wpt) {
        wpt.getPageSpeedData('120816_V2_3', this.callback);
      },
      'returns a 404 error': function (err, data) {
        assert.equal(err.code, 404);
        assert.equal(err.message, 'Not Found');
        assert.equal(data, undefined);
      }
    },

    'gets an invalid HAR data request': {
      topic: function (wpt) {
        wpt.getHARData('120816_V2_3', this.callback);
      },
      'returns an empty HAR object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.harNotFound);
      }
    },

    'gets an invalid waterfall image request': {
      topic: function (wpt) {
        wpt.getWaterfallImage('120816_V2_3', {dataURI: true}, this.callback);
      },
      'returns an empty waterfall data URI string':
        function (err, data, info) {
          if (err) throw err;
          assert.equal(data, ResponseObjects.waterfallNotFound);
          assert.deepEqual(info, {type: 'image/png', encoding: 'utf8'});
        }
    },

    'gets an invalid waterfall thumbnail request': {
      topic: function (wpt) {
        wpt.getWaterfallImage('120816_V2_3', {
          thumbnail: true,
          dataURI: true
        }, this.callback);
      },
      'returns an empty waterfall thumbnail data URI string':
        function (err, data, info) {
          if (err) throw err;
          assert.equal(data, ResponseObjects.waterfallThumbnailNotFound);
          assert.deepEqual(info, {type: 'image/png', encoding: 'utf8'});
        }
    },

    'gets an invalid screenshot thumbnail request': {
      topic: function (wpt) {
        wpt.getScreenshotImage('120816_V2_3', {
          thumbnail: true,
          dataURI: true
        }, this.callback);
      },
      'returns a 404 error': function (err, data, info) {
        assert.equal(err.code, 404);
        assert.equal(err.message, 'Not Found');
        assert.equal(data, undefined);
      }
    },

    'gets a cancel test of already cancelled test request': {
      topic: function (wpt) {
        wpt.cancelTest('120816_V2_3', this.callback);
      },
      'returns the test not cancelled object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.cancelNotCancelled);
      }
    },

    'gets a cancel test of an invalid test request': {
      topic: function (wpt) {
        wpt.cancelTest('120816_V2_4', this.callback);
      },
      'returns a 404 error': function (err, data) {
        assert.equal(err.code, 404);
        assert.equal(err.message, 'Not Found');
        assert.equal(data, undefined);
      }
    },

    'gets a test request for an api key required server': {
      topic: function (wpt) {
        wpt.runTest('http://apikey.com', this.callback);
      },
      'returns the no api key response object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.runTestNoAPIKey);
      }
    },

    'gets a test request for an api key required server with invalid key': {
      topic: function (wpt) {
        wpt.runTest('http://apikey.com', {key: '12345'}, this.callback);
      },
      'returns the no api key response object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.runTestInvalidAPIKey);
      }
    }

  }
}).export(module);
<commit_msg>renamed test suit<commit_after>/**
 * Copyright (c) 2013, Twitter Inc. and other contributors
 * Released under the MIT License
 */

var vows = require('vows'),
    assert = require('assert');

var WebPageTest = require('../lib/webpagetest'),
    NockServer = require('./helpers/nock-server'),
    ResponseObjects = require('./helpers/response-objects');

var wptNockServer = new NockServer('http://example.com');

vows.describe('Mock WPT Server').addBatch({
  'An Example WebPageTest Nock Server': {
    topic: new WebPageTest('example.com'),

    'gets a test status request': {
      topic: function (wpt) {
        wpt.getTestStatus('120816_V2_2', this.callback);
      },
      'returns the test status object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testStatus);
      }
    },

    'gets a test results request': {
      topic: function (wpt) {
        wpt.getTestResults('120816_V2_2', this.callback);
      },
      'returns the test results object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testResults);
      }
    },

    'gets a test results for multi runs with default median metric request': {
      topic: function (wpt) {
        wpt.getTestResults('130619_KK_6A2', this.callback);
      },
      'returns the test results object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testResultsMultiRunsDefaultMedianMetric);
      }
    },

    'gets a test results for multi runs with custom median metric request': {
      topic: function (wpt) {
        wpt.getTestResults('130619_KK_6A2', {medianMetric: 'TTFB'}, this.callback);
      },
      'returns the test results object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testResultsMultiRunsTTFBMedianMetric);
      }
    },

    'gets the locations list request': {
      topic: function (wpt) {
        wpt.getLocations(this.callback);
      },
      'returns the locations list object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.locations);
      }
    },

    'gets the testers list request': {
      topic: function (wpt) {
        wpt.getTesters(this.callback);
      },
      'returns the testers list object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testers);
      }
    },

    'gets a simple test request': {
      topic: function (wpt) {
        wpt.runTest('http://twitter.com/marcelduran', this.callback);
      },
      'returns the run test object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.runTest);
      }
    },

    'gets a custom test request': {
      topic: function (wpt) {
        wpt.runTest('http://twitter.com/marcelduran', {
          'location': 'Local_Firefox_Chrome:Chrome',
          label: 'test 123',
          runs: 3,
          firstViewOnly: true,
          timeline: true,
          netLog: true,
          fullResolutionScreenshot: true
        }, this.callback);
      },
      'returns the run test object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.runTest);
      }
    },

    'gets a script test request': {
      topic: function (wpt) {
        var script = wpt.scriptToString([
          {logData:    0                           },
          {navigate:   'http://foo.com/login'      },
          '// log some data',
          {logData:    1                           },
          {setValue:   ['name=username', 'johndoe']},
          {setValue:   ['name=password', '12345']  },
          {submitForm: 'action=http://foo.com/main'},
          'waitForComplete'
        ]);

        wpt.runTest(script, this.callback);
      },
      'returns the run test object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.runTest);
      }
    },

    'gets a cancel test request': {
      topic: function (wpt) {
        wpt.cancelTest('120816_V2_2', this.callback);
      },
      'returns the test cancelled object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.cancel);
      }
    },

    'gets page speed data request': {
      topic: function (wpt) {
        wpt.getPageSpeedData('120816_V2_2', this.callback);
      },
      'returns the page speed object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.pageSpeed);
      }
    },

    'gets HAR data request': {
      topic: function (wpt) {
        wpt.getHARData('120816_V2_2', this.callback);
      },
      'returns the HAR object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.har);
      }
    },

    'gets utilization data request': {
      topic: function (wpt) {
        wpt.getUtilizationData('120816_V2_2', this.callback);
      },
      'returns the utilization object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.utilization);
      }
    },

    'gets request data request': {
      topic: function (wpt) {
        wpt.getRequestData('120816_V2_2', this.callback);
      },
      'returns the request object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.request);
      }
    },

    'gets timeline data request': {
      topic: function (wpt) {
        wpt.getTimelineData('120816_V2_2', this.callback);
      },
      'returns the timeline object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.timeline);
      }
    },

    'gets net log data request': {
      topic: function (wpt) {
        wpt.getNetLogData('120816_V2_2', this.callback);
      },
      'returns the net log object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.netLog);
      }
    },

    'gets console log data request': {
      topic: function (wpt) {
        wpt.getConsoleLogData('120816_V2_2', this.callback);
      },
      'returns the console log object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.consoleLog);
      }
    },

    'gets test info request': {
      topic: function (wpt) {
        wpt.getTestInfo('120816_V2_2', this.callback);
      },
      'returns the test info object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testInfo);
      }
    },

    'gets a waterfall image request': {
      topic: function (wpt) {
        wpt.getWaterfallImage('120816_V2_2', {dataURI: true}, this.callback);
      },
      'returns the waterfall data URI string': function (err, data, info) {
        if (err) throw err;
        assert.equal(data, ResponseObjects.waterfall);
        assert.deepEqual(info, {type: 'image/png', encoding: 'utf8'});
      }
    },

    'gets a waterfall thumbnail request': {
      topic: function (wpt) {
        wpt.getWaterfallImage('120816_V2_2', {
          thumbnail: true,
          dataURI: true
        }, this.callback);
      },
      'returns the waterfall thumbnail data URI string':
        function (err, data, info) {
          if (err) throw err;
          assert.equal(data, ResponseObjects.waterfallThumbnail);
          assert.deepEqual(info, {type: 'image/png', encoding: 'utf8'});
        }
    },

    'gets a screenshot request': {
      topic: function (wpt) {
        wpt.getScreenshotImage('120816_V2_2', {dataURI: true}, this.callback);
      },
      'returns the screenshot data URI string':
        function (err, data, info) {
          if (err) throw err;
          assert.equal(data, ResponseObjects.screenshot);
          assert.deepEqual(info, {type: 'image/jpeg', encoding: 'utf8'});
        }
    },

    'gets a screenshot thumbnail request': {
      topic: function (wpt) {
        wpt.getScreenshotImage('120816_V2_2', {
          thumbnail: true,
          dataURI: true
        }, this.callback);
      },
      'returns the screenshot thumbail data URI string':
        function (err, data, info) {
          if (err) throw err;
          assert.equal(data, ResponseObjects.screenshotThumbnail);
          assert.deepEqual(info, {type: 'image/jpeg', encoding: 'utf8'});
        }
    },

    'gets a screenshot in full resolution request': {
      topic: function (wpt) {
        wpt.getScreenshotImage('120816_V2_2', {
          fullResolution: true,
          dataURI: true
        }, this.callback);
      },
      'returns the screenshot in full resolution data URI string':
        function (err, data, info) {
          if (err) throw err;
          assert.equal(data, ResponseObjects.screenshotFullResolution);
          assert.deepEqual(info, {type: 'image/png', encoding: 'utf8'});
        }
    },

    // not found / invalid

    'gets an invalid test status request': {
      topic: function (wpt) {
        wpt.getTestStatus('120816_V2_3', this.callback);
      },
      'returns a not found test status object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testStatusNotFound);
      }
    },

    'gets an invalid test results request': {
      topic: function (wpt) {
        wpt.getTestResults('120816_V2_3', this.callback);
      },
      'returns a not found test results object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.testResultsNotFound);
      }
    },

    'gets an invalid test request': {
      topic: function (wpt) {
        wpt.runTest(undefined, this.callback);
      },
      'returns an invalid run test object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.runTestInvalid);
      }
    },

    'gets an invalid file request': {
      topic: function (wpt) {
        wpt.getPageSpeedData('120816_V2_3', this.callback);
      },
      'returns a 404 error': function (err, data) {
        assert.equal(err.code, 404);
        assert.equal(err.message, 'Not Found');
        assert.equal(data, undefined);
      }
    },

    'gets an invalid HAR data request': {
      topic: function (wpt) {
        wpt.getHARData('120816_V2_3', this.callback);
      },
      'returns an empty HAR object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.harNotFound);
      }
    },

    'gets an invalid waterfall image request': {
      topic: function (wpt) {
        wpt.getWaterfallImage('120816_V2_3', {dataURI: true}, this.callback);
      },
      'returns an empty waterfall data URI string':
        function (err, data, info) {
          if (err) throw err;
          assert.equal(data, ResponseObjects.waterfallNotFound);
          assert.deepEqual(info, {type: 'image/png', encoding: 'utf8'});
        }
    },

    'gets an invalid waterfall thumbnail request': {
      topic: function (wpt) {
        wpt.getWaterfallImage('120816_V2_3', {
          thumbnail: true,
          dataURI: true
        }, this.callback);
      },
      'returns an empty waterfall thumbnail data URI string':
        function (err, data, info) {
          if (err) throw err;
          assert.equal(data, ResponseObjects.waterfallThumbnailNotFound);
          assert.deepEqual(info, {type: 'image/png', encoding: 'utf8'});
        }
    },

    'gets an invalid screenshot thumbnail request': {
      topic: function (wpt) {
        wpt.getScreenshotImage('120816_V2_3', {
          thumbnail: true,
          dataURI: true
        }, this.callback);
      },
      'returns a 404 error': function (err, data, info) {
        assert.equal(err.code, 404);
        assert.equal(err.message, 'Not Found');
        assert.equal(data, undefined);
      }
    },

    'gets a cancel test of already cancelled test request': {
      topic: function (wpt) {
        wpt.cancelTest('120816_V2_3', this.callback);
      },
      'returns the test not cancelled object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.cancelNotCancelled);
      }
    },

    'gets a cancel test of an invalid test request': {
      topic: function (wpt) {
        wpt.cancelTest('120816_V2_4', this.callback);
      },
      'returns a 404 error': function (err, data) {
        assert.equal(err.code, 404);
        assert.equal(err.message, 'Not Found');
        assert.equal(data, undefined);
      }
    },

    'gets a test request for an api key required server': {
      topic: function (wpt) {
        wpt.runTest('http://apikey.com', this.callback);
      },
      'returns the no api key response object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.runTestNoAPIKey);
      }
    },

    'gets a test request for an api key required server with invalid key': {
      topic: function (wpt) {
        wpt.runTest('http://apikey.com', {key: '12345'}, this.callback);
      },
      'returns the no api key response object': function (err, data) {
        if (err) throw err;
        assert.deepEqual(data, ResponseObjects.runTestInvalidAPIKey);
      }
    }

  }
}).export(module);
<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { makeGetAccount } from '../selectors';
import Account from '../components/account';
import {
  followAccount,
  unfollowAccount,
  blockAccount,
  unblockAccount,
  muteAccount,
  unmuteAccount,
} from '../actions/accounts';
import { openModal } from '../actions/modal';

const messages = defineMessages({
  unfollowConfirm: { id: 'confirmations.unfollow.confirm', defaultMessage: 'Unfollow' },
});

const makeMapStateToProps = () => {
  const getAccount = makeGetAccount();

  const mapStateToProps = (state, props) => ({
    account: getAccount(state, props.id),
    me: state.getIn(['meta', 'me']),
    unfollowModal: state.getIn(['meta', 'unfollow_modal']),
  });

  return mapStateToProps;
};

const mapDispatchToProps = (dispatch, { intl }) => ({

  onFollow (account) {
    if (account.getIn(['relationship', 'following']) || account.getIn(['relationship', 'requested'])) {
      if (this.unfollowModal) {
        dispatch(openModal('CONFIRM', {
          message: <FormattedMessage id='confirmations.unfollow.message' defaultMessage='Are you sure you want to unfollow {name}?' values={{ name: @{account.get('acct')} }} />,
          confirm: intl.formatMessage(messages.unfollowConfirm),
          onConfirm: () => dispatch(unfollowAccount(account.get('id'))),
        }));
      } else {
        dispatch(unfollowAccount(account.get('id')));
      }
    } else {
      dispatch(followAccount(account.get('id')));
    }
  },

  onBlock (account) {
    if (account.getIn(['relationship', 'blocking'])) {
      dispatch(unblockAccount(account.get('id')));
    } else {
      dispatch(blockAccount(account.get('id')));
    }
  },

  onMute (account) {
    if (account.getIn(['relationship', 'muting'])) {
      dispatch(unmuteAccount(account.get('id')));
    } else {
      dispatch(muteAccount(account.get('id')));
    }
  },

  onMuteNotifications (account, notifications) {
    dispatch(muteAccount(account.get('id'), notifications));
  },
});

export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Account));
<commit_msg>In probably dead code, replace a dispatch of muteAccount that was skipping the modal with launching the mute modal.<commit_after>import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { makeGetAccount } from '../selectors';
import Account from '../components/account';
import {
  followAccount,
  unfollowAccount,
  blockAccount,
  unblockAccount,
  muteAccount,
  unmuteAccount,
} from '../actions/accounts';
import { openModal } from '../actions/modal';

const messages = defineMessages({
  unfollowConfirm: { id: 'confirmations.unfollow.confirm', defaultMessage: 'Unfollow' },
});

const makeMapStateToProps = () => {
  const getAccount = makeGetAccount();

  const mapStateToProps = (state, props) => ({
    account: getAccount(state, props.id),
    me: state.getIn(['meta', 'me']),
    unfollowModal: state.getIn(['meta', 'unfollow_modal']),
  });

  return mapStateToProps;
};

const mapDispatchToProps = (dispatch, { intl }) => ({

  onFollow (account) {
    if (account.getIn(['relationship', 'following']) || account.getIn(['relationship', 'requested'])) {
      if (this.unfollowModal) {
        dispatch(openModal('CONFIRM', {
          message: <FormattedMessage id='confirmations.unfollow.message' defaultMessage='Are you sure you want to unfollow {name}?' values={{ name: @{account.get('acct')} }} />,
          confirm: intl.formatMessage(messages.unfollowConfirm),
          onConfirm: () => dispatch(unfollowAccount(account.get('id'))),
        }));
      } else {
        dispatch(unfollowAccount(account.get('id')));
      }
    } else {
      dispatch(followAccount(account.get('id')));
    }
  },

  onBlock (account) {
    if (account.getIn(['relationship', 'blocking'])) {
      dispatch(unblockAccount(account.get('id')));
    } else {
      dispatch(blockAccount(account.get('id')));
    }
  },

  onMute (account) {
    if (account.getIn(['relationship', 'muting'])) {
      dispatch(unmuteAccount(account.get('id')));
    } else {
      dispatch(initMuteModal(account));
    }
  },

  onMuteNotifications (account, notifications) {
    dispatch(muteAccount(account.get('id'), notifications));
  },
});

export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Account));
<|endoftext|>


<commit_before>'use strict';
require('./scss/main.scss');
const path = require('path');
const angular = require('angular');
const camelcase = require('camelcase');
const pascalcase = require('pascalcase');
const uiRouter = require('angular-ui-router');
const ngFileUpload = require('ng-file-upload');
const ngAnimate = require('angular-animate');
const ngDialog = require('ng-dialog');
const uiBootstrap = require('angular-ui-bootstrap');

const app = angular.module('profolio', [uiRouter, ngFileUpload, ngAnimate, ngDialog, uiBootstrap]);

let context = require.context('./config/', true, /\.js$/);
context.keys().forEach( path => {
  app.config(context(path));
});

context = require.context('./view/', true, /\.js$/);
context.keys().forEach( key => {
  let name = pascalcase(path.basename(key, '.js'));
  app.controller(name, context(key));
});

context = require.context('./service/', true, /\.js$/);
context.keys().forEach( key => {
  let name = camelcase(path.basename(key, '.js'));
  app.service(name, context(key));
});

context = require.context('./component/', true, /\.js$/);
context.keys().forEach( key => {
  let name = camelcase(path.basename(key, '.js'));
  let module = context(key);
  app.component(name, module);
});
<commit_msg>assecet file upload<commit_after>'use strict';
require('./scss/main.scss');
const path = require('path');
const angular = require('angular');
const camelcase = require('camelcase');
const pascalcase = require('pascalcase');
const uiRouter = require('angular-ui-router');
const ngFileUpload = require('ng-file-upload');
const ngAnimate = require('angular-animate');
const ngDialog = require('ng-dialog');
const uiBootstrap = require('angular-ui-bootstrap');

const app = angular.module('profolio', [uiRouter, ngFileUpload, ngAnimate, ngDialog, uiBootstrap]);

let context = require.context('./config/', true, /\.js$/);
context.keys().forEach( path => {
  app.config(context(path));
});

context = require.context('./view/', true, /\.js$/);
context.keys().forEach( key => {
  let name = pascalcase(path.basename(key, '.js'));
  app.controller(name, context(key));
});

context = require.context('./service/', true, /\.js$/);
context.keys().forEach( key => {
  let name = camelcase(path.basename(key, '.js'));
  app.service(name, context(key));
});

context = require.context('./component/', true, /\.js$/);
context.keys().forEach( key => {
  let name = camelcase(path.basename(key, '.js'));
  let module = context(key);
  app.component(name, module);
});

context = require.context('./assets/', true, /\.js$/);
context.keys().forEach( key => {
  let name = pascalcase(path.basename(key, '.jpg' || '.png'));
  app.controller(name, context(key));
});
<|endoftext|>


<commit_before>// Modal Image Gallery
function onClick(element) {
    document.getElementById("img01").src = element.src;
    document.getElementById("modal01").style.display = "block";
    var captionText = document.getElementById("caption");
    captionText.innerHTML = element.alt;
}

// Change style of navbar on scroll
window.onscroll = function() {myFunction()};
function myFunction() {
    var navbar = document.getElementById("myNavbar");
    if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
        navbar.className = "w3-bar" + " w3-card-2" + " w3-animate-top" + " w3-white";
    } else {
        navbar.className = navbar.className.replace(" w3-card-2 w3-animate-top w3-white", "");
    }
}

// Used to toggle the menu on small screens when clicking on the menu button
function toggleFunction() {
    var x = document.getElementById("navDemo");
    if (x.className.indexOf("w3-show") == -1) {
        x.className += " w3-show";
    } else {
        x.className = x.className.replace(" w3-show", "");
    }
}

//connecting scroll to a div class

    var $contactinfo = $('.contactInfo');
    var $win = $(window);
    $win.on('scroll', function(s){

    var top = $win.scrollTop();

    top = top-4000;

    $('.contactInfo').css('margin-left',top + 'px');
});

//image scroll
var $win = $(window);
$win.on('scroll', function(s){
  var top = $win.scrollTop();
  top = top/8;
$('.aliMain').css('margin-right',top + 'px');
});

<commit_msg>final<commit_after>// Modal Image Gallery
function onClick(element) {
    document.getElementById("img01").src = element.src;
    document.getElementById("modal01").style.display = "block";
    var captionText = document.getElementById("caption");
    captionText.innerHTML = element.alt;
}

// Change style of navbar on scroll
window.onscroll = function() {myFunction()};
function myFunction() {
    var navbar = document.getElementById("myNavbar");
    if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
        navbar.className = "w3-bar" + " w3-card-2" + " w3-animate-top" + " w3-white";
    } else {
        navbar.className = navbar.className.replace(" w3-card-2 w3-animate-top w3-white", "");
    }
}

// Used to toggle the menu on small screens when clicking on the menu button
function toggleFunction() {
    var x = document.getElementById("navDemo");
    if (x.className.indexOf("w3-show") == -1) {
        x.className += " w3-show";
    } else {
        x.className = x.className.replace(" w3-show", "");
    }
}

//connecting scroll to a div class

    var $contactinfo = $('.contactInfo');
    var $win = $(window);
    $win.on('scroll', function(s){

    var top = $win.scrollTop();

    top = top-4150;

    $('.contactInfo').css('margin-left',top + 'px');
});

//image scroll
var $win = $(window);
$win.on('scroll', function(s){
  var top = $win.scrollTop();
  top = top/8;
$('.aliMain').css('margin-right',top + 'px');
});

<|endoftext|>


<commit_before>'use strict';

// Setting up route
angular.module('debehaber').config(['$stateProvider', '$urlRouterProvider',
    function ($stateProvider, $urlRouterProvider) {

        $urlRouterProvider.when('/debehaber/app', '/debehaber/app/reporte');
        //$urlRouterProvider.when('/debehaber/app/reporte', '/debehaber/app/reporte/nuevosSoles');

        $stateProvider
            .state('debehaber', {
                abstract: true,
                url: '/debehaber',
                templateUrl: 'modules/debehaber/views/_body.html',
                controller: 'DebehaberController'
            })
            .state('debehaber.home', {
                url: '/home',
                templateUrl: 'modules/debehaber/views/index.html',
                ncyBreadcrumb: {
                    label: 'Index'
                }
            })
            .state('debehaber.app', {
                url: '/app',
                template: '

',
                ncyBreadcrumb: {
                    skip: true // Never display this state in breadcrumb.
                }
            })

            .state('debehaber.app.reporte', {
                url: '/reporte',
                templateUrl: 'modules/debehaber/views/reporteDebeHaber.html',
                controller: 'Debehaber.ReporteDebeHaberController'
            })
            .state('debehaber.app.reporte.historialNuevosSoles', {
                url: '/nuevosSoles',
                templateUrl: 'modules/debehaber/views/historialNuevosSoles.html',
                controller: 'Debehaber.ReporteDebeHaber.HistorialController',
                resolve: {
                    idMoneda: function () {
                        return 1;
                    }
                }
            })
            .state('debehaber.app.reporte.historialDolares', {
                url: '/dolares',
                templateUrl: 'modules/debehaber/views/historialDolares.html',
                controller: 'Debehaber.ReporteDebeHaber.HistorialController',
                resolve: {
                    idMoneda: function () {
                        return 0;
                    }
                }
            })
            .state('debehaber.app.reporte.historialEuros', {
                url: '/euros',
                templateUrl: 'modules/debehaber/views/historialEuros.html',
                controller: 'Debehaber.ReporteDebeHaber.HistorialController',
                resolve: {
                    idMoneda: function () {
                        return 2;
                    }
                }
            })

            .state('debehaber.app.reporteDetallado', {
              url: '/reporteDetallado',
              templateUrl: 'modules/debehaber/views/reporteDebeHaber_detallado.html',
              controller: 'Debehaber.ReporteDebeHaberDetalladoController'
            });
    }
]);
<commit_msg>debe haber detallado<commit_after>'use strict';

// Setting up route
angular.module('debehaber').config(['$stateProvider', '$urlRouterProvider',
    function ($stateProvider, $urlRouterProvider) {

        $urlRouterProvider.when('/debehaber/app', '/debehaber/app/reporte');
        $urlRouterProvider.when('/debehaber/app/reporte', '/debehaber/app/reporte/nuevosSoles');

        $stateProvider
            .state('debehaber', {
                abstract: true,
                url: '/debehaber',
                templateUrl: 'modules/debehaber/views/_body.html',
                controller: 'DebehaberController'
            })
            .state('debehaber.home', {
                url: '/home',
                templateUrl: 'modules/debehaber/views/index.html',
                ncyBreadcrumb: {
                    label: 'Index'
                }
            })
            .state('debehaber.app', {
                url: '/app',
                template: '

',
                ncyBreadcrumb: {
                    skip: true // Never display this state in breadcrumb.
                }
            })

            .state('debehaber.app.reporte', {
                url: '/reporte',
                templateUrl: 'modules/debehaber/views/reporteDebeHaber.html',
                controller: 'Debehaber.ReporteDebeHaberController'
            })
            .state('debehaber.app.reporte.historialNuevosSoles', {
                url: '/nuevosSoles',
                templateUrl: 'modules/debehaber/views/historialNuevosSoles.html',
                controller: 'Debehaber.ReporteDebeHaber.HistorialController',
                resolve: {
                    idMoneda: function () {
                        return 1;
                    }
                }
            })
            .state('debehaber.app.reporte.historialDolares', {
                url: '/dolares',
                templateUrl: 'modules/debehaber/views/historialDolares.html',
                controller: 'Debehaber.ReporteDebeHaber.HistorialController',
                resolve: {
                    idMoneda: function () {
                        return 0;
                    }
                }
            })
            .state('debehaber.app.reporte.historialEuros', {
                url: '/euros',
                templateUrl: 'modules/debehaber/views/historialEuros.html',
                controller: 'Debehaber.ReporteDebeHaber.HistorialController',
                resolve: {
                    idMoneda: function () {
                        return 2;
                    }
                }
            })

            .state('debehaber.app.reporteDetallado', {
              url: '/reporteDetallado',
              templateUrl: 'modules/debehaber/views/reporteDebeHaber_detallado.html',
              controller: 'Debehaber.ReporteDebeHaberDetalladoController'
            });
    }
]);
<|endoftext|>


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

'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');

var GoroGenerator = yeoman.generators.Base.extend({
  initializing: function() {
    this.pkg = require('../package.json');
  },

  prompting: function() {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay('Welcome to the laudable Goro generator!'));

    var prompts = [
      {
        type: 'confirm',
        name: 'isVendor',
        message: 'Are you an agency developer?',
        default: false
      },
      {
        type: 'input',
        name: 'agencyName',
        message: 'What is the name of your agency?',
        when: function(response) {
          return response.isVendor;
        }
      },
      {
        type: 'input',
        name: 'agencyPOC',
        message: 'Please provide a point of contact. ex: John Smith jsmith@mydomain.com',
        when: function(response) {
          return response.isVendor;
        }
      },
      {
        type: 'input',
        name: 'projectDomain',
        message: 'What is the domain used for the project? ex: www.mydomain.com'
      },
      {
        type: 'input',
        name: 'projectPath',
        message: 'What is the path used for the project? ex: /about/products/'
      },
      {
        type: 'input',
        name: 'projectBranch',
        message: 'What is the branch name used for the project?'
      },
      {
        type: 'input',
        name: 'goroPath',
        message: 'What is the local path to your Goro CLI tool? Ex: ~/tools/goro/goro.py',
        default: '~/tools/goro/goro.py'
      }
    ];

    this.prompt(prompts, function(props) {
      this.isVendor = props.isVendor;
      this.agencyName = props.agencyName;
      this.agencyPOC = props.agencyPOC;
      this.projectDomain = props.projectDomain;
      this.projectPath = props.projectPath;
      this.projectBranch = props.projectBranch;
      this.goroPath = props.goroPath;

      done();
    }.bind(this));
  },

  configuring: function() {
    this.src.copy('editorconfig', '.editorconfig');
    this.src.copy('goroignore', '.goroignore');
  },

  writing: function() {
      // Set up directory structure
      this.mkdir('css');
      this.mkdir('css/components');
      this.mkdir('index.html_data');
      this.mkdir('js');
      this.mkdir('js/components');
      this.mkdir('js/components/my-component');
      this.mkdir('js/sections');

      // Process templates
      this.template('_gruntfile.js', 'gruntfile.js');
      this.template('_base.tpl', 'base.tpl');
      this.template('_index.html', 'index.html');
      this.template('js/_main.js', 'js/main.js');
      this.template('js/_app.js', 'js/app.js');
      this.template('js/_my-service.js', 'js/my-service.js');
      this.template('js/sections/_home-controller.js', 'js/sections/home-controller.js');
      this.template('js/components/my-component/_my-component-controller.js', 'js/components/my-component/my-component-controller.js');
      this.template('js/components/my-component/_my-component-directive.js', 'js/components/my-component/my-component-directive.js');

      // Copy non-template files
      this.src.copy('package.json', 'package.json');
      this.src.copy('config.inc.tpl', 'config.inc.tpl');
      this.src.copy('css/default.min.css', 'css/default.min.css');
      this.src.copy('css/components/my-component.scss', 'css/components/my-component.scss');
      this.src.copy('index.html_data/side-content.gnode', 'index.html_data/side-content.gnode');
      this.src.copy('js/main.min.js', 'js/main.min.js');
      this.src.copy('js/components/my-component/my-directive-template.html', 'js/components/my-component/my-directive-template.html');
      this.src.copy('README', 'README');
  },

  install: function () {
    this.installDependencies({
      bower: false
    });
  },

  end: function() {
    this.spawnCommand('grunt', ['shell']);
  }
});

module.exports = GoroGenerator;
<commit_msg>Remove command to copy no longer present README file.<commit_after>/* Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');

var GoroGenerator = yeoman.generators.Base.extend({
  initializing: function() {
    this.pkg = require('../package.json');
  },

  prompting: function() {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay('Welcome to the laudable Goro generator!'));

    var prompts = [
      {
        type: 'confirm',
        name: 'isVendor',
        message: 'Are you an agency developer?',
        default: false
      },
      {
        type: 'input',
        name: 'agencyName',
        message: 'What is the name of your agency?',
        when: function(response) {
          return response.isVendor;
        }
      },
      {
        type: 'input',
        name: 'agencyPOC',
        message: 'Please provide a point of contact. ex: John Smith jsmith@mydomain.com',
        when: function(response) {
          return response.isVendor;
        }
      },
      {
        type: 'input',
        name: 'projectDomain',
        message: 'What is the domain used for the project? ex: www.mydomain.com'
      },
      {
        type: 'input',
        name: 'projectPath',
        message: 'What is the path used for the project? ex: /about/products/'
      },
      {
        type: 'input',
        name: 'projectBranch',
        message: 'What is the branch name used for the project?'
      },
      {
        type: 'input',
        name: 'goroPath',
        message: 'What is the local path to your Goro CLI tool? Ex: ~/tools/goro/goro.py',
        default: '~/tools/goro/goro.py'
      }
    ];

    this.prompt(prompts, function(props) {
      this.isVendor = props.isVendor;
      this.agencyName = props.agencyName;
      this.agencyPOC = props.agencyPOC;
      this.projectDomain = props.projectDomain;
      this.projectPath = props.projectPath;
      this.projectBranch = props.projectBranch;
      this.goroPath = props.goroPath;

      done();
    }.bind(this));
  },

  configuring: function() {
    this.src.copy('editorconfig', '.editorconfig');
    this.src.copy('goroignore', '.goroignore');
  },

  writing: function() {
      // Set up directory structure
      this.mkdir('css');
      this.mkdir('css/components');
      this.mkdir('index.html_data');
      this.mkdir('js');
      this.mkdir('js/components');
      this.mkdir('js/components/my-component');
      this.mkdir('js/sections');

      // Process templates
      this.template('_gruntfile.js', 'gruntfile.js');
      this.template('_base.tpl', 'base.tpl');
      this.template('_index.html', 'index.html');
      this.template('js/_main.js', 'js/main.js');
      this.template('js/_app.js', 'js/app.js');
      this.template('js/_my-service.js', 'js/my-service.js');
      this.template('js/sections/_home-controller.js', 'js/sections/home-controller.js');
      this.template('js/components/my-component/_my-component-controller.js', 'js/components/my-component/my-component-controller.js');
      this.template('js/components/my-component/_my-component-directive.js', 'js/components/my-component/my-component-directive.js');

      // Copy non-template files
      this.src.copy('package.json', 'package.json');
      this.src.copy('config.inc.tpl', 'config.inc.tpl');
      this.src.copy('css/default.min.css', 'css/default.min.css');
      this.src.copy('css/components/my-component.scss', 'css/components/my-component.scss');
      this.src.copy('index.html_data/side-content.gnode', 'index.html_data/side-content.gnode');
      this.src.copy('js/main.min.js', 'js/main.min.js');
      this.src.copy('js/components/my-component/my-directive-template.html', 'js/components/my-component/my-directive-template.html');
  },

  install: function () {
    this.installDependencies({
      bower: false
    });
  },

  end: function() {
    this.spawnCommand('grunt', ['shell']);
  }
});

module.exports = GoroGenerator;
<|endoftext|>


<commit_before>$(function() {
	var geocoder = new google.maps.Geocoder();

	// 初期表示
	var address = $('#address').val();
	geocoder.geocode({'address': address}, callbackRender);

	// 住所が入力された場合の対応
	$('#address').change(function(event) {
		address = $(this).val();
		geocoder.geocode({'address': address}, callbackRender);
	});
});

/**
 * ジオコーダの結果を取得したときに実行するコールバック関数。
 *
 * この関数内で GoogleMap を出力する。
 *
 * @param results ジオコーダの結果
 * @param status ジオコーディングのステータス
 *
 */
function callbackRender(results, status) {
	if(status == google.maps.GeocoderStatus.OK) {
		var options = {
			zoom: 18,
			center: results[0].geometry.location, // 指定の住所から計算した緯度経度を指定する
			mapTypeId: google.maps.MapTypeId.ROADMAP // 「地図」で GoogleMap を出力する
		};
		var gmap = new google.maps.Map(document.getElementById('map-canvas'), options);
			// #map-canvas に GoogleMap を出力する
		var marker = new google.maps.Marker({map: gmap, position: results[0].geometry.location});
			// 指定の住所から計算した緯度経度の位置に Marker を立てる

		var infoWindow = createInfoWindow(results); // InfoWindow オブジェクトを生成し、
		infoWindow.open(marker.getMap(), marker); // 初期表示で InfoWindow を表示する
		google.maps.event.addListener(marker, 'click', function(event) {
 			infoWindow.open(marker.getMap(), marker);
 				// Marker をクリックしても InfoWindow を表示する
		});

		adjustMapSize();
	}
}

/**
 * InfoWindow オブジェクトを生成する。
 *
 * @param result ジオコーダの実行結果
 *
 */
function createInfoWindow(result) {
	var infoWindow = new google.maps.InfoWindow({
		content: createTag(result),
		maxWidth: 500,
		maxHeight: 500
	});
	return infoWindow;
}

/**
 * InfoWindow 内に設定する HTML を生成する。
 *
 * HTML の生成は Underscore.js を使い、テンプレートは index.html 内に定義してある。
 *
 * @param result ジオコーダの実行結果
 *
 */
function createTag(result) {
	var latitude = result[0].geometry.location.d; // 緯度
	var longitude = result[0].geometry.location.e; // 経度
	var template = _.template($('#infowindow_template').text());
	var tag = template({latitude: latitude, longitude: longitude});
	return tag;
}

/**
 * GoogleMap を表示する部分のサイズを調整する。
 *
 */
function adjustMapSize() {
	var mapCanvas = $('#map-canvas');
	var marginBottom = 5; // CSS に定義してある margin の値
	mapCanvas.css("height", ($(window).height() - mapCanvas.offset().top - marginBottom) + "px");
}
<commit_msg>InfoWindow のオプションに間違ったものが含まれていたのを削除したのでコミット。<commit_after>$(function() {
	var geocoder = new google.maps.Geocoder();

	// 初期表示
	var address = $('#address').val();
	geocoder.geocode({'address': address}, callbackRender);

	// 住所が入力された場合の対応
	$('#address').change(function(event) {
		address = $(this).val();
		geocoder.geocode({'address': address}, callbackRender);
	});
});

/**
 * ジオコーダの結果を取得したときに実行するコールバック関数。
 *
 * この関数内で GoogleMap を出力する。
 *
 * @param results ジオコーダの結果
 * @param status ジオコーディングのステータス
 *
 */
function callbackRender(results, status) {
	if(status == google.maps.GeocoderStatus.OK) {
		var options = {
			zoom: 18,
			center: results[0].geometry.location, // 指定の住所から計算した緯度経度を指定する
			mapTypeId: google.maps.MapTypeId.ROADMAP // 「地図」で GoogleMap を出力する
		};
		var gmap = new google.maps.Map(document.getElementById('map-canvas'), options);
			// #map-canvas に GoogleMap を出力する
		var marker = new google.maps.Marker({map: gmap, position: results[0].geometry.location});
			// 指定の住所から計算した緯度経度の位置に Marker を立てる

		var infoWindow = createInfoWindow(results); // InfoWindow オブジェクトを生成し、
		infoWindow.open(marker.getMap(), marker); // 初期表示で InfoWindow を表示する
		google.maps.event.addListener(marker, 'click', function(event) {
 			infoWindow.open(marker.getMap(), marker);
 				// Marker をクリックしても InfoWindow を表示する
		});

		adjustMapSize();
	}
}

/**
 * InfoWindow オブジェクトを生成する。
 *
 * @param result ジオコーダの実行結果
 *
 */
function createInfoWindow(result) {
	var infoWindow = new google.maps.InfoWindow({
		content: createTag(result), // InfoWindow に表示するコンテンツ
		maxWidth: 500
	});
	return infoWindow;
}

/**
 * InfoWindow 内に設定する HTML を生成する。
 *
 * HTML の生成は Underscore.js を使い、テンプレートは index.html 内に定義してある。
 *
 * @param result ジオコーダの実行結果
 *
 */
function createTag(result) {
	var latitude = result[0].geometry.location.d; // 緯度
	var longitude = result[0].geometry.location.e; // 経度
	var template = _.template($('#infowindow_template').text());
	var tag = template({latitude: latitude, longitude: longitude});
	return tag;
}

/**
 * GoogleMap を表示する部分のサイズを調整する。
 *
 */
function adjustMapSize() {
	var mapCanvas = $('#map-canvas');
	var marginBottom = 5; // CSS に定義してある margin の値
	mapCanvas.css("height", ($(window).height() - mapCanvas.offset().top - marginBottom) + "px");
}
<|endoftext|>


<commit_before>(function(){

	var app = angular.module('app-directives', ['getDeck']);

	app.directive('youtube', function($window){
		return{
			restrict: 'E',
			scope: {
				height: "@",
				width: "@",
				deck: "=",
			},
			template: '

',
			link: function(scope, element){
				var tag = document.createElement('script');
				tag.src = "https://www.youtube.com/iframe_api"
				var firstScriptTag = document.getElementsByTagName('script')[0];
				firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

				var player;
				var timer = 0;

				$window.onYouTubeIframeAPIReady = function(){
					player = new YT.Player(element.children()[0], {
						height: scope.height,
						width: scope.width,
						videoId: scope.deck.sourceUrl.split("=")[1]
					});
				};
				scope.$on('seekTo', function(event, time){
					console.log(time);
					player.seekTo(time);
				});
				setInterval(function(){
					timer = player.getCurrentTime();
					console.log(timer);
				}, 500);
			}
		}
	});

	app.directive("embedLink", ['$sce', function($sce){
		return{
			restrict: 'A',
			scope : {
				deck : '='
			},
			templateUrl: "view/iframe.html",
			compile : function (tElement, tAttrs, transclude) {
				return {
					pre : function (scope, iElement, iAttrs) {
					},
					post : function (scope, iElement, iAttrs) {
						console.log(scope.deck.name);
						scope.videoEmbedUrl = $sce.trustAsResourceUrl(scope.deck.content.sourceUrl.replace("watch?v=","embed/"));
					}
				}
			}
		};
	}]);

	app.directive('videoTitle', function(){
		return{
			restrict: 'A',
			scope: {
				deck: '='
			},
			templateUrl: "view/videoTitle.html"
		};
	});

	app.directive('navbarLink', function(){
		return{
			restrict: 'A',
			scope: {
				deck: '='
			},
			templateUrl: "view/navbar.html",
			compile: function(tElement, tAttrs, transclude){
				return{
					pre : function (scope, iElement, iAttrs){
					},
					post: function (scope, iElement, iAttrs){
						scope.videoUrl = scope.deck.content.sourceUrl
						scope.deckUrl = "http://membright.com/app/#/search/" + scope.deck.name.replace(" ", "_") + "/Deck/" + scope.deck.id
					}
				}
			}
		};
	});

	app.directive('description', function(){
		return{
			restrict: 'A',
			scope: {
				descri: '='
			},
			templateUrl: "view/description.html",
			compile: function(tElement, tAttrs, transclude){
				return{
					pre : function(scope, iElement, iAttrs){
					},
					post : function(scope, iElement, iAttrs){
					console.log(scope.descri)
					}
				}
			}
		};
	});

	app.directive('showCard', function(){
		return{
			restrict: 'A',
			scope: {
				deck: '=',
			},
			templateUrl: "view/showCards.html",
			compile: function(tElement, iElement, transclude){
				return {
					pre : function(scope, iElement, iAttrs){
					},
					post : function(scope, iElement, iAttrs){
						for (var x in scope.deck.cards){
							scope.cards = scope.deck.cards
							scope.cards[x].question = scope.deck.cards[x].obj.question
							scope.cards[x].answer = scope.deck.cards[x].obj.answer
							console.log(scope.cards + "test");
						}
						scope.seek = function(x){
							console.log("x:", x)
							console.log("time", scope.deck.cards[x].time);
							scope.$emit('seek', scope.deck.cards[x].time);
						}
					}
				}
			}
		};
	});
	app.directive('highlightCard', function(){
		return{
			restrict: 'A',
			scope: {
				deck: '=',
				time: '@',
			},
			templateUrl: "view/highlightCard.html",
			compile: function(tElement, iElement, transclude){
				return{
					pre : function(scope, iElement, iAttrs){
					},
					post : function(scope, iElement, iArrtr){
					}
				}
			}
		}
	});

})();
<commit_msg>removed timer print to console<commit_after>(function(){

	var app = angular.module('app-directives', ['getDeck']);

	app.directive('youtube', function($window){
		return{
			restrict: 'E',
			scope: {
				height: "@",
				width: "@",
				deck: "=",
			},
			template: '

',
			link: function(scope, element){
				var tag = document.createElement('script');
				tag.src = "https://www.youtube.com/iframe_api"
				var firstScriptTag = document.getElementsByTagName('script')[0];
				firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

				var player;
				var timer = 0;

				$window.onYouTubeIframeAPIReady = function(){
					player = new YT.Player(element.children()[0], {
						height: scope.height,
						width: scope.width,
						videoId: scope.deck.sourceUrl.split("=")[1]
					});
				};
				scope.$on('seekTo', function(event, time){
					console.log(time);
					player.seekTo(time);
				});
				setInterval(function(){
					timer = player.getCurrentTime();
				}, 500);
			}
		}
	});

	app.directive("embedLink", ['$sce', function($sce){
		return{
			restrict: 'A',
			scope : {
				deck : '='
			},
			templateUrl: "view/iframe.html",
			compile : function (tElement, tAttrs, transclude) {
				return {
					pre : function (scope, iElement, iAttrs) {
					},
					post : function (scope, iElement, iAttrs) {
						console.log(scope.deck.name);
						scope.videoEmbedUrl = $sce.trustAsResourceUrl(scope.deck.content.sourceUrl.replace("watch?v=","embed/"));
					}
				}
			}
		};
	}]);

	app.directive('videoTitle', function(){
		return{
			restrict: 'A',
			scope: {
				deck: '='
			},
			templateUrl: "view/videoTitle.html"
		};
	});

	app.directive('navbarLink', function(){
		return{
			restrict: 'A',
			scope: {
				deck: '='
			},
			templateUrl: "view/navbar.html",
			compile: function(tElement, tAttrs, transclude){
				return{
					pre : function (scope, iElement, iAttrs){
					},
					post: function (scope, iElement, iAttrs){
						scope.videoUrl = scope.deck.content.sourceUrl
						scope.deckUrl = "http://membright.com/app/#/search/" + scope.deck.name.replace(" ", "_") + "/Deck/" + scope.deck.id
					}
				}
			}
		};
	});

	app.directive('description', function(){
		return{
			restrict: 'A',
			scope: {
				descri: '='
			},
			templateUrl: "view/description.html",
			compile: function(tElement, tAttrs, transclude){
				return{
					pre : function(scope, iElement, iAttrs){
					},
					post : function(scope, iElement, iAttrs){
					console.log(scope.descri)
					}
				}
			}
		};
	});

	app.directive('showCard', function(){
		return{
			restrict: 'A',
			scope: {
				deck: '=',
			},
			templateUrl: "view/showCards.html",
			compile: function(tElement, iElement, transclude){
				return {
					pre : function(scope, iElement, iAttrs){
					},
					post : function(scope, iElement, iAttrs){
						for (var x in scope.deck.cards){
							scope.cards = scope.deck.cards
							scope.cards[x].question = scope.deck.cards[x].obj.question
							scope.cards[x].answer = scope.deck.cards[x].obj.answer
							console.log(scope.cards + "test");
						}
						scope.seek = function(x){
							console.log("x:", x)
							console.log("time", scope.deck.cards[x].time);
							scope.$emit('seek', scope.deck.cards[x].time);
						}
					}
				}
			}
		};
	});
	app.directive('highlightCard', function(){
		return{
			restrict: 'A',
			scope: {
				deck: '=',
				time: '@',
			},
			templateUrl: "view/highlightCard.html",
			compile: function(tElement, iElement, transclude){
				return{
					pre : function(scope, iElement, iAttrs){
					},
					post : function(scope, iElement, iArrtr){
					}
				}
			}
		}
	});

})();
<|endoftext|>


<commit_before>function baseicon(widget_id, url, skin, parameters)
{
    // Will be using "self" throughout for the various flavors of "this"
    // so for consistency ...

    self = this;

    // Initialization

    self.widget_id = widget_id;

    // Parameters may come in useful later on

    self.parameters = parameters;

    self.OnStateAvailable = OnStateAvailable;
    self.OnStateUpdate = OnStateUpdate;
    self.OnIconClick = OnIconClick;

    var monitored_entities =
        [
            {"entity": parameters.entity, "initial": self.OnStateAvailable, "update": self.OnStateUpdate}
        ];

    var callbacks = [
        {"selector": '#' + widget_id, "action": "click", "callback": self.OnIconClick},
    ]

    // Finally, call the parent constructor to get things moving

    WidgetBase.call(self, widget_id, url, skin, parameters, monitored_entities, callbacks);

    // Function Definitions

    // The StateAvailable function will be called when
    // self.state[<entity>] has valid information for the requested entity
    // state is the initial state

    function OnStateAvailable(self, state)
    {
        self.state = state.state;
        set_view(self, self.state)
    }

    // The OnStateUpdate function will be called when the specific entity
    // receives a state update - its new values will be available
    // in self.state[<entity>] and returned in the state parameter

    function OnStateUpdate(self, state)
    {
        self.state = state.state;

        delay_time = self.parameters.update_delay;
        if (delay_time != undefined) {
            if (self.timeout != undefined) {
                clearTimeout(self.timeout);
            }

            self.timeout = setTimeout(() => set_view(self, self.state), delay_time * 1000);
        } else {
            set_view(self, self.state);
        }
    }

    function OnIconClick(self) {
        if (self.post_service != undefined) {
            self.call_service(self, self.post_service);
        }
    }

    // Set view is a helper function to set all aspects of the widget to its
    // current state - it is called by widget code when an update occurs
    // or some other event that requires a an update of the view

    function set_view(self, state, level)
    {
        if ("icons" in self.parameters)
        {
            if (state in self.parameters.icons)
            {
                self.set_icon(self, "icon", self.parameters.icons[state].icon);
                self.set_field(self, "icon_style", self.parameters.icons[state].style);
                set_service_call(self, self.parameters.icons[state]);
            }
            else if ("default" in self.parameters.icons)
            {
                self.set_icon(self, "icon", self.parameters.icons.default.icon);
                self.set_field(self, "icon_style", self.parameters.icons.default.style);
                set_service_call(self, self.parameters.default);
            }
            else
            {
                self.set_icon(self, "icon", "fa-circle-thin");
                self.set_field(self, "icon_style", "color: white");
                self.post_service = undefined;
            }

        }

        if ("state_text" in self.parameters && self.parameters.state_text == 1)
        {
            self.set_field(self, "state_text", self.map_state(self, state))
        }
    }

    function set_service_call(self, data) {
        if (data.service != undefined) {
            self.post_service = data.service;
            if (self.post_service["namespace"] == undefined) {
                self.post_service["namespace"] = self.parameters.namespace;
            }
        } else if (data.sequence != undefined) {
            self.post_service = {
                service: "sequence/run",
                sequence: data.sequence,
                namespace: "rules"
            }
        } else if (data.script != undefined) {
            self.post_service = {
                service: "homeassistant/turn_on",
                entity_id: data.script,
                namespace: self.parameters.namespace
            }
        } else {
            self.post_service = undefined;
        }
    }
}
<commit_msg>Automatic script/sequence prefix<commit_after>function baseicon(widget_id, url, skin, parameters)
{
    // Will be using "self" throughout for the various flavors of "this"
    // so for consistency ...

    self = this;

    // Initialization

    self.widget_id = widget_id;

    // Parameters may come in useful later on

    self.parameters = parameters;

    self.OnStateAvailable = OnStateAvailable;
    self.OnStateUpdate = OnStateUpdate;
    self.OnIconClick = OnIconClick;

    var monitored_entities =
        [
            {"entity": parameters.entity, "initial": self.OnStateAvailable, "update": self.OnStateUpdate}
        ];

    var callbacks = [
        {"selector": '#' + widget_id, "action": "click", "callback": self.OnIconClick},
    ]

    // Finally, call the parent constructor to get things moving

    WidgetBase.call(self, widget_id, url, skin, parameters, monitored_entities, callbacks);

    // Function Definitions

    // The StateAvailable function will be called when
    // self.state[<entity>] has valid information for the requested entity
    // state is the initial state

    function OnStateAvailable(self, state)
    {
        self.state = state.state;
        set_view(self, self.state)
    }

    // The OnStateUpdate function will be called when the specific entity
    // receives a state update - its new values will be available
    // in self.state[<entity>] and returned in the state parameter

    function OnStateUpdate(self, state)
    {
        self.state = state.state;

        delay_time = self.parameters.update_delay;
        if (delay_time != undefined) {
            if (self.timeout != undefined) {
                clearTimeout(self.timeout);
            }

            self.timeout = setTimeout(() => set_view(self, self.state), delay_time * 1000);
        } else {
            set_view(self, self.state);
        }
    }

    function OnIconClick(self) {
        if (self.post_service != undefined) {
            self.call_service(self, self.post_service);
        }
    }

    // Set view is a helper function to set all aspects of the widget to its
    // current state - it is called by widget code when an update occurs
    // or some other event that requires a an update of the view

    function set_view(self, state, level)
    {
        if ("icons" in self.parameters)
        {
            if (state in self.parameters.icons)
            {
                self.set_icon(self, "icon", self.parameters.icons[state].icon);
                self.set_field(self, "icon_style", self.parameters.icons[state].style);
                set_service_call(self, self.parameters.icons[state]);
            }
            else if ("default" in self.parameters.icons)
            {
                self.set_icon(self, "icon", self.parameters.icons.default.icon);
                self.set_field(self, "icon_style", self.parameters.icons.default.style);
                set_service_call(self, self.parameters.default);
            }
            else
            {
                self.set_icon(self, "icon", "fa-circle-thin");
                self.set_field(self, "icon_style", "color: white");
                self.post_service = undefined;
            }

        }

        if ("state_text" in self.parameters && self.parameters.state_text == 1)
        {
            self.set_field(self, "state_text", self.map_state(self, state))
        }
    }

    function set_service_call(self, data) {
        if (data.service != undefined) {
            self.post_service = data.service;
            if (self.post_service["namespace"] == undefined) {
                self.post_service["namespace"] = self.parameters.namespace;
            };
        } else if (data.sequence != undefined) {
            self.post_service = {
                service: "sequence/run",
                sequence: "sequence." + data.sequence,
                namespace: "rules"
            }
        } else if (data.script != undefined) {
            self.post_service = {
                service: "homeassistant/turn_on",
                entity_id: "script." + data.script,
                namespace: self.parameters.namespace
            }
        } else {
            self.post_service = undefined;
        }
    }
}
<|endoftext|>