<commit_before>define([
    'underscore',
    'hr/hr',
    'utils/url',
    'vendors/filer',
    'core/operations',
    'utils/dialogs',
    'utils/alerts'
], function(_, hr, Url, Filer, operations, dialogs, alerts) {
    var logger = hr.Logger.addNamespace("localfs");

    // Base folder for localfs
    var base = "/";

    // Constant mime type for a directory
    var MIME_DIRECTORY = "inode/directory";

    // Duration for sync (ms)
    syncDuration = 1*60*1000;

    // Create fs interface
    var filer = new Filer();

    var fsCall = function(method, args, context) {
        if (_.isUndefined(args)) args = [];
        if (!_.isArray(args)) args = [args];

        var d = Q.defer();
        args.push(function() {
            if (arguments.length == 1) return d.resolve(arguments[0]);
            d.resolve(arguments);
        });
        args.push(function(err) {
            logger.error("Error occurs: ", err);
            d.reject(err);
        })

        method.apply(context, args);

        return d.promise;
    };

    /*
     *  Init the localfs
     */
    var initFs = function(baseDir) {
        var box = require("core/box");

        base = "/"+baseDir;
        return fsCall(filer.init, {
            persistent: true,
            size: 10 * 1024 * 1024
        }, filer).then(function() {
            logger.log("ready");

            // Box fs changes
            box.on("box:watch", function() {
                logger.warn("box change");
                autoSync();
            })
        });
    };

    /*
     * Adapt path
     */
    var adaptPath = function(path) {
        path = base+path;
        path = path.replace("//", "/");
        return path;
    }

    /*
     *  Convert a vfs url in a path
     */
    var urlToPath = function(url) {
        var path = url.replace("/vfs/", "");
        if (path.length == 0) path = '/';
        if (path[0] != '/') path = "/" + path;
        return path;
    };

    /*
     *  Return informations about a fileentry
     */
    var getEntryInfos = function(fEntry) {
        return fsCall(fEntry.getMetadata, [], fEntry).then(function(metadata) {
            var path = fEntry.fullPath.replace(base, "/").replace("//", "/");
            var url = location.protocol+"//"+location.host+"/vfs"+path;

            if (fEntry.isDirectory) url = url + "/";

            return {
                "name": fEntry.name,
                "size": metadata.size,
                "mtime": metadata.modificationTime.getTime(),
                "mime": fEntry.isDirectory ? MIME_DIRECTORY : "application/octet-stream",
                "href": url,
                "exportUrl": fEntry.toURL(),
                "offline": true,
                '_fullPath': path
            };
        })
    };

    /*
     *  List a directory
     */
    var listDir = function(path) {
        path = adaptPath(path);

        logger.log("ls:", path);
        return fsCall(filer.ls, path, filer).then(function(entries) {
            return Q.all(_.map(entries, function(entry) {
                return getEntryInfos(entry);
            }))
        }).then(function(entries) {
            return entries;
        }, function(err) {
            logger.error("ls:", err);
        });
    };

    /*
     *  Create a file
     */
    var createFile = function(path) {
        path = adaptPath(path);
        logger.log("create:", path);
        return fsCall(filer.create, [path, true], filer);
    };

    /*
     *  Write file
     */
    var writeFile = function(path, data) {
        path = adaptPath(path);
        logger.log("write:", path);
        return fsCall(filer.write, [path, {
            'data': data || ""
        }], filer);
    };

    /*
     *  Open a file
     */
    var openFile = function(path) {
        path = adaptPath(path);
        logger.log("open:", path);
        return fsCall(filer.getEntry, [path], filer).then(function(fEntry) {
            return getEntryInfos(fEntry);
        })
    };

    /*
     *  Read a file
     */
    var readFile = function(path) {
        path = adaptPath(path);
        logger.log("read:", path);
        return fsCall(filer.open, [path], filer).then(function(file) {
            var d = Q.defer();

            var reader = new FileReader();
            reader.onerror = function(err) {
                d.reject(err);
            };
            reader.onload = function(e) {
                d.resolve(this.result);
            };
            reader.readAsText(file);

            return d.promise;
        });
    };

    /*
     *  Create a file
     */
    var createDirectory = function(path) {
        path = adaptPath(path);
        logger.log("mkdir:", path);
        return fsCall(filer.mkdir, [path, false], filer);
    };

    /*
     *  Move a file
     */
    var move = function(from, to) {
        from = adaptPath(from);
        to = adaptPath(to);

        logger.log("move:", from, "to", to);
        return fsCall(filer.mv, [from, '.', to], filer);
    };

    /*
     *  Remove a file or directory
     */
    var remove = function(path) {
        path = adaptPath(path);

        logger.log("remove:", path);
        return fsCall(filer.rm, [path], filer);
    };

    /*
     *  Sync a file in the box fs with the local fs
     *
     *  this will download the files and saved them in the localfs
     */
    var syncFileBoxToLocal = function() {
        var box = require("core/box");

        var doSync = function(fp) {
            var path = fp.path();
            if (path == "/.git") return Q();

            logger.log("sync:box->local:", path);

            if (fp.isDirectory()) {
                // Create the directory
                return createDirectory(path).then(function() {
                    // List subfiles
                    return fp.listdir();
                }).then(function(files) {
                    // Recursively sync files and directory
                    return Q.all(_.map(files, function(f) {
                        return doSync(f);
                    }));
                });
            } else {
                // Read file content
                return fp.read().then(function(content) {
                    // Write file content
                    return writeFile(path, content);
                });
            }
        };
        return operations.start("files.sync", function(op) {
            logger.warn("Start sync: box->local");
            return remove("/").then(function() {
                return doSync(box.root);
            }, function() {
                return doSync(box.root)
            }).then(function() {
                alerts.show("Workspace has been saved offline.", 5000);
                logger.warn("Finished sync: box->local");
            });
        }, {
            title: "Downloading ..."
        });
    };

    /*
     *  Sync localfs to vfs
     */
    var syncFileLocalToBox = function() {
        var File = require("models/file");
        var box = require("core/box");
        var messages = [];

        var doSyncDir = function(path, parent) {
            var localEntries, boxEntries, currentEntryInfos;
            if (path == "/.git") return Q();

            logger.log("sync:local->box:", path);

            // Get current directory
            return openFile(path).then(function(infos) {
                // Infos about this entry
                currentEntryInfos = infos;

                return listDir(path);
            }).then(function(entries) {
                // Entry in the browser
                localEntries = entries;
                return parent.listdir();
            }).then(function(entries) {
                // Entries on the boxes
                boxEntries = entries;
            }).then(function() {
                // Eliminate old useless entries
                return Q.all(_.map(boxEntries, function(boxFile) {
                    var localEntry = _.find(localEntries, function(localEntry) {
                        return localEntry.name == boxFile.get("name");
                    });

                    // File don't exists and box file older than current directory
                    if (!localEntry && boxFile.get("mtime") < currentEntryInfos.mtime) {
                        // -> Remove the file on the box
                        //logger.log("resync: need to remove ", boxFile.path());
                        messages.push({
                            'operation': "remove",
                            'path': boxFile.path(),
                            'message': "[conflict] You should manually remove "+boxFile.path()
                        });
                    }

                    // Do nothing
                    return Q();
                }));
            }).then(function() {
                // Update entries and create new entries
                return Q.all(_.map(localEntries, function(localEntry) {
                    var entryIsDir = localEntry.mime == MIME_DIRECTORY;
                    var boxFile = _.find(boxEntries, function(boxFile) {
                        return localEntry.name == boxFile.get("name");
                    });

                    // Is not a directory and:
                    if (!entryIsDir && (!boxFile    // File don't exist
                    || (boxFile.get("mtime") < localEntry.mtime)))    // or File modified offline
                    {
                        // -> Update box content
                        /*logger.log("resync: need to update ", localEntry._fullPath);
                        logger.log(" -> box:", boxFile.get("mtime"));
                        logger.log(" -> local:", localEntry.mtime);*/
                        return readFile(localEntry._fullPath).then(function(content) {
                            return parent.write(content, localEntry._fullPath);
                        });
                    }

                    // if a directory
                    if (entryIsDir) {
                        var syncEntry = function(newParent) {
                            return doSyncDir(localEntry._fullPath, newParent);
                        }

                        if (boxFile) {
                            if (boxFile.isDirectory()) {
                                return syncEntry(boxFile);
                            } else {
                                messages.push({
                                    'operation': "remove",
                                    'path': boxFile.path(),
                                    'message': "[conflict] You should manually remove "+boxFile.path()
                                });
                            }
                        } else {
                            return parent.mkdir(localEntry.name).then(function() {
                                return parent.getChild(localEntry.name);
                            }).then(syncEntry);
                        }
                    }

                    // Do nothing
                    return Q();
                }));
            }).fail(function(err) {
                logger.error("Error during sync: ", err);
            });
        };

        return operations.start("files.sync", function(op) {
            logger.warn("Start sync: local->box");
            return doSyncDir("/", box.root).then(function() {
                logger.warn("Finished sync: local->box");
            })
        }, {
            title: "Uploading changes..."
        }).then(function() {
            alerts.show("Offline changes have been uploaded to the workspace.", 5000);
            if (messages.length > 0) {
                return dialogs.alert("Conflict during synchronization:", _.pluck(messages, 'message').join("<br/>"));
            }
        });
    };

    /*
     *  Global sync:
     *      -> if never sync: download everything
     *      -> if already sync: upload changes and download last changes
     */
    var sync = function(options) {
        options = _.defaults({}, options || {}, {
            'updateLocal': false
        });

        if (hr.Offline.isConnected()) {
            var endT, startT = Date.now();

            return openFile("/").then(function(infos) {
                if (options.updateLocal) return Q();
                return syncFileLocalToBox();
            }, function() {
                return createDirectory("/");
            }).then(function() {
                return syncFileBoxToLocal();
            }).then(function() {
                //Calcul duration
                endT = Date.now();
                syncDuration = _.max([endT - startT, 5000]);
                updateAutoSync();

                alerts.show("Offline and Workspace have been synchronized.", 5000);
                return syncDuration;
            }, function(err) {
                logger.error("!!!!!! ERROR !!!!!!!", err);
            });
        } else {
            return Q.reject(new Error("Can't synchronize when offline"));
        }
    };

    /*
     *  Auto sync allow to resync the localfs every interval
     */
    var autoSync = null;
    var updateAutoSync = function() {
        logger.log("sync take ", syncDuration/1000,"seconds");
        autoSync =  _.throttle(function() {
            sync({
                updateLocal: true
            });
        }, 2*syncDuration);
    };
    updateAutoSync();

    // Run sync every 5min
    setTimeout(function() {
        autoSync();
    }, 5*60*1000);

    return {
        'getEntryInfos': getEntryInfos,
        'urlToPath': urlToPath,
        'init': initFs,
        'ls': listDir,
        'create': createFile,
        'mkdir': createDirectory,
        'write': writeFile,
        'read': readFile,
        'mv': move,
        'rm': remove,
        'reset': syncFileBoxToLocal,
        'sync': sync,
        'autoSync': function() {
            return autoSync();
        },
        'filer': filer,
        'syncDuration': syncDuration
    };
});<commit_msg>Correct sync message for /.git folder<commit_after>define([
    'underscore',
    'hr/hr',
    'utils/url',
    'vendors/filer',
    'core/operations',
    'utils/dialogs',
    'utils/alerts'
], function(_, hr, Url, Filer, operations, dialogs, alerts) {
    var logger = hr.Logger.addNamespace("localfs");

    // Base folder for localfs
    var base = "/";

    // Constant mime type for a directory
    var MIME_DIRECTORY = "inode/directory";

    // Duration for sync (ms)
    syncDuration = 1*60*1000;

    // Create fs interface
    var filer = new Filer();

    var fsCall = function(method, args, context) {
        if (_.isUndefined(args)) args = [];
        if (!_.isArray(args)) args = [args];

        var d = Q.defer();
        args.push(function() {
            if (arguments.length == 1) return d.resolve(arguments[0]);
            d.resolve(arguments);
        });
        args.push(function(err) {
            logger.error("Error occurs: ", err);
            d.reject(err);
        })

        method.apply(context, args);

        return d.promise;
    };

    /*
     *  Init the localfs
     */
    var initFs = function(baseDir) {
        var box = require("core/box");

        base = "/"+baseDir;
        return fsCall(filer.init, {
            persistent: true,
            size: 10 * 1024 * 1024
        }, filer).then(function() {
            logger.log("ready");

            // Box fs changes
            box.on("box:watch", function() {
                logger.warn("box change");
                autoSync();
            })
        });
    };

    /*
     * Adapt path
     */
    var adaptPath = function(path) {
        path = base+path;
        path = path.replace("//", "/");
        return path;
    }

    /*
     *  Convert a vfs url in a path
     */
    var urlToPath = function(url) {
        var path = url.replace("/vfs/", "");
        if (path.length == 0) path = '/';
        if (path[0] != '/') path = "/" + path;
        return path;
    };

    /*
     *  Return informations about a fileentry
     */
    var getEntryInfos = function(fEntry) {
        return fsCall(fEntry.getMetadata, [], fEntry).then(function(metadata) {
            var path = fEntry.fullPath.replace(base, "/").replace("//", "/");
            var url = location.protocol+"//"+location.host+"/vfs"+path;

            if (fEntry.isDirectory) url = url + "/";

            return {
                "name": fEntry.name,
                "size": metadata.size,
                "mtime": metadata.modificationTime.getTime(),
                "mime": fEntry.isDirectory ? MIME_DIRECTORY : "application/octet-stream",
                "href": url,
                "exportUrl": fEntry.toURL(),
                "offline": true,
                '_fullPath': path
            };
        })
    };

    /*
     *  List a directory
     */
    var listDir = function(path) {
        path = adaptPath(path);

        logger.log("ls:", path);
        return fsCall(filer.ls, path, filer).then(function(entries) {
            return Q.all(_.map(entries, function(entry) {
                return getEntryInfos(entry);
            }))
        }).then(function(entries) {
            return entries;
        }, function(err) {
            logger.error("ls:", err);
        });
    };

    /*
     *  Create a file
     */
    var createFile = function(path) {
        path = adaptPath(path);
        logger.log("create:", path);
        return fsCall(filer.create, [path, true], filer);
    };

    /*
     *  Write file
     */
    var writeFile = function(path, data) {
        path = adaptPath(path);
        logger.log("write:", path);
        return fsCall(filer.write, [path, {
            'data': data || ""
        }], filer);
    };

    /*
     *  Open a file
     */
    var openFile = function(path) {
        path = adaptPath(path);
        logger.log("open:", path);
        return fsCall(filer.getEntry, [path], filer).then(function(fEntry) {
            return getEntryInfos(fEntry);
        })
    };

    /*
     *  Read a file
     */
    var readFile = function(path) {
        path = adaptPath(path);
        logger.log("read:", path);
        return fsCall(filer.open, [path], filer).then(function(file) {
            var d = Q.defer();

            var reader = new FileReader();
            reader.onerror = function(err) {
                d.reject(err);
            };
            reader.onload = function(e) {
                d.resolve(this.result);
            };
            reader.readAsText(file);

            return d.promise;
        });
    };

    /*
     *  Create a file
     */
    var createDirectory = function(path) {
        path = adaptPath(path);
        logger.log("mkdir:", path);
        return fsCall(filer.mkdir, [path, false], filer);
    };

    /*
     *  Move a file
     */
    var move = function(from, to) {
        from = adaptPath(from);
        to = adaptPath(to);

        logger.log("move:", from, "to", to);
        return fsCall(filer.mv, [from, '.', to], filer);
    };

    /*
     *  Remove a file or directory
     */
    var remove = function(path) {
        path = adaptPath(path);

        logger.log("remove:", path);
        return fsCall(filer.rm, [path], filer);
    };

    /*
     *  Sync a file in the box fs with the local fs
     *
     *  this will download the files and saved them in the localfs
     */
    var syncFileBoxToLocal = function() {
        var box = require("core/box");

        var doSync = function(fp) {
            var path = fp.path();
            if (path == "/.git") return Q();

            logger.log("sync:box->local:", path);

            if (fp.isDirectory()) {
                // Create the directory
                return createDirectory(path).then(function() {
                    // List subfiles
                    return fp.listdir();
                }).then(function(files) {
                    // Recursively sync files and directory
                    return Q.all(_.map(files, function(f) {
                        return doSync(f);
                    }));
                });
            } else {
                // Read file content
                return fp.read().then(function(content) {
                    // Write file content
                    return writeFile(path, content);
                });
            }
        };
        return operations.start("files.sync", function(op) {
            logger.warn("Start sync: box->local");
            return remove("/").then(function() {
                return doSync(box.root);
            }, function() {
                return doSync(box.root)
            }).then(function() {
                alerts.show("Workspace has been saved offline.", 5000);
                logger.warn("Finished sync: box->local");
            });
        }, {
            title: "Downloading ..."
        });
    };

    /*
     *  Sync localfs to vfs
     */
    var syncFileLocalToBox = function() {
        var File = require("models/file");
        var box = require("core/box");
        var messages = [];

        var doSyncDir = function(path, parent) {
            var localEntries, boxEntries, currentEntryInfos;
            if (path == "/.git") return Q();

            logger.log("sync:local->box:", path);

            // Get current directory
            return openFile(path).then(function(infos) {
                // Infos about this entry
                currentEntryInfos = infos;

                return listDir(path);
            }).then(function(entries) {
                // Entry in the browser
                localEntries = entries;
                return parent.listdir();
            }).then(function(entries) {
                // Entries on the boxes
                boxEntries = entries;
            }).then(function() {
                // Eliminate old useless entries
                return Q.all(_.map(boxEntries, function(boxFile) {
                    if (boxFile.path() == "/.git") return Q();

                    var localEntry = _.find(localEntries, function(localEntry) {
                        return localEntry.name == boxFile.get("name");
                    });

                    // File don't exists and box file older than current directory
                    if (!localEntry && boxFile.get("mtime") < currentEntryInfos.mtime) {
                        // -> Remove the file on the box
                        //logger.log("resync: need to remove ", boxFile.path());
                        messages.push({
                            'operation': "remove",
                            'path': boxFile.path(),
                            'message': "[conflict] You should manually remove "+boxFile.path()
                        });
                    }

                    // Do nothing
                    return Q();
                }));
            }).then(function() {
                // Update entries and create new entries
                return Q.all(_.map(localEntries, function(localEntry) {
                    var entryIsDir = localEntry.mime == MIME_DIRECTORY;
                    var boxFile = _.find(boxEntries, function(boxFile) {
                        return localEntry.name == boxFile.get("name");
                    });

                    // Is not a directory and:
                    if (!entryIsDir && (!boxFile    // File don't exist
                    || (boxFile.get("mtime") < localEntry.mtime)))    // or File modified offline
                    {
                        // -> Update box content
                        /*logger.log("resync: need to update ", localEntry._fullPath);
                        logger.log(" -> box:", boxFile.get("mtime"));
                        logger.log(" -> local:", localEntry.mtime);*/
                        return readFile(localEntry._fullPath).then(function(content) {
                            return parent.write(content, localEntry._fullPath);
                        });
                    }

                    // if a directory
                    if (entryIsDir) {
                        var syncEntry = function(newParent) {
                            return doSyncDir(localEntry._fullPath, newParent);
                        }

                        if (boxFile) {
                            if (boxFile.isDirectory()) {
                                return syncEntry(boxFile);
                            } else {
                                messages.push({
                                    'operation': "remove",
                                    'path': boxFile.path(),
                                    'message': "[conflict] You should manually remove "+boxFile.path()
                                });
                            }
                        } else {
                            return parent.mkdir(localEntry.name).then(function() {
                                return parent.getChild(localEntry.name);
                            }).then(syncEntry);
                        }
                    }

                    // Do nothing
                    return Q();
                }));
            }).fail(function(err) {
                logger.error("Error during sync: ", err);
            });
        };

        return operations.start("files.sync", function(op) {
            logger.warn("Start sync: local->box");
            return doSyncDir("/", box.root).then(function() {
                logger.warn("Finished sync: local->box");
            })
        }, {
            title: "Uploading changes..."
        }).then(function() {
            alerts.show("Offline changes have been uploaded to the workspace.", 5000);
            if (messages.length > 0) {
                return dialogs.alert("Conflict during synchronization:", _.pluck(messages, 'message').join("<br/>"));
            }
        });
    };

    /*
     *  Global sync:
     *      -> if never sync: download everything
     *      -> if already sync: upload changes and download last changes
     */
    var sync = function(options) {
        options = _.defaults({}, options || {}, {
            'updateLocal': false
        });

        if (hr.Offline.isConnected()) {
            var endT, startT = Date.now();

            return openFile("/").then(function(infos) {
                if (options.updateLocal) return Q();
                return syncFileLocalToBox();
            }, function() {
                return createDirectory("/");
            }).then(function() {
                return syncFileBoxToLocal();
            }).then(function() {
                //Calcul duration
                endT = Date.now();
                syncDuration = _.max([endT - startT, 5000]);
                updateAutoSync();

                alerts.show("Offline and Workspace have been synchronized.", 5000);
                return syncDuration;
            }, function(err) {
                logger.error("!!!!!! ERROR !!!!!!!", err);
            });
        } else {
            return Q.reject(new Error("Can't synchronize when offline"));
        }
    };

    /*
     *  Auto sync allow to resync the localfs every interval
     */
    var autoSync = null;
    var updateAutoSync = function() {
        logger.log("sync take ", syncDuration/1000,"seconds");
        autoSync =  _.throttle(function() {
            sync({
                updateLocal: true
            });
        }, 2*syncDuration);
    };
    updateAutoSync();

    // Run sync every 5min
    setTimeout(function() {
        autoSync();
    }, 5*60*1000);

    return {
        'getEntryInfos': getEntryInfos,
        'urlToPath': urlToPath,
        'init': initFs,
        'ls': listDir,
        'create': createFile,
        'mkdir': createDirectory,
        'write': writeFile,
        'read': readFile,
        'mv': move,
        'rm': remove,
        'reset': syncFileBoxToLocal,
        'sync': sync,
        'autoSync': function() {
            return autoSync();
        },
        'filer': filer,
        'syncDuration': syncDuration
    };
});<|endoftext|>


<commit_before>/*
 * test_phyx2ontology.js: Test whether phyx2ontology.js can be executed successfully.
 */

const BASE_DIR = 'phyx/';

// Node libraries.
const ChildProcess = require('child_process');
const fs = require('fs');

// Javascript libraries.
const tmp = require('tmp');
const chai = require('chai');

const assert = chai.assert;

const tmpfilename = tmp.fileSync().name;

describe('Executing phyx2ontology.js on all current Phyx files', function () {
  this.timeout(10000);

  const child = ChildProcess.spawnSync(process.execPath, [
    'phyx2ontology/phyx2ontology.js', BASE_DIR, '>', tmpfilename,
  ], {
    encoding: 'utf8',
    shell: true,
  });

  it('should execute successfully', function () {
    assert.isEmpty(child.stderr, 'Should not produce any output to STDERR');
    assert.isNull(child.signal, `Terminated because of signal ${child.signal}`);
    assert.equal(child.status, 0, 'Exit value should be zero');
  });

  it('should produce valid JSON output', function () {
    const jsonContent = fs.readFileSync(tmpfilename, { encoding: 'utf8' });
    let json = [];
    assert.doesNotThrow(function () {
      json = JSON.parse(jsonContent);
    }, SyntaxError);
    assert.isNotEmpty(json, 'Produced JSON should not be empty');
  });
});
<commit_msg>We now have warnings for max specifiers, so STDERR is no longer empty.<commit_after>/*
 * test_phyx2ontology.js: Test whether phyx2ontology.js can be executed successfully.
 */

const BASE_DIR = 'phyx/';

// Node libraries.
const ChildProcess = require('child_process');
const fs = require('fs');

// Javascript libraries.
const tmp = require('tmp');
const chai = require('chai');

const assert = chai.assert;

const tmpfilename = tmp.fileSync().name;

describe('Executing phyx2ontology.js on all current Phyx files', function () {
  this.timeout(10000);

  const child = ChildProcess.spawnSync(process.execPath, [
    'phyx2ontology/phyx2ontology.js', BASE_DIR, '>', tmpfilename,
  ], {
    encoding: 'utf8',
    shell: true,
  });

  it('should execute successfully', function () {
    assert.isNull(child.signal, `Terminated because of signal ${child.signal}`);
    assert.equal(child.status, 0, 'Exit value should be zero');
  });

  it('should produce valid JSON output', function () {
    const jsonContent = fs.readFileSync(tmpfilename, { encoding: 'utf8' });
    let json = [];
    assert.doesNotThrow(function () {
      json = JSON.parse(jsonContent);
    }, SyntaxError);
    assert.isNotEmpty(json, 'Produced JSON should not be empty');
  });
});
<|endoftext|>


<commit_before>// import client side soundworks and player experience
import * as soundworks from 'soundworks/client';
import PlayerExperience from './PlayerExperience.js';
import viewTemplates from '../shared/viewTemplates';
import viewContent from '../shared/viewContent';

// list of files to load (passed to the experience)
const files = [
  'sounds/gol1.mp3',
  'sounds/gol2.mp3',
  'sounds/gol3.mp3',
];

// launch application when document is fully loaded
window.addEventListener('load', () => {
  // configuration received from the server through the `index.html`
  // @see {~/src/server/index.js}
  // @see {~/html/default.ejs}
  const { appName, clientType, socketIO, assetsDomain }  = window.soundworksConfig;
  // initialize the 'player' client
  soundworks.client.init(clientType, { appName, socketIO });
  soundworks.client.setViewContentDefinitions(viewContent);
  soundworks.client.setViewTemplateDefinitions(viewTemplates);
  // create client side (player) experience
  const experience = new PlayerExperience(assetsDomain, files);

  // start the client
  soundworks.client.start();
});
<commit_msg>quito gol3<commit_after>// import client side soundworks and player experience
import * as soundworks from 'soundworks/client';
import PlayerExperience from './PlayerExperience.js';
import viewTemplates from '../shared/viewTemplates';
import viewContent from '../shared/viewContent';

// list of files to load (passed to the experience)
const files = [
  'sounds/gol1.mp3',
  'sounds/gol2.mp3',

];

// launch application when document is fully loaded
window.addEventListener('load', () => {
  // configuration received from the server through the `index.html`
  // @see {~/src/server/index.js}
  // @see {~/html/default.ejs}
  const { appName, clientType, socketIO, assetsDomain }  = window.soundworksConfig;
  // initialize the 'player' client
  soundworks.client.init(clientType, { appName, socketIO });
  soundworks.client.setViewContentDefinitions(viewContent);
  soundworks.client.setViewTemplateDefinitions(viewTemplates);
  // create client side (player) experience
  const experience = new PlayerExperience(assetsDomain, files);

  // start the client
  soundworks.client.start();
});
<|endoftext|>


<commit_before>/**
 * Convert an image-based heightmap into vertex-based height data.
 *
 * @param {THREE.Vector3[]} g
 *   The vertex array for plane geometry to modify with heightmap data. This
 *   method sets the `z` property of each vertex.
 * @param {Object} options
 *   A map of settings that control how the terrain is constructed and
 *   displayed. Valid values are the same as those for the `options` parameter
 *   of {@link THREE.Terrain}().
 */
THREE.Terrain.fromHeightmap = function(g, options) {
    var canvas = document.createElement('canvas'),
        context = canvas.getContext('2d'),
        rows = options.ySegments + 1,
        cols = options.xSegments + 1,
        spread = options.maxHeight - options.minHeight;
    canvas.width = cols;
    canvas.height = rows;
    context.drawImage(options.heightmap, 0, 0, canvas.width, canvas.height);
    var data = context.getImageData(0, 0, canvas.width, canvas.height).data;
    for (var row = 0; row < rows; row++) {
        for (var col = 0; col < cols; col++) {
            var i = row * cols + col,
                idx = i * 4;
            g[i].z = (data[idx] + data[idx+1] + data[idx+2]) / 765 * spread + options.minHeight;
        }
    }
};

/**
 * Convert a terrain plane into an image-based heightmap.
 *
 * Parameters are the same as for {@link THREE.Terrain.fromHeightmap} except
 * that if `options.heightmap` is a canvas element then the image will be
 * painted onto that canvas; otherwise a new canvas will be created.
 *
 * NOTE: this method performs an operation on an array of vertices, which
 * aren't available when using `BufferGeometry`. So, if you want to use this
 * method, make sure to set the `useBufferGeometry` option to `false` when
 * generating your terrain.
 *
 * @return {HTMLCanvasElement}
 *   A canvas with the relevant heightmap painted on it.
 */
THREE.Terrain.toHeightmap = function(g, options) {
    var hasMax = typeof options.maxHeight === 'undefined',
        hasMin = typeof options.minHeight === 'undefined',
        max = hasMax ? options.maxHeight : -Infinity,
        min = hasMin ? options.minHeight :  Infinity;
    if (!hasMax || !hasMin) {
        var max2 = max,
            min2 = min;
        for (var k = 0, l = g.length; k < l; k++) {
            if (g[k].z > max2) max2 = g[k].z;
            if (g[k].z < min2) min2 = g[k].z;
        }
        if (!hasMax) max = max2;
        if (!hasMin) min = min2;
    }
    var canvas = options.heightmap instanceof HTMLCanvasElement ? options.heightmap : document.createElement('canvas'),
        context = canvas.getContext('2d'),
        rows = options.ySegments + 1,
        cols = options.xSegments + 1,
        spread = options.maxHeight - options.minHeight;
    canvas.width = cols;
    canvas.height = rows;
    var d = context.createImageData(canvas.width, canvas.height),
        data = d.data;
    for (var row = 0; row < rows; row++) {
        for (var col = 0; col < cols; col++) {
            var i = row * cols + col,
            idx = i * 4;
            data[idx] = data[idx+1] = data[idx+2] = Math.round(((g[i].z - min) / spread) * 255);
            data[idx+3] = 255;
        }
    }
    context.putImageData(d, 0, 0);
    return canvas;
};
<commit_msg>some missed details in previous bugfix commit<commit_after>/**
 * Convert an image-based heightmap into vertex-based height data.
 *
 * @param {THREE.Vector3[]} g
 *   The vertex array for plane geometry to modify with heightmap data. This
 *   method sets the `z` property of each vertex.
 * @param {Object} options
 *   A map of settings that control how the terrain is constructed and
 *   displayed. Valid values are the same as those for the `options` parameter
 *   of {@link THREE.Terrain}().
 */
THREE.Terrain.fromHeightmap = function(g, options) {
    var canvas = document.createElement('canvas'),
        context = canvas.getContext('2d'),
        rows = options.ySegments + 1,
        cols = options.xSegments + 1,
        spread = options.maxHeight - options.minHeight;
    canvas.width = cols;
    canvas.height = rows;
    context.drawImage(options.heightmap, 0, 0, canvas.width, canvas.height);
    var data = context.getImageData(0, 0, canvas.width, canvas.height).data;
    for (var row = 0; row < rows; row++) {
        for (var col = 0; col < cols; col++) {
            var i = row * cols + col,
                idx = i * 4;
            g[i].z = (data[idx] + data[idx+1] + data[idx+2]) / 765 * spread + options.minHeight;
        }
    }
};

/**
 * Convert a terrain plane into an image-based heightmap.
 *
 * Parameters are the same as for {@link THREE.Terrain.fromHeightmap} except
 * that if `options.heightmap` is a canvas element then the image will be
 * painted onto that canvas; otherwise a new canvas will be created.
 *
 * NOTE: this method performs an operation on an array of vertices, which
 * aren't available when using `BufferGeometry`. So, if you want to use this
 * method, make sure to set the `useBufferGeometry` option to `false` when
 * generating your terrain.
 *
 * @return {HTMLCanvasElement}
 *   A canvas with the relevant heightmap painted on it.
 */
THREE.Terrain.toHeightmap = function(g, options) {
    var hasMax = typeof options.maxHeight !== 'undefined',
        hasMin = typeof options.minHeight !== 'undefined',
        max = hasMax ? options.maxHeight : -Infinity,
        min = hasMin ? options.minHeight :  Infinity;
    if (!hasMax || !hasMin) {
        var max2 = max,
            min2 = min;
        for (var k = 0, l = g.length; k < l; k++) {
            if (g[k].z > max2) max2 = g[k].z;
            if (g[k].z < min2) min2 = g[k].z;
        }
        if (!hasMax) max = max2;
        if (!hasMin) min = min2;
    }
    var canvas = options.heightmap instanceof HTMLCanvasElement ? options.heightmap : document.createElement('canvas'),
        context = canvas.getContext('2d'),
        rows = options.ySegments + 1,
        cols = options.xSegments + 1,
        spread = max - min;
    canvas.width = cols;
    canvas.height = rows;
    var d = context.createImageData(canvas.width, canvas.height),
        data = d.data;
    for (var row = 0; row < rows; row++) {
        for (var col = 0; col < cols; col++) {
            var i = row * cols + col,
            idx = i * 4;
            data[idx] = data[idx+1] = data[idx+2] = Math.round(((g[i].z - min) / spread) * 255);
            data[idx+3] = 255;
        }
    }
    context.putImageData(d, 0, 0);
    return canvas;
};
<|endoftext|>


<commit_before>function main() {
    var DISPLAY_WIDTH = 320;
    var DISPLAY_HEIGHT = 450;
    var STAGE_WIDTH = DISPLAY_WIDTH;
    var STAGE_HEIGHT = DISPLAY_WIDTH;
    var SCORE_LEFT = 16;
    var SCORE_TOP = 16;
    var SCORE_TITLE_WIDTH = 48;

    enchant();
    var core = new Core(DISPLAY_WIDTH, DISPLAY_HEIGHT);
    core.preload("img/chara1.png", "img/icon1.png", "img/cursor.png", "img/heart.png");
    core.fps = 15;
    core.onload = function () {
        var background = (function () {
            var sprite = new Sprite(STAGE_WIDTH, STAGE_HEIGHT);
            sprite.image = (function () {
                var surface = new Surface(STAGE_WIDTH, STAGE_HEIGHT);
                var context = surface.context;
                context.fillStyle = (function () {
                    var grad = context.createLinearGradient(0, 0, 0, STAGE_HEIGHT);
                    grad.addColorStop(0, "#cceedd");
                    grad.addColorStop(0.5, "#aaccbb");
                    grad.addColorStop(1, "#668877");
                    return grad;
                })();
                context.fillRect(0, 0, STAGE_WIDTH, STAGE_HEIGHT);
                return surface;
            })();
            return sprite;
        })();
        var bear = (function () {
            var width = 32;
            var height = 32;
            var sprite = new Sprite(width, height);
            sprite.image = core.assets["img/chara1.png"];
            sprite.frame = [0];
            sprite.x = (STAGE_WIDTH / 2) - (width / 2);
            sprite.y = (STAGE_HEIGHT / 2) - (height / 2);
            return sprite;
        })();
        var controller = (function () {
            var areaWidth = STAGE_WIDTH;
            var areaHeight = DISPLAY_HEIGHT - STAGE_HEIGHT;
            var sprite = new Sprite(areaWidth, areaHeight);
            sprite.image = (function () {
                var surface = new Surface(areaWidth, areaHeight);
                surface.context.fillStyle = "#ffffff";
                surface.context.fillRect(0, 0, areaWidth, areaHeight);
                return surface;
            })();
            sprite.x = 0;
            sprite.y = STAGE_HEIGHT;
            return sprite;
        })();
        var cursor = (function () {
            var width = 120;
            var height = 120;
            var areaWidth = STAGE_WIDTH;
            var areaHeight = DISPLAY_HEIGHT - STAGE_HEIGHT;
            var sprite = new Sprite(width, height);
            sprite.image = core.assets["img/cursor.png"];
            sprite.x = (areaWidth / 2) - (width / 2);
            sprite.y = STAGE_HEIGHT + (areaHeight - height) / 2;
            return sprite;
        })();
        var scoreTitle = (function () {
            var label = new Label();
            label.text = "Score:";
            label.font = "14px/16px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
            label.x = SCORE_LEFT;
            label.y = SCORE_TOP;
            return label;
        })();
        var scoreNumber = (function () {
            var label = new Label();
            label.text = "0";
            label.font = "bold 16px/16px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
            label.x = SCORE_LEFT + SCORE_TITLE_WIDTH;
            label.y = SCORE_TOP;
            return label;
        })();
        core.rootScene.addChild(background);
        core.rootScene.addChild(bear);
        core.rootScene.addChild(controller);
        core.rootScene.addChild(cursor);
        core.rootScene.addChild(scoreTitle);
        core.rootScene.addChild(scoreNumber);

        // 左右どちらのボタンが押されているかを管理します
        var INPUT_NONE = 0;
        var INPUT_LEFT = 1;
        var INPUT_RIGHT = 2;
        var currentInput = INPUT_NONE;

        // ハートをキャッチするたびに増える得点です
        var score = 0;

        // ボールがプレイヤーに当たった時に true になります
        var gameover = false;

        /**
         * ボタン上をタッチまたはスワイプした際に発火する関数です。
         * 以下の処理を行います。
         *
         * - ボタンのスプライトを変更し、押された感じを表現します
         * - プレイヤーのモーションを走っている状態にします
         *
         * @param {Event} e
         */
        var inputCursor = function (e) {
            var input = (e.x < STAGE_WIDTH / 2) ? INPUT_LEFT : INPUT_RIGHT;
            if (currentInput !== input) {
                currentInput = input;
                cursor.frame = [input];

                if (!gameover) {
                    var newScale = (currentInput === INPUT_RIGHT) ? 1 : -1;
                    bear.scaleX = newScale;
                    bear.frame = [0, 0, 1, 1, 0, 0, 2, 2];
                }
            }
        };

        /**
         * ボタンから指を離した際に発火する関数です。
         * 以下の処理を行います。
         *
         * - ボタンのスプライトをデフォルトに変更します
         * - プレイヤーのモーションを止まっている状態にします
         *
         * @param {Event} e
         */
        var stopCursor = function (e) {
            currentInput = INPUT_NONE;
            cursor.frame = [INPUT_NONE];
            if (!gameover) {
                bear.frame = [0];
            }
        };
        cursor.addEventListener(Event.TOUCH_START, inputCursor);
        cursor.addEventListener(Event.TOUCH_MOVE, inputCursor);
        cursor.addEventListener(Event.TOUCH_END, stopCursor);

        /**
         * フレーム毎に実行される関数です。
         * もしも右か左のボタンが押されていたら、プレイヤーの位置を移動させます。
         *
         * @param {Event} e
         */
        var moveBear = function (e) {
            if (currentInput === INPUT_NONE) {
                return;
            }

            var dx = (currentInput === INPUT_LEFT) ? -5 : 5;
            var newX = Math.min(Math.max(bear.x + dx, 0), STAGE_WIDTH - 32);
            bear.x = newX;
        };
        bear.addEventListener(Event.ENTER_FRAME, moveBear);

        var createHeart = function () {
            var width = 32;
            var height = 32;
            var sprite = new Sprite(width, height);
            sprite.image = core.assets["img/heart.png"];
            sprite.x = Math.random() * (STAGE_WIDTH - width);
            var topToBottom = (Math.random() < 0.5); // true: 上から下, false: 下から上
            sprite.y = topToBottom ? -width : STAGE_HEIGHT;
            sprite.frame = [0, 0, 0, 1, 1, 1];
            sprite.addEventListener(Event.ENTER_FRAME, function (e) {
                if (gameover) {
                    return;
                }
                sprite.y += topToBottom ? 3 : -3;
                var out = (topToBottom && STAGE_HEIGHT < sprite.y) || (!topToBottom && sprite.y < -width);
                if (out) {
                    core.rootScene.removeChild(sprite);
                }
                // プレイヤーがハートをキャッチしたら得点を +1 します
                if (sprite.within(bear, width / 2)) {
                    core.rootScene.removeChild(sprite);
                    score++;
                    scoreNumber.text = score;
                }
            });
            return sprite;
        };
        var createBall = function (e) {
            var width = 16;
            var height = 16;
            var sprite = new Sprite(width, height);
            sprite.image = core.assets["img/icon1.png"];
            sprite.x = Math.random() * (STAGE_WIDTH - width);
            var topToBottom = (Math.random() < 0.5); // true: 上から下, false: 下から上
            var speed = 2 + (Math.random() * 3);
            sprite.y = topToBottom ? - width : STAGE_HEIGHT;
            var frameIndex = (Math.random() < 0.5) ? 0 : 1;
            sprite.frame = [frameIndex];
            sprite.addEventListener(Event.ENTER_FRAME, function (e) {
                sprite.rotate(15);
                if (gameover) {
                    return;
                }
                sprite.y += topToBottom ? speed : - speed;
                var out = (topToBottom && STAGE_HEIGHT < sprite.y) || (!topToBottom && sprite.y < - width);
                if (out) {
                    core.rootScene.removeChild(sprite);
                }
                // ボールがプレイヤーに当たったらゲームオーバーとします
                if (sprite.within(bear, width)) {
                    gameover = true;
                    bear.frame = [3];
                    bear.removeEventListener(Event.ENTER_FRAME, moveBear);
                    bear.tl.moveTo(bear.x, STAGE_HEIGHT + 64, 15, function (t, b, c, d) {
                        var peak = 0.25;
                        var x = (t / d) - peak;
                        return 2 * (x * x * (c - b) + b - (peak * peak));
                    });
                    core.rootScene.removeEventListener(Event.ENTER_FRAME, createObject);
                }
            });
            return sprite;
        };
        var createObject = function (e) {
            var rand = Math.random();
            if (0.06 < rand) {
                return;
            }

            if (0.03 < rand) {
                var heart = createHeart();
                core.rootScene.insertBefore(heart, controller);
            } else {
                var ball = createBall();
                core.rootScene.insertBefore(ball, controller);
            }
        };
        core.rootScene.addEventListener(Event.ENTER_FRAME, createObject);
    };
    core.start();
}
<commit_msg>Replace rootSchene with new Scene<commit_after>function main() {
    var DISPLAY_WIDTH = 320;
    var DISPLAY_HEIGHT = 450;
    var STAGE_WIDTH = DISPLAY_WIDTH;
    var STAGE_HEIGHT = DISPLAY_WIDTH;
    var SCORE_LEFT = 16;
    var SCORE_TOP = 16;
    var SCORE_TITLE_WIDTH = 48;

    enchant();
    var core = new Core(DISPLAY_WIDTH, DISPLAY_HEIGHT);
    core.preload("img/chara1.png", "img/icon1.png", "img/cursor.png", "img/heart.png");
    core.fps = 15;
    core.onload = function () {
        var background = (function () {
            var sprite = new Sprite(STAGE_WIDTH, STAGE_HEIGHT);
            sprite.image = (function () {
                var surface = new Surface(STAGE_WIDTH, STAGE_HEIGHT);
                var context = surface.context;
                context.fillStyle = (function () {
                    var grad = context.createLinearGradient(0, 0, 0, STAGE_HEIGHT);
                    grad.addColorStop(0, "#cceedd");
                    grad.addColorStop(0.5, "#aaccbb");
                    grad.addColorStop(1, "#668877");
                    return grad;
                })();
                context.fillRect(0, 0, STAGE_WIDTH, STAGE_HEIGHT);
                return surface;
            })();
            return sprite;
        })();
        var bear = (function () {
            var width = 32;
            var height = 32;
            var sprite = new Sprite(width, height);
            sprite.image = core.assets["img/chara1.png"];
            sprite.frame = [0];
            sprite.x = (STAGE_WIDTH / 2) - (width / 2);
            sprite.y = (STAGE_HEIGHT / 2) - (height / 2);
            return sprite;
        })();
        var controller = (function () {
            var areaWidth = STAGE_WIDTH;
            var areaHeight = DISPLAY_HEIGHT - STAGE_HEIGHT;
            var sprite = new Sprite(areaWidth, areaHeight);
            sprite.image = (function () {
                var surface = new Surface(areaWidth, areaHeight);
                surface.context.fillStyle = "#ffffff";
                surface.context.fillRect(0, 0, areaWidth, areaHeight);
                return surface;
            })();
            sprite.x = 0;
            sprite.y = STAGE_HEIGHT;
            return sprite;
        })();
        var cursor = (function () {
            var width = 120;
            var height = 120;
            var areaWidth = STAGE_WIDTH;
            var areaHeight = DISPLAY_HEIGHT - STAGE_HEIGHT;
            var sprite = new Sprite(width, height);
            sprite.image = core.assets["img/cursor.png"];
            sprite.x = (areaWidth / 2) - (width / 2);
            sprite.y = STAGE_HEIGHT + (areaHeight - height) / 2;
            return sprite;
        })();
        var scoreTitle = (function () {
            var label = new Label();
            label.text = "Score:";
            label.font = "14px/16px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
            label.x = SCORE_LEFT;
            label.y = SCORE_TOP;
            return label;
        })();
        var scoreNumber = (function () {
            var label = new Label();
            label.text = "0";
            label.font = "bold 16px/16px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
            label.x = SCORE_LEFT + SCORE_TITLE_WIDTH;
            label.y = SCORE_TOP;
            return label;
        })();

        var gameScene = new Scene();
        gameScene.addChild(background);
        gameScene.addChild(bear);
        gameScene.addChild(controller);
        gameScene.addChild(cursor);
        gameScene.addChild(scoreTitle);
        gameScene.addChild(scoreNumber);

        // 左右どちらのボタンが押されているかを管理します
        var INPUT_NONE = 0;
        var INPUT_LEFT = 1;
        var INPUT_RIGHT = 2;
        var currentInput = INPUT_NONE;

        // ハートをキャッチするたびに増える得点です
        var score = 0;

        // ボールがプレイヤーに当たった時に true になります
        var gameover = false;

        /**
         * ボタン上をタッチまたはスワイプした際に発火する関数です。
         * 以下の処理を行います。
         *
         * - ボタンのスプライトを変更し、押された感じを表現します
         * - プレイヤーのモーションを走っている状態にします
         *
         * @param {Event} e
         */
        var inputCursor = function (e) {
            var input = (e.x < STAGE_WIDTH / 2) ? INPUT_LEFT : INPUT_RIGHT;
            if (currentInput !== input) {
                currentInput = input;
                cursor.frame = [input];

                if (!gameover) {
                    var newScale = (currentInput === INPUT_RIGHT) ? 1 : -1;
                    bear.scaleX = newScale;
                    bear.frame = [0, 0, 1, 1, 0, 0, 2, 2];
                }
            }
        };

        /**
         * ボタンから指を離した際に発火する関数です。
         * 以下の処理を行います。
         *
         * - ボタンのスプライトをデフォルトに変更します
         * - プレイヤーのモーションを止まっている状態にします
         *
         * @param {Event} e
         */
        var stopCursor = function (e) {
            currentInput = INPUT_NONE;
            cursor.frame = [INPUT_NONE];
            if (!gameover) {
                bear.frame = [0];
            }
        };
        cursor.addEventListener(Event.TOUCH_START, inputCursor);
        cursor.addEventListener(Event.TOUCH_MOVE, inputCursor);
        cursor.addEventListener(Event.TOUCH_END, stopCursor);

        /**
         * フレーム毎に実行される関数です。
         * もしも右か左のボタンが押されていたら、プレイヤーの位置を移動させます。
         *
         * @param {Event} e
         */
        var moveBear = function (e) {
            if (currentInput === INPUT_NONE) {
                return;
            }

            var dx = (currentInput === INPUT_LEFT) ? -5 : 5;
            var newX = Math.min(Math.max(bear.x + dx, 0), STAGE_WIDTH - 32);
            bear.x = newX;
        };
        bear.addEventListener(Event.ENTER_FRAME, moveBear);

        var createHeart = function () {
            var width = 32;
            var height = 32;
            var sprite = new Sprite(width, height);
            sprite.image = core.assets["img/heart.png"];
            sprite.x = Math.random() * (STAGE_WIDTH - width);
            var topToBottom = (Math.random() < 0.5); // true: 上から下, false: 下から上
            sprite.y = topToBottom ? -width : STAGE_HEIGHT;
            sprite.frame = [0, 0, 0, 1, 1, 1];
            sprite.addEventListener(Event.ENTER_FRAME, function (e) {
                if (gameover) {
                    return;
                }
                sprite.y += topToBottom ? 3 : -3;
                var out = (topToBottom && STAGE_HEIGHT < sprite.y) || (!topToBottom && sprite.y < -width);
                if (out) {
                    gameScene.removeChild(sprite);
                }
                // プレイヤーがハートをキャッチしたら得点を +1 します
                if (sprite.within(bear, width / 2)) {
                    gameScene.removeChild(sprite);
                    score++;
                    scoreNumber.text = score;
                }
            });
            return sprite;
        };
        var createBall = function (e) {
            var width = 16;
            var height = 16;
            var sprite = new Sprite(width, height);
            sprite.image = core.assets["img/icon1.png"];
            sprite.x = Math.random() * (STAGE_WIDTH - width);
            var topToBottom = (Math.random() < 0.5); // true: 上から下, false: 下から上
            var speed = 2 + (Math.random() * 3);
            sprite.y = topToBottom ? - width : STAGE_HEIGHT;
            var frameIndex = (Math.random() < 0.5) ? 0 : 1;
            sprite.frame = [frameIndex];
            sprite.addEventListener(Event.ENTER_FRAME, function (e) {
                sprite.rotate(15);
                if (gameover) {
                    return;
                }
                sprite.y += topToBottom ? speed : - speed;
                var out = (topToBottom && STAGE_HEIGHT < sprite.y) || (!topToBottom && sprite.y < - width);
                if (out) {
                    gameScene.removeChild(sprite);
                }
                // ボールがプレイヤーに当たったらゲームオーバーとします
                if (sprite.within(bear, width)) {
                    gameover = true;
                    bear.frame = [3];
                    bear.removeEventListener(Event.ENTER_FRAME, moveBear);
                    bear.tl.moveTo(bear.x, STAGE_HEIGHT + 64, 15, function (t, b, c, d) {
                        var peak = 0.25;
                        var x = (t / d) - peak;
                        return 2 * (x * x * (c - b) + b - (peak * peak));
                    });
                    gameScene.removeEventListener(Event.ENTER_FRAME, createObject);
                }
            });
            return sprite;
        };
        var createObject = function (e) {
            var rand = Math.random();
            if (0.06 < rand) {
                return;
            }

            if (0.03 < rand) {
                var heart = createHeart();
                gameScene.insertBefore(heart, controller);
            } else {
                var ball = createBall();
                gameScene.insertBefore(ball, controller);
            }
        };
        gameScene.addEventListener(Event.ENTER_FRAME, createObject);
        core.replaceScene(gameScene);
    };
    core.start();
}
<|endoftext|>


<commit_before>/**
 * @fileoverview Proxy client respecting 'Retry-After' header. Request are
 * execute serially.
 */

goog.provide('ydn.client.Proxy');
goog.provide('ydn.client.SerialProxy');
goog.require('goog.async.Deferred');
goog.require('ydn.client.Client');
goog.require('ydn.client.SimpleHttpRequest');

/**
 * OAuth client.
 * @param {ydn.client.Client} client
 * @param {string} proxy_path xhr manager.
 * @constructor
 * @implements {ydn.client.Client}
 * @const
 */
ydn.client.Proxy = function(client, proxy_path) {
  /**
   * @protected
   * @type {ydn.client.Client}
   */
  this.client = client;
  /**
   * @protected
   * @type {string}
   */
  this.proxy_path = proxy_path;
  /**
   * @protected
   * @type {number}
   */
  this.next_retry = NaN;
  /**
   * @type {Array.<ydn.client.Proxy.Request>}
   * @private
   */
  this.reqs_ = [];
  /**
   * True in request.
   * @type {boolean}
   * @private
   */
  this.in_req_ = false;
};

/**
 * @inheritDoc
 */
ydn.client.Proxy.prototype.request = function(req) {
  return new ydn.client.Proxy.Request(req, this);
};

/**
 * @return {string}
 */
ydn.client.Proxy.prototype.getProxyPath = function() {
  return this.proxy_path;
};

/**
 * Request data.
 * @param {ydn.client.HttpRequestData} args
 * @param {ydn.client.Proxy} parent xhr manager.
 * @constructor
 * @extends {ydn.client.SimpleHttpRequest}
 * @struct
 */
ydn.client.Proxy.Request = function(args, parent) {
  args.path = parent.proxy_path + args.path;
  /**
   * @protected
   * @final
   * @type {!ydn.client.HttpRequest}
   */
  this.req = parent.client.request(args);
  /**
   * @final
   * @type {ydn.client.Proxy}
   */
  this.parent = parent;
  /**
   * @type {Function}
   * @private
   */
  this.cb_ = null;
  this.scope_ = undefined;
};
goog.inherits(ydn.client.Proxy.Request, ydn.client.SimpleHttpRequest);

/**
 * @define {boolean} debug flag.
 */
ydn.client.Proxy.DEBUG = goog.DEBUG;

/**
 * Execute the request.
 * @param {function(this: T, Object, ydn.client.HttpRespondData)?} cb
 * @param {T=} opt_scope scope.
 * @template T
 */
ydn.client.Proxy.Request.prototype.execute = function(cb, opt_scope) {
  if (this.parent.in_req_) {
    this.cb_ = cb;
    this.scope_ = opt_scope;
    this.parent.reqs_.push(this);
    return;
  }
  this.parent.in_req_ = true;
  /**
   * @this {ydn.client.Proxy.Request}
   * @param {Object} json
   * @param {ydn.client.HttpRespondData} raw
   */
  var handleRequest = function(json, raw) {
    var retry = raw.getHeader('retry-after');
    if (retry) {
      var is_numeric = !/[^0-9|\.]/.test(retry);
      if (is_numeric) {
        // retry after in second.
        this.parent.next_retry = parseFloat(retry) * 1000 + goog.now();
      } else {
        // retry after by date
        this.parent.next_retry = new Date(retry).getTime();
      }
      if (ydn.client.Proxy.DEBUG) {
        goog.global.console.info('Next retry ' + this.parent.next_retry + ', now ' + goog.now());
      }
    } else {
      this.parent.next_retry = NaN;
    }
    if (cb) {
      cb.call(opt_scope, json, raw);
    }
    this.parent.in_req_ = false;
    var req = this.parent.reqs_.pop();
    if (req) {
      req.execute(req.cb_, req.scope_);
      req.cb_ = null;
      req.scope_ = null;
    }
  };
  var intv = this.parent.next_retry - goog.now();
  if (intv > 0) {
    if (ydn.client.Proxy.DEBUG) {
      goog.global.console.info('Proxy will call after ' + intv + ' ms');
    }
    goog.Timer.callOnce(function() {
      this.parent.next_retry = NaN;
      this.req.execute(handleRequest, this);
    }, intv, this);
  } else {
    this.req.execute(handleRequest, this);
  }
};

/**
 * Test function.
 * @param {number} n try 6.
 * @private
 */
ydn.client.Proxy.test_ = function(n) {
  var px = ydn.client.getClient('proxy');
  goog.global.console.assert(px, 'no proxy client');
  var req = px.request(new ydn.client.HttpRequestData('https://api.mixpanel.com/track/'));
  req.execute(function(json, raw) {
    goog.global.console.info(n);
    if (n > 0) {
      n--;
      ydn.client.Proxy.test_(n);
    }
  });
};

<commit_msg>fix info sniff bug.<commit_after>/**
 * @fileoverview Proxy client respecting 'Retry-After' header. Request are
 * execute serially.
 */

goog.provide('ydn.client.Proxy');
goog.provide('ydn.client.SerialProxy');
goog.require('goog.async.Deferred');
goog.require('ydn.client.Client');
goog.require('ydn.client.SimpleHttpRequest');

/**
 * OAuth client.
 * @param {ydn.client.Client} client
 * @param {string} proxy_path xhr manager.
 * @constructor
 * @implements {ydn.client.Client}
 * @const
 */
ydn.client.Proxy = function(client, proxy_path) {
  /**
   * @protected
   * @type {ydn.client.Client}
   */
  this.client = client;
  /**
   * @protected
   * @type {string}
   */
  this.proxy_path = proxy_path;
  /**
   * @protected
   * @type {number}
   */
  this.next_retry = NaN;
  /**
   * @type {Array.<ydn.client.Proxy.Request>}
   * @private
   */
  this.reqs_ = [];
  /**
   * True in request.
   * @type {boolean}
   * @private
   */
  this.in_req_ = false;
};

/**
 * @inheritDoc
 */
ydn.client.Proxy.prototype.request = function(req) {
  return new ydn.client.Proxy.Request(req, this);
};

/**
 * @return {string}
 */
ydn.client.Proxy.prototype.getProxyPath = function() {
  return this.proxy_path;
};

/**
 * Request data.
 * @param {ydn.client.HttpRequestData} args
 * @param {ydn.client.Proxy} parent xhr manager.
 * @constructor
 * @extends {ydn.client.SimpleHttpRequest}
 * @struct
 */
ydn.client.Proxy.Request = function(args, parent) {
  args.path = parent.proxy_path + args.path;
  /**
   * @protected
   * @final
   * @type {!ydn.client.HttpRequest}
   */
  this.req = parent.client.request(args);
  /**
   * @final
   * @type {ydn.client.Proxy}
   */
  this.parent = parent;
  /**
   * @type {Function}
   * @private
   */
  this.cb_ = null;
  this.scope_ = undefined;
};
goog.inherits(ydn.client.Proxy.Request, ydn.client.SimpleHttpRequest);

/**
 * @define {boolean} debug flag.
 */
ydn.client.Proxy.DEBUG = goog.DEBUG;

/**
 * Execute the request.
 * @param {function(this: T, Object, ydn.client.HttpRespondData)?} cb
 * @param {T=} opt_scope scope.
 * @template T
 */
ydn.client.Proxy.Request.prototype.execute = function(cb, opt_scope) {
  if (this.parent.in_req_) {
    this.cb_ = cb;
    this.scope_ = opt_scope;
    this.parent.reqs_.push(this);
    return;
  }
  this.parent.in_req_ = true;
  /**
   * @this {ydn.client.Proxy.Request}
   * @param {Object} json
   * @param {ydn.client.HttpRespondData} raw
   */
  var handleRequest = function(json, raw) {
    // todo: need to think about Request timeout
    // otherwise req queue will never flush.
    var retry = raw.getHeader('retry-after');
    if (retry) {
      var is_numeric = !/[^0-9|\.]/.test(retry);
      if (is_numeric) {
        // retry after in second.
        this.parent.next_retry = parseFloat(retry) * 1000 + goog.now();
      } else {
        // retry after by date
        this.parent.next_retry = new Date(retry).getTime();
      }
      if (ydn.client.Proxy.DEBUG) {
        goog.global.console.info('Next retry ' + this.parent.next_retry + ', now ' + goog.now());
      }
    } else {
      this.parent.next_retry = NaN;
    }
    if (cb) {
      cb.call(opt_scope, json, raw);
    }
    this.parent.in_req_ = false;
    var req = this.parent.reqs_.pop();
    if (req) {
      req.execute(req.cb_, req.scope_);
      req.cb_ = null;
      req.scope_ = null;
    }
  };
  var intv = this.parent.next_retry - goog.now();
  if (intv > 0) {
    if (ydn.client.Proxy.DEBUG) {
      goog.global.console.info('Proxy will call after ' + intv + ' ms');
    }
    goog.Timer.callOnce(function() {
      this.parent.next_retry = NaN;
      this.req.execute(handleRequest, this);
    }, intv, this);
  } else {
    this.req.execute(handleRequest, this);
  }
};

/**
 * Test function.
 * @param {number} n try 6.
 * @private
 */
ydn.client.Proxy.test_ = function(n) {
  var px = ydn.client.getClient('proxy');
  goog.global.console.assert(px, 'no proxy client');
  var req = px.request(new ydn.client.HttpRequestData('https://api.mixpanel.com/track/'));
  req.execute(function(json, raw) {
    goog.global.console.info(n);
    if (n > 0) {
      n--;
      ydn.client.Proxy.test_(n);
    }
  });
};

<|endoftext|>


<commit_before>'use strict';

angular.module('admin').controller('UserListController', ['$scope', '$filter', 'Admin',
  function ($scope, $filter, Admin) {
    Admin.query(function (data) {
      $scope.users = data;
      $scope.buildPager();
    });

    $scope.buildPager = function () {
      $scope.pagedItems = [];
      $scope.itemsPerPage = 15;
      $scope.currentPage = 1;
      $scope.filter = {};
      $scope.figureOutItemsToDisplay();
    };

    $scope.figureOutItemsToDisplay = function () {
      // $scope.filteredItems = $filter('filter')($scope.users, {
      //   $: $scope.search
      // });
      $scope.filteredItems = $filter('users_filter')($scope.users, $scope.filter);
      $scope.filterLength = $scope.filteredItems.length;
      var begin = (($scope.currentPage - 1) * $scope.itemsPerPage);
      var end = begin + $scope.itemsPerPage;
      $scope.pagedItems = $scope.filteredItems.slice(begin, end);
    };

    $scope.pageChanged = function () {
      $scope.figureOutItemsToDisplay();
    };
  }
]);
<commit_msg>Commited from HaNhatLenh at Sun, Jul 23, 2017 10:54:54 AM<commit_after>'use strict';

angular.module('admin').controller('UserListController', ['$scope', '$filter', 'Admin',
  function ($scope, $filter, Admin) {
    Admin.query(function (data) {
      $scope.users = data;
      $scope.buildPager();
    });

    $scope.buildPager = function () {
      $scope.pagedItems = [];
      $scope.itemsPerPage = 15;
      $scope.currentPage = 1;
      $scope.filter = {};
      $scope.figureOutItemsToDisplay();
    };

    $scope.figureOutItemsToDisplay = function () {
      // $scope.filteredItems = $filter('filter')($scope.users, {
      //   $: $scope.search
      // });
      console.log($scope.users);
      console.log($scope.filter);
      $scope.filteredItems = $filter('users_filter')($scope.users, $scope.filter);
      $scope.filterLength = $scope.filteredItems.length;
      var begin = (($scope.currentPage - 1) * $scope.itemsPerPage);
      var end = begin + $scope.itemsPerPage;
      $scope.pagedItems = $scope.filteredItems.slice(begin, end);
    };

    $scope.pageChanged = function () {
      $scope.figureOutItemsToDisplay();
    };
  }
]);
<|endoftext|>


<commit_before>jQuery(function($) {
  var app = new ExplorerApp({
    el: $('.recline-app')
  })
});

var ExplorerApp = Backbone.View.extend({
  events: {
    'submit form.js-import-url': '_onImportURL',
    'submit .js-import-dialog-file form': '_onImportFile'
  },

  initialize: function() {
    this.el = $(this.el);
    this.explorer = null;
    this.explorerDiv = $('.data-explorer-here');
    _.bindAll(this, 'viewExplorer', 'viewHome');

    this.router = new Backbone.Router();
    this.router.route('', 'home', this.viewHome);
    this.router.route(/explorer/, 'explorer', this.viewExplorer);
    Backbone.history.start();

    var state = recline.Util.parseQueryString(decodeURIComponent(window.location.search));
    if (state) {
      _.each(state, function(value, key) {
        try {
          value = JSON.parse(value);
        } catch(e) {}
        state[key] = value;
      });
      if (state.embed) {
        $('.navbar').hide();
        $('body').attr('style', 'padding-top: 0px');
      }
    }
    var dataset = null;
    // special cases for demo / memory dataset
    if (state.url === 'demo' || state.backend === 'memory') {
      dataset = localDataset();
    }
    else if (state.dataset || state.url) {
      dataset = recline.Model.Dataset.restore(state);
    }
    if (dataset) {
      this.createExplorer(dataset, state);
    }
  },

  viewHome: function() {
    this.switchView('home');
  },

  viewExplorer: function() {
    this.router.navigate('explorer');
    this.switchView('explorer');
  },

  switchView: function(path) {
    $('.backbone-page').hide();
    var cssClass = path.replace('/', '-');
    $('.page-' + cssClass).show();
  },

  // make Explorer creation / initialization in a function so we can call it
  // again and again
  createExplorer: function(dataset, state) {
    var self = this;
    // remove existing data explorer view
    var reload = false;
    if (this.dataExplorer) {
      this.dataExplorer.remove();
      reload = true;
    }
    this.dataExplorer = null;
    var $el = $('
');
    $el.appendTo(this.explorerDiv);
    this.dataExplorer = new recline.View.DataExplorer({
      model: dataset,
      el: $el,
      state: state
    });
    this._setupPermaLink(this.dataExplorer);
    this._setupEmbed(this.dataExplorer);

    this.viewExplorer();
  },

  _setupPermaLink: function(explorer) {
    var self = this;
    var $viewLink = this.el.find('.js-share-and-embed-dialog .view-link');
    explorer.state.bind('change', function() {
      $viewLink.val(self.makePermaLink(explorer.state));
    });
    $viewLink.val(self.makePermaLink(explorer.state));
  },

  _setupEmbed: function(explorer) {
    var self = this;
    var $embedLink = this.el.find('.js-share-and-embed-dialog .view-embed');
    function makeEmbedLink(state) {
      var link = self.makePermaLink(state);
      link = link + '&embed=true';
      var out = $.mustache('', {link: link});
      return out;
    }
    explorer.state.bind('change', function() {
      $embedLink.val(makeEmbedLink(explorer.state));
    });
    $embedLink.val(makeEmbedLink(explorer.state));
  },

  makePermaLink: function(state) {
    var qs = recline.Util.composeQueryString(state.toJSON());
    return window.location.origin + window.location.pathname + qs;
  },

  // setup the loader menu in top bar
  setupLoader: function(callback) {
    // pre-populate webstore load form with an example url
    var demoUrl = 'http://thedatahub.org/api/data/b9aae52b-b082-4159-b46f-7bb9c158d013';
    $('form.js-import-url input[name="source"]').val(demoUrl);
  },

  _onImportURL: function(e) {
    e.preventDefault();
    $('.modal.js-import-dialog-url').modal('hide');
    var $form = $(e.target);
    var source = $form.find('input[name="source"]').val();
    var datasetInfo = {
      id: 'my-dataset',
      url: source,
      webstore_url: source
    };
    var type = $form.find('select[name="backend_type"]').val();
    if (type === 'csv' || type === 'excel') {
      datasetInfo.format = type;
      type = 'dataproxy';
    }
    var dataset = new recline.Model.Dataset(datasetInfo, type);
    this.createExplorer(dataset);
  },

  _onImportFile: function(e) {
    var self = this;
    e.preventDefault();
    var $form = $(e.target);
    $('.modal.js-import-dialog-file').modal('hide');
    var $file = $form.find('input[type="file"]')[0];
    var file = $file.files[0];
    var options = {
      separator : $form.find('input[name="separator"]').val(),
      delimiter : $form.find('input[name="delimiter"]').val(),
      encoding : $form.find('input[name="encoding"]').val()
    };
    recline.Backend.loadFromCSVFile(file, function(dataset) {
        self.createExplorer(dataset)
      },
      options
    );
  }
});

// provide a demonstration in memory dataset
function localDataset() {
  var dataset = Fixture.getDataset();
  dataset.queryState.addFacet('country');
  return dataset;
}

<commit_msg>[app][xs]: micro tidy.<commit_after>jQuery(function($) {
  window.ReclineDataExplorer = new ExplorerApp({
    el: $('.recline-app')
  })
});

var ExplorerApp = Backbone.View.extend({
  events: {
    'submit form.js-import-url': '_onImportURL',
    'submit .js-import-dialog-file form': '_onImportFile'
  },

  initialize: function() {
    this.el = $(this.el);
    this.dataExplorer = null;
    this.explorerDiv = $('.data-explorer-here');
    _.bindAll(this, 'viewExplorer', 'viewHome');

    this.router = new Backbone.Router();
    this.router.route('', 'home', this.viewHome);
    this.router.route(/explorer/, 'explorer', this.viewExplorer);
    Backbone.history.start();

    var state = recline.Util.parseQueryString(decodeURIComponent(window.location.search));
    if (state) {
      _.each(state, function(value, key) {
        try {
          value = JSON.parse(value);
        } catch(e) {}
        state[key] = value;
      });
      if (state.embed) {
        $('.navbar').hide();
        $('body').attr('style', 'padding-top: 0px');
      }
    }
    var dataset = null;
    // special cases for demo / memory dataset
    if (state.url === 'demo' || state.backend === 'memory') {
      dataset = localDataset();
    }
    else if (state.dataset || state.url) {
      dataset = recline.Model.Dataset.restore(state);
    }
    if (dataset) {
      this.createExplorer(dataset, state);
    }
  },

  viewHome: function() {
    this.switchView('home');
  },

  viewExplorer: function() {
    this.router.navigate('explorer');
    this.switchView('explorer');
  },

  switchView: function(path) {
    $('.backbone-page').hide();
    var cssClass = path.replace('/', '-');
    $('.page-' + cssClass).show();
  },

  // make Explorer creation / initialization in a function so we can call it
  // again and again
  createExplorer: function(dataset, state) {
    var self = this;
    // remove existing data explorer view
    var reload = false;
    if (this.dataExplorer) {
      this.dataExplorer.remove();
      reload = true;
    }
    this.dataExplorer = null;
    var $el = $('
');
    $el.appendTo(this.explorerDiv);
    this.dataExplorer = new recline.View.DataExplorer({
      model: dataset,
      el: $el,
      state: state
    });
    this._setupPermaLink(this.dataExplorer);
    this._setupEmbed(this.dataExplorer);

    this.viewExplorer();
  },

  _setupPermaLink: function(explorer) {
    var self = this;
    var $viewLink = this.el.find('.js-share-and-embed-dialog .view-link');
    explorer.state.bind('change', function() {
      $viewLink.val(self.makePermaLink(explorer.state));
    });
    $viewLink.val(self.makePermaLink(explorer.state));
  },

  _setupEmbed: function(explorer) {
    var self = this;
    var $embedLink = this.el.find('.js-share-and-embed-dialog .view-embed');
    function makeEmbedLink(state) {
      var link = self.makePermaLink(state);
      link = link + '&embed=true';
      var out = $.mustache('', {link: link});
      return out;
    }
    explorer.state.bind('change', function() {
      $embedLink.val(makeEmbedLink(explorer.state));
    });
    $embedLink.val(makeEmbedLink(explorer.state));
  },

  makePermaLink: function(state) {
    var qs = recline.Util.composeQueryString(state.toJSON());
    return window.location.origin + window.location.pathname + qs;
  },

  // setup the loader menu in top bar
  setupLoader: function(callback) {
    // pre-populate webstore load form with an example url
    var demoUrl = 'http://thedatahub.org/api/data/b9aae52b-b082-4159-b46f-7bb9c158d013';
    $('form.js-import-url input[name="source"]').val(demoUrl);
  },

  _onImportURL: function(e) {
    e.preventDefault();
    $('.modal.js-import-dialog-url').modal('hide');
    var $form = $(e.target);
    var source = $form.find('input[name="source"]').val();
    var datasetInfo = {
      id: 'my-dataset',
      url: source,
      webstore_url: source
    };
    var type = $form.find('select[name="backend_type"]').val();
    if (type === 'csv' || type === 'excel') {
      datasetInfo.format = type;
      type = 'dataproxy';
    }
    var dataset = new recline.Model.Dataset(datasetInfo, type);
    this.createExplorer(dataset);
  },

  _onImportFile: function(e) {
    var self = this;
    e.preventDefault();
    var $form = $(e.target);
    $('.modal.js-import-dialog-file').modal('hide');
    var $file = $form.find('input[type="file"]')[0];
    var file = $file.files[0];
    var options = {
      separator : $form.find('input[name="separator"]').val(),
      delimiter : $form.find('input[name="delimiter"]').val(),
      encoding : $form.find('input[name="encoding"]').val()
    };
    recline.Backend.loadFromCSVFile(file, function(dataset) {
        self.createExplorer(dataset)
      },
      options
    );
  }
});

// provide a demonstration in memory dataset
function localDataset() {
  var dataset = Fixture.getDataset();
  dataset.queryState.addFacet('country');
  return dataset;
}

<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on filters, and services
angular.module('app', [
  'ngMockE2E'
]).controller('appCtrl', ['$scope', '$http', function($scope, $http) {

	$scope.version = angular.version;

	$scope.prettyPrint || ($scope.prettyPrint = false);

	$scope.request || ($scope.request = { method: '', url: '', headers: '', data: ''});

	var format = $scope.format = function (obj){
		return $scope.prettyPrint
			? JSON.stringify(obj, null, 2)
			: JSON.stringify(obj)
	};

	$scope.$watch('prettyPrint', function() {
		if($scope.response){
			$scope.response = {
				data: format($scope.rawResponse.data),
				status: $scope.response.status,
				headers: format($scope.rawResponse.headers)
			};
		}
	});

	$scope.call = function(){

		delete $scope.response;

		var request = angular.copy($scope.request);

		request.url = '/' + request.url;

		var headerRegex = /^\s*([^:\s]+)\s*:\s*(.*)\s*$/mg;
		request.headers = {};
		var header;
		while(header = headerRegex.exec(request.headers)){
			request.headers[header[1]] = header[2];
		}

		function recordResponse(data, status, headers) {

			headers = headers ? headers() : undefined;
			$scope.rawResponse = {
				data: data,
				headers: headers
			};

			$scope.response = {
				data: format(data),
				status: status,
				headers: format(headers)
			};
		}

		$http(request).success(recordResponse).error(recordResponse);
	};

}]).run(function($httpBackend) {

	//Must expose this so that it is accessible to remotely invoked javascript.
	window.$httpBackend = $httpBackend

    $httpBackend.whenGET('/test').respond(
    	200, {
    	msg: "You called /test",
    	args: null
    }, {'test-header': 'success'});

    $httpBackend.whenGET('/missing').respond(
    	404,
    	"You called /missing",
    	{'test-header': 'failed'});
});
<commit_msg>Updates app to make http calls upon app load given a correctly constructed query string.<commit_after>'use strict';

// Declare app level module which depends on filters, and services
angular.module('app', [
  'ngMockE2E'
]).value()
.controller('appCtrl', ['$scope', '$http', function($scope, $http) {

	$scope.version = angular.version;

	$scope.prettyPrint || ($scope.prettyPrint = false);

	$scope.request || ($scope.request = { method: '', url: '', headers: '', data: ''});

	var format = $scope.format = function (obj){
		return $scope.prettyPrint
			? JSON.stringify(obj, null, 2)
			: JSON.stringify(obj)
	};

	$scope.$watch('prettyPrint', function() {
		if($scope.response){
			$scope.response = {
				data: format($scope.rawResponse.data),
				status: $scope.response.status,
				headers: format($scope.rawResponse.headers)
			};
		}
	});

	if($scope.$root.initialRequest){
		$scope.request = angular.extend($scope.request, $scope.$root.initialRequest.request);
		$scope.$root.$watch('initialRequest.response', function(){
			var response = $scope.$root.initialRequest.response;
			if(response){
				recordResponse(response.data, response.status, response.headers);
			}
		});
	}

	$scope.call = function(){

		delete $scope.response;

		var request = angular.copy($scope.request);

		request.url = '/' + request.url;

		var headerRegex = /^\s*([^:\s]+)\s*:\s*(.*)\s*$/mg;
		request.headers = {};
		var header;
		while(header = headerRegex.exec(request.headers)){
			request.headers[header[1]] = header[2];
		}

		$http(request).success(recordResponse).error(recordResponse);
	};

	function recordResponse(data, status, headers) {

		headers = headers ? headers() : undefined;
		$scope.rawResponse = {
			data: data,
			headers: headers
		};

		$scope.response = {
			data: format(data),
			status: status,
			headers: format(headers)
		};
	}

}]).run(function($httpBackend, $window, $rootScope, $http) {

	//Must expose this so that it is accessible to remotely invoked javascript.
	window.$httpBackend = $httpBackend

    $httpBackend.whenGET('/test').respond(
    	200, {
    	msg: "You called /test",
    	args: null
    }, {'test-header': 'success'});

    $httpBackend.whenGET('/missing').respond(
    	404,
    	"You called /missing",
    	{'test-header': 'failed'});

	if($window.location.search.length > 1){
		var request;
		try{
			request = JSON.parse(decodeURI($window.location.search.substring(1)));
		} catch (ex) {
			console.log(ex);
		}

		if(request){
			$rootScope.initialRequest = { request: request };

			$http(request).success(function(data, status, headers){
				$rootScope.initialRequest.response = {
					data: data,
					status: status,
					headers: headers
				};
			}).error(function(data, status, headers){
				$rootScope.initialRequest.response = {
					data: data,
					status: status,
					headers: headers
				};
			});
		}
	}
});
<|endoftext|>


<commit_before>// import $ from 'jquery';
// var $ = require('jquery');
// require("pjax");

const app = {};
app.model = {};
app.view = {};
app.ctrl = {};
app.data = {};
app.data.result = {};
app.data.isShowingResult = false;

app.data.activeDetailId = null;
app.data.backTo = "result";
app.data.favIds = [];
app.mock = {};
app.mock.weitingTime = 3000;

// app.data.checkLogin = () => {
//   app.data.isLoggedIn = false;
//   return false;
// }

$(function(){
  /*
  * jQueryオブジェクトキャッシュ
  */
  var
  $page = $(".page"),
  $pageIndex = $(".page--index"),
  $pageResult = $(".page--result"),
  $pageCollection = $(".page--collection"),
  $pageDetail = $(".page--detail");

  /*
  * (1)通信
  */
  app.model.login = (param1) => {
    app.view.topLoading();
    FB.login(function(response) {
      if (response.authResponse) {
        AWS.config.region = 'ap-northeast-1';
        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
          IdentityPoolId: 'ap-northeast-1:0f6f04d8-73c8-486a-8e31-8eaea50ee3a2',
          Logins: {
            'graph.facebook.com': response.authResponse.accessToken
          }
        });

        console.log('You are now logged in.');

        // AWS.config.credentials.get(function() {
        //   var client = new AWS.CognitoSyncManager({log: function(e) {
        //     console.log(e);
        //   }});
        //   client.openOrCreateDataset('userProfile', function(err, dataset) {
        //     if (err) {
        //       console.error(err);
        //     }
        //     dataset.put('fbToken', response.authResponse.accessToken, function(err, record) {
        //       if ( !err ) {
        //         dataset.synchronize({
        //           onSuccess: function(dataset, newRecords) {
        //             console.log("Data saved successfully.");
        //           },
        //           onFailure: function(err) {
        //             console.error(err);
        //             console.log("Error occured.");
        //           },
        //           onConflict: function(dataset, conflicts, callback) {
        //             var resolved = [];
        //             console.log(conflicts);
        //             for (var i=0; i < conflicts.length; i++) {
        //               resolved.push(conflicts[i].resolveWithRemoteRecord());
        //             }
        //             dataset.resolve(resolved, function(err) {
        //               if (err) {
        //                 console.error(err);
        //               }
        //               callback(true);
        //             });
        //           },
        //           onDatasetDeleted: function(dataset, datasetName, callback) {
        //             return callback(true);
        //           },
        //           onDatasetMerged: function(dataset, datasetNames, callback) {
        //             return callback(false);
        //           }
        //         });
        //       }
        //     });
        //   });
        // });
        var cognitoidentity = new AWS.CognitoIdentity();
        cognitoidentity.getId({
          IdentityPoolId: 'ap-northeast-1:0f6f04d8-73c8-486a-8e31-8eaea50ee3a2',
          Logins: {
            'graph.facebook.com': response.authResponse.accessToken
          }
        }, function(err, data) {
          if (err) {
            console.error(err);
          }
          cognitoidentity.getCredentialsForIdentity({
            IdentityId: data.IdentityId,
            Logins: {
              'graph.facebook.com': response.authResponse.accessToken
            }
          }, function(err, data) {
            if (err) {
              console.error(err);
            }

            AWS.config.update({
              accessKeyId: data.Credentials.AccessKeyId,
              secretAccessKey: data.Credentials.SecretKey,
              sessionToken: data.Credentials.SessionToken,
              region: 'ap-northeast-1'
            });

            var lambda = new AWS.Lambda();

            lambda.invoke({
              FunctionName: "TCHackaThon2015Analyze",
              InvocationType: "RequestResponse",
              Payload: JSON.stringify({fbToken: response.authResponse.accessToken})
            }, function(err, result) {
              if(err) {
                console.error(err);
              }
              app.data.result = JSON.parse(result.Payload);
              app.view.writeResult();
            });
          });
        });

      } else {
        console.error('There was a problem logging you in.');
      }
    }, {scope: 'user_posts'});
  }

  /*
  * 描画: 結果取得
  */
  app.view.topLoading = () => {
    $(".img--topLogo").addClass("loading");
    $(".img--topLogo__heart").attr('class', function(index, classNames) {
      return classNames + ' loading';
    });
    $(".title--main").addClass("fadeOut");
    $(".text--top").addClass("fadeOut");
    $(".btn--facebook").addClass("fadeOut");
    $(".text--alreadyLogin__wrap").addClass("fadeOut");
  }

  app.view.writeResult = () => {
    console.log(app.data.result);
    console.log("write");
    for (var i=0; i<app.data.result.length; i++) {
      var data = app.data.result[i];
      // $("#result").append("
"+ data.id + "
");
      var html = "
";
      html += "";
      // html += "
"+ data.matched + "
";
      html += "<divclass='profile__name'>"+ data.name + "(" + data.age+ ")
";
      html += "
"+ data.job + "
";
      html += "

"
      $("#result").append(html);
    }
    app.view.changePage($pageIndex, $pageResult, "result");

  }

  /*
  * 描画: ページ遷移
  */
  app.view.changePage = (prev, next, uri) => {
    history.pushState({}, uri);
    console.log(prev);
    $page.removeClass("page--show");
    next.addClass("page--show");
  }

  app.view.setDetail = (targetUser) => {
    $(".detail__img").attr("src",targetUser.image);
    $(".detail__name").text(targetUser.name + "(" + targetUser.age + ")");
    $(".detail__job").text(targetUser.job);
    $(".js--d--match").text(targetUser.matched);
    $(".detail__type").text("聞き上手で頑張り屋さん。本当はちょっと冒険してみたい…");
    app.data.activeDetailId = targetUser.id;
    app.view.changePage({}, $pageDetail);
  }

  app.view.setCollection = () => {
    for(var i=0; i < app.data.result.length; i ++){
      if(app.data.favIds.indexOf(app.data.result[i].id) !== -1){
        var data = app.data.result[i];
        // $("#result").append("
"+ data.id + "
");
        var html = "
";
        html += "";
        // html += "
"+ data.matched + "
";
        html += "
"+ data.name + "(" + data.age+ ")
";
        html += "
"+ data.job + "
";
        html += "

"
        $("#collection").append(html);
      }
    }

  }

  /*
  * (3)DOM Event
  */
  $(".js--submit").on("click", () => {
    app.model.login();
    // app.model.loginMock();
  });

  $(".js--btn--collection").on("click", (e) => {
    // app.model.login();
    e.preventDefault();
    app.data.backTo = "collection";
    app.view.setCollection();
    app.view.changePage($pageResult,$pageCollection,"collection");
  });
  $(".js--btn--result").on("click", (e) => {
    // app.model.login();
    e.preventDefault();
    app.data.backTo = "result";
    app.view.changePage($pageCollection,$pageResult,"result");
  });
  $(".js--btn--detailBack").on("click",function(e){
    e.preventDefault();
    if(app.data.backTo === "collection"){
      app.view.changePage($pageResult,$pageCollection,"collection");
    }else{
      app.view.changePage($pageCollection,$pageResult,"result");
    }
  });
  $(".js--btn--like").on("click",function(e){
    e.preventDefault();
    // console.log($(this).data("id"));
    if(app.data.favIds.indexOf(app.data.activeDetailId) !== -1){
      app.data.favIds.some(function(v, i){
         if (v==app.data.activeDetailId) app.data.favIds.splice(i,1);
      });
      $(".btn--like").removeClass("on");
    }else{
      app.data.favIds.push(app.data.activeDetailId);
      $(".btn--like").addClass("on");
    }
    console.log(app.data.favIds);
  });
  $(document).on("click",".js--btn--detail" ,function(e){
    var that = this;
    e.preventDefault();
    var userId = parseInt($(this).data("id"));
    var targetUser = {};
    for(var i=0; i < app.data.result.length; i++){
      if(parseInt(app.data.result[i].id) === userId){
        targetUser = app.data.result[i];
        break;
      }
    }

    console.log(targetUser);
    app.view.setDetail(targetUser);
  })
  /*
  * (4)Pjax
  */

});
<commit_msg>fix: divのくずれ<commit_after>// import $ from 'jquery';
// var $ = require('jquery');
// require("pjax");

const app = {};
app.model = {};
app.view = {};
app.ctrl = {};
app.data = {};
app.data.result = {};
app.data.isShowingResult = false;

app.data.activeDetailId = null;
app.data.backTo = "result";
app.data.favIds = [];
app.mock = {};
app.mock.weitingTime = 3000;

// app.data.checkLogin = () => {
//   app.data.isLoggedIn = false;
//   return false;
// }

$(function(){
  /*
  * jQueryオブジェクトキャッシュ
  */
  var
  $page = $(".page"),
  $pageIndex = $(".page--index"),
  $pageResult = $(".page--result"),
  $pageCollection = $(".page--collection"),
  $pageDetail = $(".page--detail");

  /*
  * (1)通信
  */
  app.model.login = (param1) => {
    app.view.topLoading();
    FB.login(function(response) {
      if (response.authResponse) {
        AWS.config.region = 'ap-northeast-1';
        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
          IdentityPoolId: 'ap-northeast-1:0f6f04d8-73c8-486a-8e31-8eaea50ee3a2',
          Logins: {
            'graph.facebook.com': response.authResponse.accessToken
          }
        });

        console.log('You are now logged in.');

        // AWS.config.credentials.get(function() {
        //   var client = new AWS.CognitoSyncManager({log: function(e) {
        //     console.log(e);
        //   }});
        //   client.openOrCreateDataset('userProfile', function(err, dataset) {
        //     if (err) {
        //       console.error(err);
        //     }
        //     dataset.put('fbToken', response.authResponse.accessToken, function(err, record) {
        //       if ( !err ) {
        //         dataset.synchronize({
        //           onSuccess: function(dataset, newRecords) {
        //             console.log("Data saved successfully.");
        //           },
        //           onFailure: function(err) {
        //             console.error(err);
        //             console.log("Error occured.");
        //           },
        //           onConflict: function(dataset, conflicts, callback) {
        //             var resolved = [];
        //             console.log(conflicts);
        //             for (var i=0; i < conflicts.length; i++) {
        //               resolved.push(conflicts[i].resolveWithRemoteRecord());
        //             }
        //             dataset.resolve(resolved, function(err) {
        //               if (err) {
        //                 console.error(err);
        //               }
        //               callback(true);
        //             });
        //           },
        //           onDatasetDeleted: function(dataset, datasetName, callback) {
        //             return callback(true);
        //           },
        //           onDatasetMerged: function(dataset, datasetNames, callback) {
        //             return callback(false);
        //           }
        //         });
        //       }
        //     });
        //   });
        // });
        var cognitoidentity = new AWS.CognitoIdentity();
        cognitoidentity.getId({
          IdentityPoolId: 'ap-northeast-1:0f6f04d8-73c8-486a-8e31-8eaea50ee3a2',
          Logins: {
            'graph.facebook.com': response.authResponse.accessToken
          }
        }, function(err, data) {
          if (err) {
            console.error(err);
          }
          cognitoidentity.getCredentialsForIdentity({
            IdentityId: data.IdentityId,
            Logins: {
              'graph.facebook.com': response.authResponse.accessToken
            }
          }, function(err, data) {
            if (err) {
              console.error(err);
            }

            AWS.config.update({
              accessKeyId: data.Credentials.AccessKeyId,
              secretAccessKey: data.Credentials.SecretKey,
              sessionToken: data.Credentials.SessionToken,
              region: 'ap-northeast-1'
            });

            var lambda = new AWS.Lambda();

            lambda.invoke({
              FunctionName: "TCHackaThon2015Analyze",
              InvocationType: "RequestResponse",
              Payload: JSON.stringify({fbToken: response.authResponse.accessToken})
            }, function(err, result) {
              if(err) {
                console.error(err);
              }
              app.data.result = JSON.parse(result.Payload);
              app.view.writeResult();
            });
          });
        });

      } else {
        console.error('There was a problem logging you in.');
      }
    }, {scope: 'user_posts'});
  }

    app.model.loginMock = (param1) => {
      //pram1 = bears
      app.view.topLoading();
      setTimeout(()=>{
        var url = "/stub/dummy.json";
        $.ajax({
          url: url,
          type: "GET",
          dataType: "json",
          cache: false,
          success: function success(msg) {
            app.data.result = msg;
            app.view.writeResult();
         }
       });
     })
   }

  /*
  * 描画: 結果取得
  */
  app.view.topLoading = () => {
    $(".img--topLogo").addClass("loading");
    $(".img--topLogo__heart").attr('class', function(index, classNames) {
      return classNames + ' loading';
    });
    $(".title--main").addClass("fadeOut");
    $(".text--top").addClass("fadeOut");
    $(".btn--facebook").addClass("fadeOut");
    $(".text--alreadyLogin__wrap").addClass("fadeOut");
  }

  app.view.writeResult = () => {
    console.log(app.data.result);
    console.log("write");
    for (var i=0; i<app.data.result.length; i++) {
      var data = app.data.result[i];
      // $("#result").append("
"+ data.id + "
");
      var html = "
";
      html += "";
      // html += "
"+ data.matched + "
";
      html += "
"+ data.name + "(" + data.age+ ")
";
      html += "
"+ data.job + "
";
      html += "

"
      $("#result").append(html);
    }
    app.view.changePage($pageIndex, $pageResult, "result");

  }

  /*
  * 描画: ページ遷移
  */
  app.view.changePage = (prev, next, uri) => {
    history.pushState({}, uri);
    console.log(prev);
    $page.removeClass("page--show");
    next.addClass("page--show");
  }

  app.view.setDetail = (targetUser) => {
    $(".detail__img").attr("src",targetUser.image);
    $(".detail__name").text(targetUser.name + "(" + targetUser.age + ")");
    $(".detail__job").text(targetUser.job);
    $(".js--d--match").text(targetUser.matched);
    $(".detail__type").text("聞き上手で頑張り屋さん。本当はちょっと冒険してみたい…");
    app.data.activeDetailId = targetUser.id;
    app.view.changePage({}, $pageDetail);
  }

  app.view.setCollection = () => {
    for(var i=0; i < app.data.result.length; i ++){
      if(app.data.favIds.indexOf(app.data.result[i].id) !== -1){
        var data = app.data.result[i];
        // $("#result").append("
"+ data.id + "
");
        var html = "
";
        html += "";
        // html += "
"+ data.matched + "
";
        html += "
"+ data.name + "(" + data.age+ ")
";
        html += "
"+ data.job + "
";
        html += "
"
        $("#collection").append(html);
      }
    }

  }

  /*
  * (3)DOM Event
  */
  $(".js--submit").on("click", () => {
    app.model.login();
    // app.model.loginMock();
  });

  $(".js--btn--collection").on("click", (e) => {
    // app.model.login();
    e.preventDefault();
    app.data.backTo = "collection";
    app.view.setCollection();
    app.view.changePage($pageResult,$pageCollection,"collection");
  });
  $(".js--btn--result").on("click", (e) => {
    // app.model.login();
    e.preventDefault();
    app.data.backTo = "result";
    app.view.changePage($pageCollection,$pageResult,"result");
  });
  $(".js--btn--detailBack").on("click",function(e){
    e.preventDefault();
    if(app.data.backTo === "collection"){
      app.view.changePage($pageResult,$pageCollection,"collection");
    }else{
      app.view.changePage($pageCollection,$pageResult,"result");
    }
  });
  $(".js--btn--like").on("click",function(e){
    e.preventDefault();
    // console.log($(this).data("id"));
    if(app.data.favIds.indexOf(app.data.activeDetailId) !== -1){
      app.data.favIds.some(function(v, i){
         if (v==app.data.activeDetailId) app.data.favIds.splice(i,1);
      });
      $(".btn--like").removeClass("on");
    }else{
      app.data.favIds.push(app.data.activeDetailId);
      $(".btn--like").addClass("on");
    }
    console.log(app.data.favIds);
  });
  $(document).on("click",".js--btn--detail" ,function(e){
    var that = this;
    e.preventDefault();
    var userId = parseInt($(this).data("id"));
    var targetUser = {};
    for(var i=0; i < app.data.result.length; i++){
      if(parseInt(app.data.result[i].id) === userId){
        targetUser = app.data.result[i];
        break;
      }
    }

    console.log(targetUser);
    app.view.setDetail(targetUser);
  })
  /*
  * (4)Pjax
  */

});
<|endoftext|>