<commit_before>'use strict'

const bodyParser = require('koa-bodyparser');
const route = require('koa-route');

module.exports = (config, app) => {

  // TODO: Remove relative path when questionnaire-core is published to npmjs.org
  const core = require('../../questionnaire-core/src/interface.js')(config.dbUrl,config.usedDatabase);

  // API METHODS

  async function getQuestionnaires(ctx) {
    let responseFromCore = await core.getQuestionnaires();
    ctx.body = responseFromCore;
  }

  async function putQuestionnaire(ctx){
    let payload = ctx.request.body;
    let responseFromCore = await core.putQuestionnaire(payload);
    ctx.body = responseFromCore;
  }

  async function deleteQuestionnaire(ctx,uuid){
    let responseFromCore = await core.deleteQuestionnaire(uuid);
    ctx.body = responseFromCore;
  }

  async function getQuestionnaire(ctx,uuid){
    let responseFromCore = await core.getQuestionnaire(uuid);
    ctx.body = responseFromCore;
  }

  async function deployQuestionnaire(ctx,uuid){
    let responseFromCore = await core.deployQuestionnaire(uuid);
    ctx.body = responseFromCore;
  }

  async function closeQuestionnaire(ctx,uuid){
    let responseFromCore = await core.closeQuestionnaire(uuid);
    ctx.body = responseFromCore;
  }

  async function updateQuestionnaire(ctx,uuid){
  	let payload = ctx.request.body;
    let responseFromCore = await core.updateQuestionnaire(uuid,payload);
    ctx.body = responseFromCore;
  }

  async function getQuestions(ctx,path){
  	let lang = this.query.lang;
    let responseFromCore = await core.getQuestions(path,lang);
    ctx.body = responseFromCore;
  }

  // ROUTES

  app.use(bodyParser());
  app.use(route.get('/questionnaires', getQuestionnaires));
  app.use(route.put('/questionnaire', putQuestionnaire));
  app.use(route.delete('/questionnaire/:uuid', deleteQuestionnaire));
  app.use(route.get('/questionnaire/:uuid', getQuestionnaire));
  app.use(route.post('/questionnaire/:uuid/deploy', deployQuestionnaire));
  app.use(route.post('/questionnaire/:uuid/close', closeQuestionnaire));
  app.use(route.put('/questionnaire/:uuid', updateQuestionnaire));
  app.use(route.get('/questions/:path',getQuestions));
}
<commit_msg>Change to api.js routing<commit_after>'use strict'

const bodyParser = require('koa-bodyparser');
const route = require('koa-route');

module.exports = (config, app) => {

  // TODO: Remove relative path when questionnaire-core is published to npmjs.org
  const core = require('../../questionnaire-core/src/interface.js')(config.dbUrl,config.usedDatabase);

  // API METHODS

  async function getQuestionnaires(ctx) {
    let responseFromCore = await core.getQuestionnaires();
    ctx.body = responseFromCore;
  }

  async function putQuestionnaire(ctx){
    let payload = ctx.request.body;
    let responseFromCore = await core.putQuestionnaire(payload);
    ctx.body = responseFromCore;
  }

  async function deleteQuestionnaire(ctx,uuid){
    let responseFromCore = await core.deleteQuestionnaire(uuid);
    ctx.body = responseFromCore;
  }

  async function getQuestionnaire(ctx,uuid){
    let responseFromCore = await core.getQuestionnaire(uuid);
    ctx.body = responseFromCore;
  }

  async function deployQuestionnaire(ctx,uuid){
    let responseFromCore = await core.deployQuestionnaire(uuid);
    ctx.body = responseFromCore;
  }

  async function closeQuestionnaire(ctx,uuid){
    let responseFromCore = await core.closeQuestionnaire(uuid);
    ctx.body = responseFromCore;
  }

  async function updateQuestionnaire(ctx,uuid){
  	let payload = ctx.request.body;
    let responseFromCore = await core.updateQuestionnaire(uuid,payload);
    ctx.body = responseFromCore;
  }

  async function getQuestions(ctx,path){
  	let lang = this.query.lang;
    let responseFromCore = await core.getQuestions(path,lang);
    ctx.body = responseFromCore;
  }

  // ROUTES

  app.use(bodyParser());
  app.use(route.get('/v1/questionnaires', getQuestionnaires));
  app.use(route.put('/v1/questionnaires', putQuestionnaire));
  app.use(route.delete('/v1/questionnaires/:uuid', deleteQuestionnaire));
  app.use(route.get('/v1/questionnaires/:uuid', getQuestionnaire));
  app.use(route.post('/v1/questionnaires/:uuid/deploy', deployQuestionnaire));
  app.use(route.post('/v1/questionnaires/:uuid/close', closeQuestionnaire));
  app.use(route.put('/v1/questionnaires/:uuid', updateQuestionnaire));
  app.use(route.get('/v1/questions/:path',getQuestions));
}
<|endoftext|>


<commit_before>'use strict';

var del = require('del');
var gulp = require('gulp');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var rename = require('gulp-rename');
var browserify = require('browserify');
var through2 = require('through2');
var mocha = require('gulp-mocha');
var compass = require('gulp-compass');
var autoprefixer = require('gulp-autoprefixer');
var jshint = require('gulp-jshint');
// var uglify = require('gulp-uglify');
var karma = require('karma');
var protractor = require('gulp-protractor').protractor;
var webdriver = require('gulp-protractor').webdriver;
var webdriverUpdate = require('gulp-protractor').webdriver_update;

var paths = {
    api: {
        tests: ['api/**/test/*.js'],
        all: ['app.js', 'api/**/*.js']
    }
};

/*
    Api tasks
*/
gulp.task('mocha', function () {
    return gulp.src(paths.api.tests, {read: false})
        .pipe(mocha({reporter: 'spec'}))
        .on('end', function () {
            gutil.log('\n\n***** Mocha Tests Complete *****\n\n\n\n');
        });
});

gulp.task('lint-api', function() {
    return gulp.src(['app.js', './api/**/*.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('api-tests', function () {
    gulp.watch(paths.api.all, ['mocha']);
});

/*
    Client tasks
*/
gulp.task('browserify', function () {
    gulp.src(['./client/main.js'])
        .pipe(through2.obj(function (file, enc, next) {
            browserify(file.path)
                .bundle(function (err, res) {
                    file.contents = res;
                    next(null, file);
                });
        }))
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(rename('bundle.js'))
        // .pipe(uglify())
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./public'));
});

gulp.task('views', function () {
    gulp.src('client/index.html')
        .pipe(gulp.dest('public/'));

    gulp.src('client/ToDo/*.html')
        .pipe(gulp.dest('public/ToDo/'));
});

gulp.task('compass', function () {
    gulp.src('client/sass/*.scss')
        .pipe(compass({
            http_path: '/',
            project: __dirname + '/client',
            css: '../public/css',
            sass: 'sass',
            image: 'images',
            font: 'css'
        }))
        .pipe(autoprefixer({
            browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1'],
            cascade: false
        }))
        // .pipe(minifyCSS())
        .pipe(gulp.dest('public/css'));
});

gulp.task('images', function () {
    gulp.src('client/images/**/*')
        .pipe(gulp.dest('public/images/'));
});

gulp.task('lint-client', function () {
    gulp.src(['client/**/*.js', '!client/test/*.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('webdriver-update', webdriverUpdate);
gulp.task('webdriver', webdriver);

gulp.task('protractor', ['webdriver-update', 'webdriver'], function () {
    return gulp.src('client/**/test/*.e2e.js')
        .pipe(protractor({
            configFile: './protractor.conf.js',
            args: ['--baseUrl', 'http://127.0.0.1:3000']
        }))
        .on('error', function(err) {
            console.error(err);
        })
        .on('end', function () {
            gutil.log('\n\n***** Protractor Tests Complete *****\n\n\n\n');
        });
});

gulp.task('karma', function () {
    karma.server.start({
        configFile: __dirname + '/karma.conf.js'
    });
});

/*
    Build
*/

gulp.task('clean', function (cb) {
    del(['public/**/*'], cb);
});

gulp.task('build', ['clean', 'browserify', 'views', 'compass'], function () {
    gutil.log('*** Run with: $ npm start ***');
});

/*
    Watchers
*/
gulp.task('unit-tests', function () {
    gulp.watch(paths.api.tests, ['mocha']);
});

gulp.task('dev', function () {
    // gulp.watch(['app.js', 'api/**/*.js'], ['lint-api']);
    gulp.watch(paths.api.all, ['mocha']);
    gulp.watch(['client/**/*.js', '!client/test/*.js'], ['browserify', 'protractor']);
    gulp.watch(['client/**/*.html'], ['views']);
    gulp.watch(['client/sass/*.scss'], ['compass']);

    karma.server.start({
        configFile: __dirname + '/karma.conf.js'
    });
});
<commit_msg>added minifyCss and sourcemaps to compass task<commit_after>'use strict';

var del = require('del');
var gulp = require('gulp');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var rename = require('gulp-rename');
var browserify = require('browserify');
var through2 = require('through2');
var mocha = require('gulp-mocha');
var compass = require('gulp-compass');
var minifyCss = require('gulp-minify-css');
var autoprefixer = require('gulp-autoprefixer');
var jshint = require('gulp-jshint');
// var uglify = require('gulp-uglify');
var karma = require('karma');
var protractor = require('gulp-protractor').protractor;
var webdriver = require('gulp-protractor').webdriver;
var webdriverUpdate = require('gulp-protractor').webdriver_update;

var paths = {
    api: {
        tests: ['api/**/test/*.js'],
        all: ['app.js', 'api/**/*.js']
    }
};

/*
    Api tasks
*/
gulp.task('mocha', function () {
    return gulp.src(paths.api.tests, {read: false})
        .pipe(mocha({reporter: 'spec'}))
        .on('end', function () {
            gutil.log('\n\n***** Mocha Tests Complete *****\n\n\n\n');
        });
});

gulp.task('lint-api', function() {
    return gulp.src(['app.js', './api/**/*.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('api-tests', function () {
    gulp.watch(paths.api.all, ['mocha']);
});

/*
    Client tasks
*/
gulp.task('browserify', function () {
    gulp.src(['./client/main.js'])
        .pipe(through2.obj(function (file, enc, next) {
            browserify(file.path)
                .bundle(function (err, res) {
                    file.contents = res;
                    next(null, file);
                });
        }))
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(rename('bundle.js'))
        // .pipe(uglify())
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./public'));
});

gulp.task('views', function () {
    gulp.src('client/index.html')
        .pipe(gulp.dest('public/'));

    gulp.src('client/ToDo/*.html')
        .pipe(gulp.dest('public/ToDo/'));
});

gulp.task('compass', function () {
    gulp.src('client/sass/*.scss')
        .pipe(compass({
            http_path: '/',
            project: __dirname + '/client',
            css: '../public/css',
            sass: 'sass',
            image: 'images',
            font: 'css'
        }))
        .pipe(autoprefixer({
            browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1'],
            cascade: false
        }))
        .pipe(sourcemaps.init())
        .pipe(minifyCss())
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('public/css'));
});

gulp.task('images', function () {
    gulp.src('client/images/**/*')
        .pipe(gulp.dest('public/images/'));
});

gulp.task('lint-client', function () {
    gulp.src(['client/**/*.js', '!client/test/*.js'])
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('webdriver-update', webdriverUpdate);
gulp.task('webdriver', webdriver);

gulp.task('protractor', ['webdriver-update', 'webdriver'], function () {
    return gulp.src('client/**/test/*.e2e.js')
        .pipe(protractor({
            configFile: './protractor.conf.js',
            args: ['--baseUrl', 'http://127.0.0.1:3000']
        }))
        .on('error', function(err) {
            console.error(err);
        })
        .on('end', function () {
            gutil.log('\n\n***** Protractor Tests Complete *****\n\n\n\n');
        });
});

gulp.task('karma', function () {
    karma.server.start({
        configFile: __dirname + '/karma.conf.js'
    });
});

/*
    Build
*/

gulp.task('clean', function (cb) {
    del(['public/**/*'], cb);
});

gulp.task('build', ['clean', 'browserify', 'views', 'compass'], function () {
    gutil.log('*** Run with: $ npm start ***');
});

/*
    Watchers
*/
gulp.task('unit-tests', function () {
    gulp.watch(paths.api.tests, ['mocha']);
});

gulp.task('dev', function () {
    // gulp.watch(['app.js', 'api/**/*.js'], ['lint-api']);
    gulp.watch(paths.api.all, ['mocha']);
    gulp.watch(['client/**/*.js', '!client/test/*.js'], ['browserify', 'protractor']);
    gulp.watch(['client/**/*.html'], ['views']);
    gulp.watch(['client/sass/*.scss'], ['compass']);

    karma.server.start({
        configFile: __dirname + '/karma.conf.js'
    });
});
<|endoftext|>


<commit_before>"use strict";

var selectStyle = {

  style: {
    padding: 10,
    position: 'relative',
    borderBottom: '1px #ccc solid',
    boxSizing: 'border-box'
  },

  focusedStyle: {
    padding: 10,
    position: 'relative',
    borderBottom: '1px #53C7F2 solid',
    boxSizing: 'border-box',
  },

  hoverStyle: {
    padding: 10,
    position: 'relative',
    borderBottom: '1px #92D6EF solid',
    boxSizing: 'border-box'
  },

  wrapperStyle: {
    position: 'relative'
  },

  optionsAreaStyle: {
    display: 'block',
    listStyleType: 'none',
    background: '#FFF',
    padding: 0,
    margin: 0,
    position: 'absolute',
    width: '100%',
    zIndex: 10000,
    boxSizing: 'border-box'
  },

  nativeSelectStyle: {
    border: 0,
    clip: "rect(0 0 0 0)",
    height: 1,
    margin: -1,
    overflow: "hidden",
    padding: 0,
    position: "absolute",
    width: 1
  },

  caretDownStyle: {
    height: 0,
    width: 0,
    content: ' ',
    position: 'absolute',
    top: 20,
    right: 10,
    borderTop: '6px solid #666',
    borderLeft: '5px solid transparent',
    borderRight: '5px solid transparent'
  },

  caretUpStyle: {
    height: 0,
    width: 0,
    content: ' ',
    position: 'absolute',
    top: 20,
    right: 10,
    borderBottom: '6px solid #666',
    borderLeft: '5px solid transparent',
    borderRight: '5px solid transparent'
  },

  entryStyle: {
    padding: 10
  },

  entryHoverStyle: {
    padding: 10,
    background: '#DDD'
  }

};

export default selectStyle;
<commit_msg>style(Select): improve entry styling<commit_after>"use strict";

var selectStyle = {

  style: {
    padding: 10,
    position: 'relative',
    borderBottom: '1px #ccc solid',
    boxSizing: 'border-box'
  },

  focusedStyle: {
    padding: 10,
    position: 'relative',
    borderBottom: '1px #53C7F2 solid',
    boxSizing: 'border-box',
  },

  hoverStyle: {
    padding: 10,
    position: 'relative',
    borderBottom: '1px #92D6EF solid',
    boxSizing: 'border-box'
  },

  wrapperStyle: {
    position: 'relative'
  },

  optionsAreaStyle: {
    display: 'block',
    listStyleType: 'none',
    background: '#FFF',
    padding: 0,
    margin: 0,
    position: 'absolute',
    width: '100%',
    zIndex: 10000,
    boxSizing: 'border-box',
    borderRadius: 2,
    boxShadow: '0 1px 1px rgba(0, 0, 0, 0.2)',
    borderTop: '1px solid #f2f2f2',
    top: 0
  },

  nativeSelectStyle: {
    border: 0,
    clip: "rect(0 0 0 0)",
    height: 1,
    margin: -1,
    overflow: "hidden",
    padding: 0,
    position: "absolute",
    width: 1
  },

  caretDownStyle: {
    height: 0,
    width: 0,
    content: ' ',
    position: 'absolute',
    top: 20,
    right: 10,
    borderTop: '6px solid #666',
    borderLeft: '5px solid transparent',
    borderRight: '5px solid transparent'
  },

  caretUpStyle: {
    height: 0,
    width: 0,
    content: ' ',
    position: 'absolute',
    top: 20,
    right: 10,
    borderBottom: '6px solid #666',
    borderLeft: '5px solid transparent',
    borderRight: '5px solid transparent'
  },

  entryStyle: {
    padding: 10,
    color: '#666'
  },

  entryHoverStyle: {
    padding: 10,
    background: '#F5F5F5',
    color: '#666'
  }

};

export default selectStyle;
<|endoftext|>


<commit_before>
$(document).ready( function() {
   var roadcrew = new Roadcrew();

   roadcrew.intercept('#tablePage', function(dispatch) {
      alert("OK" + dispatch.target);
      dispatch();
   });

   var submit = $('#myform').find('[name="submit"]');
   submit.click(function(event) {
      event.preventDefault();
      roadcrew.goto("#tablePage");
   });

});<commit_msg>showing a loading page<commit_after>
$(document).ready( function() {
   var roadcrew = new Roadcrew();

   roadcrew.intercept('#tablePage', function(dispatch) {
      roadcrew.flip('#loadingPage');
      console.log("Heading to: " + dispatch.target);
      setTimeout(dispatch,3000);
   });

   var submit = $('#myform').find('[name="submit"]');
   submit.click(function(event) {
      event.preventDefault();
      roadcrew.goto("#tablePage");
   });
});<|endoftext|>


<commit_before>process.env.NODE_ENV = 'test';

var fs = require('fs');
var assert = require('assert');
var MBTiles = require('..');

var fixtureDir = __dirname + '/fixtures/output';

// Recreate output directory to remove previous tests.
try { fs.unlinkSync(fixtureDir + '/write_2.mbtiles'); } catch(err) {}
try { fs.mkdirSync(fixtureDir, 0755); } catch(err) {}

exports['test mbtiles file creation'] = function(beforeExit) {
    var completed = { written: 0, read: 0 };
    new MBTiles(fixtureDir + '/write_2.mbtiles', function(err, mbtiles) {
        completed.open = true;
        if (err) throw err;

        mbtiles.startWriting(function(err) {
            completed.started = true;
            if (err) throw err;

            fs.readdirSync(__dirname + '/fixtures/grids/').forEach(insertGrid);
        });

        function insertGrid(file) {
            var coords = file.match(/^plain_2_(\d+)_(\d+)_(\d+).json$/);
            if (!coords) return;

            // Flip Y coordinate because file names are TMS, but .putGrid() expects XYZ.
            coords[2] = Math.pow(2, coords[3]) - 1 - coords[2];

            fs.readFile(__dirname + '/fixtures/grids/' + file, 'utf8', function(err, grid) {
                if (err) throw err;

                mbtiles.putGrid(coords[3] | 0, coords[1] | 0, coords[2] | 0, JSON.parse(grid), function(err) {
                    if (err) throw err;
                    completed.written++;
                    if (completed.written === 241) {
                        mbtiles.stopWriting(function(err) {
                            completed.stopped = true;
                            if (err) throw err;
                            verifyWritten();
                        });
                    }
                });
            });
        }

        function verifyWritten() {
            fs.readdirSync(__dirname + '/fixtures/grids/').forEach(function(file) {
                var coords = file.match(/^plain_2_(\d+)_(\d+)_(\d+).json$/);
                if (coords) {
                    // Flip Y coordinate because file names are TMS, but .getTile() expects XYZ.
                    coords[2] = Math.pow(2, coords[3]) - 1 - coords[2];
                    mbtiles.getGrid(coords[3] | 0, coords[1] | 0, coords[2] | 0, function(err, grid) {
                        if (err) throw err;
                        assert.deepEqual(JSON.stringify(grid), fs.readFileSync(__dirname + '/fixtures/grids/' + file, 'utf8'));
                        completed.read++;
                    });
                }
            });
        }
    });

    beforeExit(function() {
        assert.deepEqual({
            open: true,
            started: true,
            written: 241,
            read: 241,
            stopped: true
        }, completed);
    })
};
<commit_msg>Use readFileSync to avoid errors on low ulimit setups.<commit_after>process.env.NODE_ENV = 'test';

var fs = require('fs');
var assert = require('assert');
var MBTiles = require('..');

var fixtureDir = __dirname + '/fixtures/output';

// Recreate output directory to remove previous tests.
try { fs.unlinkSync(fixtureDir + '/write_2.mbtiles'); } catch(err) {}
try { fs.mkdirSync(fixtureDir, 0755); } catch(err) {}

exports['test mbtiles file creation'] = function(beforeExit) {
    var completed = { written: 0, read: 0 };
    new MBTiles(fixtureDir + '/write_2.mbtiles', function(err, mbtiles) {
        completed.open = true;
        if (err) throw err;

        mbtiles.startWriting(function(err) {
            completed.started = true;
            if (err) throw err;

            fs.readdirSync(__dirname + '/fixtures/grids/').forEach(insertGrid);
        });

        function insertGrid(file) {
            var coords = file.match(/^plain_2_(\d+)_(\d+)_(\d+).json$/);
            if (!coords) return;

            // Flip Y coordinate because file names are TMS, but .putGrid() expects XYZ.
            coords[2] = Math.pow(2, coords[3]) - 1 - coords[2];

            var grid = fs.readFileSync(__dirname + '/fixtures/grids/' + file, 'utf8');
            mbtiles.putGrid(coords[3] | 0, coords[1] | 0, coords[2] | 0, JSON.parse(grid), function(err) {
                if (err) throw err;
                completed.written++;
                if (completed.written === 241) {
                    mbtiles.stopWriting(function(err) {
                        completed.stopped = true;
                        if (err) throw err;
                        verifyWritten();
                    });
                }
            });
        }

        function verifyWritten() {
            fs.readdirSync(__dirname + '/fixtures/grids/').forEach(function(file) {
                var coords = file.match(/^plain_2_(\d+)_(\d+)_(\d+).json$/);
                if (coords) {
                    // Flip Y coordinate because file names are TMS, but .getTile() expects XYZ.
                    coords[2] = Math.pow(2, coords[3]) - 1 - coords[2];
                    mbtiles.getGrid(coords[3] | 0, coords[1] | 0, coords[2] | 0, function(err, grid) {
                        if (err) throw err;
                        assert.deepEqual(JSON.stringify(grid), fs.readFileSync(__dirname + '/fixtures/grids/' + file, 'utf8'));
                        completed.read++;
                    });
                }
            });
        }
    });

    beforeExit(function() {
        assert.deepEqual({
            open: true,
            started: true,
            written: 241,
            read: 241,
            stopped: true
        }, completed);
    })
};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
    var path = require("path");

    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-mocha-test');

    var moduleCache = {};

    grunt.initConfig({
        build: {
            options: {
                modules: []
            },
            sweetjs: {
                options: {
                    compileFrom: "./lib/sweet"
                },
                src: "src/*.js",
                dest: ["build/lib/", "browser/scripts/"]
            },
            test: {
                options: {
                    compileFrom: "./build/lib/sweet"
                },
                src: "test/*.js",
                dest: "build/"
            }
        },
        copy: {
            buildMacros: {
                expand: true,
                flatten: true,
                src: "macros/*",
                dest: "build/macros/"
            },

            browserMacros: {
                expand: true,
                flatten: true,
                src: "macros/*",
                dest: "browser/scripts/"
            },

            browserSrc: {
                expand: true,
                flatten: true,
                src: "src/*",
                dest: "browser/scripts/src/"
            },

            dist: {
                expand: true,
                flatten: true,
                src: "build/lib/*.js",
                dest: "lib/"
            }
        },
        mochaTest: {
            test: {
                options:{
                    colors: !grunt.option('no-color')
                },
                src: ["build/*.js"]
            }
        },
        jshint: {
            all: ["build/lib/*.js"]
        }
    });

    grunt.registerMultiTask("build", function() {
        var options = this.options({
            modules: [],
            sourceMap: true,
            compileFrom: "./lib/sweet"
        });
        var sweet = require(options.compileFrom);

        var moduleSrc = options.modules.map(function(m) {
            return moduleCache[m] || (moduleCache[m] = readModule(m));
        }).join("\n");

        this.files.forEach(function(f) {
            var dest = Array.isArray(f.dest) ? f.dest : [f.dest];
            grunt.log.writeln("output to " + dest.join(", "));

            f.src.forEach(function(file) {
                grunt.log.writeln("compiling " + file);

                var code = moduleSrc + "\n" + grunt.file.read(file);
                var output = sweet.compile(code, {
                    sourceMap: options.sourceMap,
                    filename: file
                });

                dest.forEach(function(dest) {
                    var sourceMappingURL = dest + path.basename(file) + ".map";
                    var outputFile = output.code; // + "\n//# sourceMappingURL=" + path.basename(file) + ".map"
                    // macro expanded result
                    grunt.file.write(dest + path.basename(file),
                                     outputFile);
                    if (options.sourceMap) {
                        // sourcemap
                        grunt.file.write(sourceMappingURL,
                                         output.sourceMap);

                    }
                });
            })
        });

    });

    grunt.registerTask("dist", ["build:sweetjs", "copy:dist"]);

    grunt.registerTask("default", ["build",
                                   "copy:buildMacros",
                                   "copy:browserSrc",
                                   "copy:browserMacros",
                                   "mochaTest"]);

    function readModule(mod) {
        var path = require.resolve(mod);
        return grunt.file.read(path);
    }
};
<commit_msg>turning off sm for sweet.js<commit_after>module.exports = function(grunt) {
    var path = require("path");

    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-mocha-test');

    var moduleCache = {};

    grunt.initConfig({
        build: {
            options: {
                modules: []
            },
            sweetjs: {
                options: {
                    compileFrom: "./lib/sweet"
                },
                src: "src/*.js",
                dest: ["build/lib/", "browser/scripts/"]
            },
            test: {
                options: {
                    compileFrom: "./build/lib/sweet"
                },
                src: "test/*.js",
                dest: "build/"
            }
        },
        copy: {
            buildMacros: {
                expand: true,
                flatten: true,
                src: "macros/*",
                dest: "build/macros/"
            },

            browserMacros: {
                expand: true,
                flatten: true,
                src: "macros/*",
                dest: "browser/scripts/"
            },

            browserSrc: {
                expand: true,
                flatten: true,
                src: "src/*",
                dest: "browser/scripts/src/"
            },

            dist: {
                expand: true,
                flatten: true,
                src: "build/lib/*.js",
                dest: "lib/"
            }
        },
        mochaTest: {
            test: {
                options:{
                    colors: !grunt.option('no-color')
                },
                src: ["build/*.js"]
            }
        },
        jshint: {
            all: ["build/lib/*.js"]
        }
    });

    grunt.registerMultiTask("build", function() {
        var options = this.options({
            modules: [],
            sourceMap: true,
            compileFrom: "./lib/sweet"
        });
        var sweet = require(options.compileFrom);

        var moduleSrc = options.modules.map(function(m) {
            return moduleCache[m] || (moduleCache[m] = readModule(m));
        }).join("\n");

        this.files.forEach(function(f) {
            var dest = Array.isArray(f.dest) ? f.dest : [f.dest];
            grunt.log.writeln("output to " + dest.join(", "));

            f.src.forEach(function(file) {
                grunt.log.writeln("compiling " + file);

                var code = moduleSrc + "\n" + grunt.file.read(file);
                var output = sweet.compile(code, {
                    sourceMap: options.sourceMap,
                    filename: file
                });

                dest.forEach(function(dest) {
                    var sourceMappingURL = dest + path.basename(file) + ".map";
                    // var outputFile = output.code + "\n//# sourceMappingURL=" + path.basename(file) + ".map"
                    var outputFile = output.code;
                    // macro expanded result
                    grunt.file.write(dest + path.basename(file),
                                     outputFile);
                    if (options.sourceMap) {
                        // sourcemap
                        grunt.file.write(sourceMappingURL,
                                         output.sourceMap);

                    }
                });
            })
        });

    });

    grunt.registerTask("dist", ["build:sweetjs", "copy:dist"]);

    grunt.registerTask("default", ["build",
                                   "copy:buildMacros",
                                   "copy:browserSrc",
                                   "copy:browserMacros",
                                   "mochaTest"]);

    function readModule(mod) {
        var path = require.resolve(mod);
        return grunt.file.read(path);
    }
};
<|endoftext|>


<commit_before>/*
 * Notes :
 * need to figure out if there is a way to continously check if
 * the alarms sets off.
 */

/**
 * Welcome to Pebble.js!
 * Test
 * This is where you write your app.
 */

// Calls in required stuff
var UI = require('ui');
var Vibe = require('ui/vibe');
var Settings = require('settings');
var date = new Date();

//var Vector2 = require('vector2');

// A for loop to make array of hours
var hours = [];
for (var i = 0; i < 24; i++) {
    hours.push(i + 1);
}

// Sets up the alarms
var alarms = Settings.data('alarms') || [];

var createAlarmItems = function(alarms) {
    var items = [];
    for (var i = 0; i < hours.length; i++) {
        items.push({
            title: alarms[i].time,
            subtitle: alarms[i].enabled
        });
    }
    return items;
};

/*
// Creates a loop to make an array of hours
var createHourItems = function() {
  var items = [];
  for (var i = 0; i < hours.length; i++) {
    items.push({
      title: hours[i]
    });
  }
  return items;
};
*/

/*
var main = new UI.Menu({
   sections:[{
     items: createItems()
  }]
});

main.show();
*/

// The Spashscreen
var spashScreen = new UI.Card({
    title: 'Alarm',
    icon: 'images/menu_icon.png',
    subtitle: 'Welcome to Our App',
    body: 'This is the spash page'
    //banner (future plans)
});

// Makes a menu with New Alarms
var main = new UI.Menu({
    sections: [{
        items: [{
            title: 'Add New Alarm',
            subtitle: 'New Alarm'
        }, {
            // Dr. Seuss
            title: 'One Alarm'
        }, {
            title: 'Two Alarm'
        }, {
            title: 'Red Alarm'
        }, {
            title: 'Blue Alarm'
        }]
        //, createAlarmItems(alarms)
    }]
});

// Shows the spashscreen and goes to the menu after 400 ms
spashScreen.show();
setTimeout(function() {
    spashScreen.hide();
    main.show();
}, 400);

main.on('select', function(e) {
    // If it is on the "New Alarm Option"
    if (e.itemIndex === 0) {
        // Has a random card as a placeholder
        var card = new UI.Card();
        card.title('A Card');
        card.subtitle('Is a Window');
        card.body('The simplest window type in Pebble.js.');
        card.show();

        // When click the middle button it makes an alarm
        card.on('click', 'select', function() {
            Vibe.vibrate('long');
            alarms.push({
                hour: date.getHours() + 1,
                minute: date.getMinutes() + 2,
                enabled: true
            });
            createAlarmItems(alarms);
            card.hide();
        });
    } else {
        // Otherwise the user selects an alarm
        // Creates the Menu for Alarm Options
        var alarmOptions = new UI.Menu({
            sections : [{
                items: [{
                    subtitle: e.item.title
                }, {
                    title: 'Disable'
                }, {
                    title: 'Edit'
                }, {
                    title: 'Delete'
                }]
            }]
        });
        alarmOptions.show();
    }
    // Choose an option to chnage alarm
    alarmOptions.on('select', function(e) {
        switch(e.itemIndex) {
            case 0:
                // Disable or Enable the Alarm
                if (e.item.enabled) {
                    e.item.enabled = false;
                } else {
                    e.item.enabled = true;
                }
                break;
            case 1:
                // Edit the time of the alarm
                break;
            case 2:
                // Deletes the alarm
                alarms.splice(e.itemIndex, 1);
                break;
            default:
                console.log("error");
                break;
        }
        // Update the alarms and gets rid of the option menu
        createAlarmItems();
        alarmOptions.hide();
    });
});

// Code from before, I don't currently remove it for reference
/*
// Try but doesn't work
main.on('click', 'select', function(e) {
    var item = this.items(0);
    if (item.title == "Add New Alarm") {
        Vibe.vibrate('long');
        var card = new UI.Card();
        card.title('A Card');
        card.subtitle('Is a Window');
        card.body('The simplest window type in Pebble.js.');
        card.show();
    }
});
*/

/*
main.on('click', 'up', function(e) {
    var menu = new UI.Menu({
        sections: [{
            items: [{
                title: 'Pebble.js',
                icon: 'images/menu_icon.png',
                subtitle: 'Can do Menus'
            }, {
                title: 'Second Item',
                subtitle: 'Subtitle Text'
            }]
        }]
    });
    menu.on('select', function(e) {
        console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
        console.log('The item is titled "' + e.item.title + '"');
    });
    menu.show();
});
*/

// When click middle button
/*
main.on('click', 'up', function(e) {
    //test vibrqtion and date fubction
    console.log("foo");
    if (new Date() == new Date()) {
        Vibe.vibrate('long');
    }
    var wind = new UI.Window();
    //var time = new UI.TimeText();
    // Time in Text form
    var textfield = new UI.TimeText({
        position: new Vector2(0, 50),
        size: new Vector2(144, 30),
        font: 'gothic-24-bold',
        text: '%M:%S, %a',
        textAlign: 'center'
    });
    wind.add(textfield);
    wind.show();
});
*/

/*
main.on('click', 'down', function(e) {
    var card = new UI.Card();
    card.title('A Card');
    card.subtitle('Is a Window');
    card.body('The simplest window type in Pebble.js.');
    card.show();
});
*/
<commit_msg>seeing what caused the crash<commit_after>/*
 * Notes :
 * need to figure out if there is a way to continously check if
 * the alarms sets off.
 */

/**
 * Welcome to Pebble.js!
 * Test
 * This is where you write your app.
 */

// Calls in required stuff
var UI = require('ui');
var Vibe = require('ui/vibe');
var Settings = require('settings');
var date = new Date();

//var Vector2 = require('vector2');

// A for loop to make array of hours
var hours = [];
for (var i = 0; i < 24; i++) {
    hours.push(i + 1);
}

// Sets up the alarms
var alarms = Settings.data('alarms') || [];

var createAlarmItems = function(alarms) {
    var items = [];
    for (var i = 0; i < hours.length; i++) {
        items.push({
            title: alarms[i].time,
            subtitle: alarms[i].enabled
        });
    }
    return items;
};

/*
// Creates a loop to make an array of hours
var createHourItems = function() {
  var items = [];
  for (var i = 0; i < hours.length; i++) {
    items.push({
      title: hours[i]
    });
  }
  return items;
};
*/

/*
var main = new UI.Menu({
   sections:[{
     items: createItems()
  }]
});

main.show();
*/

// The Spashscreen
var spashScreen = new UI.Card({
    title: 'Alarm',
    icon: 'images/menu_icon.png',
    subtitle: 'Welcome to Our App',
    body: 'This is the spash page'
    //banner (future plans)
});

// Makes a menu with New Alarms
var main = new UI.Menu({
    sections: [{
        items: [{
            title: 'Add New Alarm',
            subtitle: 'New Alarm'
        }, {
            // Dr. Seuss
            title: 'One Alarm'
        }, {
            title: 'Two Alarm'
        }, {
            title: 'Red Alarm'
        }, {
            title: 'Blue Alarm'
        }]
        //, createAlarmItems(alarms)
    }]
});

// Shows the spashscreen and goes to the menu after 400 ms
spashScreen.show();
setTimeout(function() {
    spashScreen.hide();
    main.show();
}, 400);

main.on('select', function(e) {
    // If it is on the "New Alarm Option"
    if (e.itemIndex === 0) {
        // Has a random card as a placeholder
        var card = new UI.Card();
        card.title('A Card');
        card.subtitle('Is a Window');
        card.body('The simplest window type in Pebble.js.');
        card.show();

        // When click the middle button it makes an alarm
        card.on('click', 'select', function() {
            Vibe.vibrate('long');
            alarms.push({
                hour: date.getHours() + 1,
                minute: date.getMinutes() + 2,
                enabled: true
            });
            createAlarmItems(alarms);
            card.hide();
        });
    } else {
        // Otherwise the user selects an alarm
        // Creates the Menu for Alarm Options
        var alarmOptions = new UI.Menu({
            sections : [{
                items: [{
                    title: 'Disable'
                }, {
                    title: 'Edit'
                }, {
                    title: 'Delete'
                }]
            }]
        });
        alarmOptions.show();
    }
    // Choose an option to chnage alarm
    alarmOptions.on('select', function(e) {
        switch(e.itemIndex) {
            case 0:
                // Disable or Enable the Alarm
                if (e.item.enabled) {
                    e.item.enabled = false;
                } else {
                    e.item.enabled = true;
                }
                break;
            case 1:
                // Edit the time of the alarm
                break;
            case 2:
                // Deletes the alarm
                alarms.splice(e.itemIndex, 1);
                break;
            default:
                console.log("error");
                break;
        }
        // Update the alarms and gets rid of the option menu
        //createAlarmItems();
        alarmOptions.hide();
    });
});

// Code from before, I don't currently remove it for reference
/*
// Try but doesn't work
main.on('click', 'select', function(e) {
    var item = this.items(0);
    if (item.title == "Add New Alarm") {
        Vibe.vibrate('long');
        var card = new UI.Card();
        card.title('A Card');
        card.subtitle('Is a Window');
        card.body('The simplest window type in Pebble.js.');
        card.show();
    }
});
*/

/*
main.on('click', 'up', function(e) {
    var menu = new UI.Menu({
        sections: [{
            items: [{
                title: 'Pebble.js',
                icon: 'images/menu_icon.png',
                subtitle: 'Can do Menus'
            }, {
                title: 'Second Item',
                subtitle: 'Subtitle Text'
            }]
        }]
    });
    menu.on('select', function(e) {
        console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
        console.log('The item is titled "' + e.item.title + '"');
    });
    menu.show();
});
*/

// When click middle button
/*
main.on('click', 'up', function(e) {
    //test vibrqtion and date fubction
    console.log("foo");
    if (new Date() == new Date()) {
        Vibe.vibrate('long');
    }
    var wind = new UI.Window();
    //var time = new UI.TimeText();
    // Time in Text form
    var textfield = new UI.TimeText({
        position: new Vector2(0, 50),
        size: new Vector2(144, 30),
        font: 'gothic-24-bold',
        text: '%M:%S, %a',
        textAlign: 'center'
    });
    wind.add(textfield);
    wind.show();
});
*/

/*
main.on('click', 'down', function(e) {
    var card = new UI.Card();
    card.title('A Card');
    card.subtitle('Is a Window');
    card.body('The simplest window type in Pebble.js.');
    card.show();
});
*/
<|endoftext|>


<commit_before>module.exports = function (grunt) {

   var AUTO_START_BROWSERS = ['Chrome', 'Firefox', 'Safari'];

   var STREAM_SOURCE_PORT = 4567;

   // NB: source files are order sensitive
   var OBOE_BROWSER_SOURCE_FILES = [
      'src/functional.js'
   ,  'src/util.js'
   ,  'src/lists.js'
   ,  'src/libs/clarinet.js'
   ,  'src/clarinetListenerAdaptor.js'
   ,  'src/streamingHttp-browser.js'
   ,  'src/jsonPathSyntax.js'
   ,  'src/incrementalContentBuilder.js'
   ,  'src/jsonPath.js'
   ,  'src/pubSub.js'
   ,  'src/events.js'
   ,  'src/instanceController.js'
   ,  'src/wire.js'
   ,  'src/publicApi.js'
   ];

   var OBOE_NODE_SOURCE_FILES = [
      'src/functional.js'
   ,  'src/util.js'
   ,  'src/lists.js'
   ,  'src/clarinetListenerAdaptor.js'
   ,  'src/streamingHttp-node.js'
   ,  'src/jsonPathSyntax.js'
   ,  'src/incrementalContentBuilder.js'
   ,  'src/jsonPath.js'
   ,  'src/pubSub.js'
   ,  'src/events.js'
   ,  'src/instanceController.js'
   ,  'src/wire.js'
   ,  'src/publicApi.js'
   ];

   var FILES_TRIGGERING_KARMA = [
      'src/**/*.js',
      'test/specs/*.spec.js',
      'test/libs/*.js'
   ];

   grunt.initConfig({

      pkg:grunt.file.readJSON("package.json")

   ,  clean: ['dist/*.js', 'build/*.js']

   ,  concat: {
         browser:{
            src: OBOE_BROWSER_SOURCE_FILES,
            dest: 'build/oboe-browser.concat.js'
         },
         node:{
            src: OBOE_NODE_SOURCE_FILES,
            dest: 'build/oboe-node.concat.js'
         }
      }

   ,  wrap: {
         browserPackage: {
            src: 'build/oboe-browser.concat.js',
            dest: '.',
            wrapper: [
               '// this file is the concatenation of several js files. See https://github.com/jimhigson/oboe-browser.js/tree/master/src ' +
                   'for the unconcatenated source\n' +
               // having a local undefined, window, Object etc allows slightly better minification:
               '(function  (window, Object, Array, Error, undefined ) {\n'

                  // source code here

            ,     '\n\n;' +

                  'if ( typeof define === "function" && define.amd ) {' +
                     'define( "oboe", [], function () { return oboe; } );' +
                  '} else {' +
                     'window.oboe = oboe;' +
                  '}' +
               '})(window, Object, Array, Error);'
            ]
         },

         nodePackage: {
            src: 'build/oboe-node.concat.js',
            dest: '.',
            wrapper: [
               '// this file is the concatenation of several js files. See https://github.com/jimhigson/oboe-browser.js/tree/master/src ' +
                   'for the unconcatenated source\n' +

               'module.exports = (function  () {\n' +
                  'var clarinet = require("clarinet");\n'

                              // source code here

            ,  '\n\n;return oboe;})();'
            ]
         }
      }

   ,  uglify: {
         build:{
            files:{
               'build/oboe-browser.min.js': 'build/oboe-browser.concat.js'
            }
         }
      }

   ,  karma: {
         options:{
            singleRun: true,
            proxies: {
               '/testServer'   : 'http://localhost:' + STREAM_SOURCE_PORT
            },
            // test results reporter to use
            // possible values: 'dots', 'progress', 'junit'
            reporters : ['progress'],

            // enable / disable colors in the output (reporters and logs)
            colors : true
         }

      ,
         'precaptured-dev': {
            // for doing a single test run with already captured browsers during development.
            // this is good for running tests in browsers karma can't easily start such as
            // IE running inside a Windows VM on a unix dev environment
            browsers: [],
            configFile: 'test/unit.conf.js',
            singleRun: 'true'
         }
      ,
         'single-dev': {
            browsers: AUTO_START_BROWSERS,
            configFile: 'test/unit.conf.js'
         }
      ,
         'single-concat': {
            browsers: AUTO_START_BROWSERS,
            configFile: 'test/concat.conf.js'
         }
      ,
         'single-minified': {
            browsers: AUTO_START_BROWSERS,
            configFile: 'test/min.conf.js'
         }

      ,
         'single-amd': {
            browsers: AUTO_START_BROWSERS,
            configFile: 'test/amd.conf.js'
         }

      ,
         'single-browser-http': {
            browsers: AUTO_START_BROWSERS,
            configFile: 'test/http.conf.js'
         }

      ,
         'persist': {
            // for setting up a persistent karma server.
            // To start the server, the task is:
            //    karma:persist
            // To run these, the task is:
            //    karma:persist:run
            configFile: 'test/unit.conf.js',
            browsers: [],
            singleRun:false,
            background:true
         }
      }

   ,  copy: {
         browserDist: {
            files: [
               {src: ['build/oboe-browser.min.js'],    dest: 'dist/oboe-browser.min.js'}
            ,  {src: ['build/oboe-browser.concat.js'], dest: 'dist/oboe-browser.js'    }
            ]
         },
         nodeDist: {
            files: [
               {src: ['build/oboe-node.concat.js'],    dest: 'dist/oboe-node.js'}
            ]
         }
      }

   ,  exec:{
         // these might not go too well on Windows :-) - get Cygwin.
         reportMinifiedSize:{
            command: "echo Minified size to Browser is `wc -c < dist/oboe-browser.min.js` bytes"
         },
         reportMinifiedAndGzippedSize:{
            command: "echo Size after gzip is `gzip --best --stdout dist/oboe-browser.min.js | wc -c` bytes - max 5120"
         }
      }

   ,  watch:{
         karma:{
            files:FILES_TRIGGERING_KARMA,
            tasks:['karma:persist:run']
         },

         // like above but reports the file size. This is good for
         // watching while developing to make sure it doesn't get
         // too big. Doesn't run tests against minified.
         karmaAndSize:{
            files: FILES_TRIGGERING_KARMA,
            tasks:[
               'karma:persist:run',
               'browser-build',
               'dist-sizes']
         },

         // like above but reports the file size. This is good for
         // watching while developing to make sure it doesn't get
         // too big. Doesn't run tests against minified.
         testNode:{
            files: FILES_TRIGGERING_KARMA,
            tasks:[
               'node-build-run']
         },

         restartStreamSourceAndRunTests:{
            // this fails at the moment because start-stream-source
            // fails if run more than once - the port is taken.
            files: ['test/streamsource.js'],
            tasks: ['start-stream-source', 'karma:persist:run']
         }
      }

   ,  concurrent:{
         watchDev: {
            tasks:[ 'watch:karmaAndSize', 'watch:restartStreamSourceAndRunTests' ],
            options:{
               logConcurrentOutput: true
            }
         }
      }

   });

   require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

   var streamSource;

   grunt.registerTask('start-stream-source', function () {
      grunt.log.ok('do we have a streaming source already?', !!streamSource);

      // if we previously loaded the streamsource, stop it to let the new one in:
      if( streamSource ) {
         grunt.log.ok('there seems to be a streaming server already, let\'s stop it');
         streamSource.stop();
      }

      grunt.log.ok('let\'s get a streaming server started');
      streamSource = require('./test/streamsource.js');
      streamSource.start(STREAM_SOURCE_PORT, grunt);
      grunt.log.ok('we started it, but does it work?', streamSource);
   });

   grunt.registerTask("jasmine_node_oboe", "Runs jasmine-node.", function() {

      require('jasmine-node').executeSpecsInFolder({

         "specFolders":[process.cwd() + '/test/specs/'],
         "isVerbose":true,
         "showColors":true,
         "teamcity":false,
         "useRequireJs":false,
         "regExpSpec":/oboe\.(?:integration|performance)\.spec\.(js)$/,
         "junitreport":{"report":false, "savePath":"./reports/", "useDotNotation":true, "consolidate":true},
         "includeStackTrace":true,
         "growl":false,
         onComplete: this.async()

      });
   });

   grunt.registerTask('test-start-server',   [
      'karma:persist'
   ]);

   grunt.registerTask('test-run',   [
      'karma:persist:run'
   ]);

   grunt.registerTask('dist-sizes',   [
      'exec:reportMinifiedSize',
      'exec:reportMinifiedAndGzippedSize'
   ]);

   grunt.registerTask('node-build',      [
      'concat:node',
      'wrap:nodePackage',
      'copy:nodeDist'
   ]);

   grunt.registerTask('node-build-test',      [
      'node-build',
      'jasmine_node_oboe'
   ]);

   grunt.registerTask('node',      [
      'start-stream-source',
      'node-build-test'
   ]);

   grunt.registerTask('browser-build',      [
      'concat:browser',
      'concat:node',
      'wrap:browserPackage',
      'uglify',
      'copy:browserDist'
   ]);

   grunt.registerTask('browser-build-test',      [
      'karma:single-dev',
      'karma:single-browser-http',
      'browser-build',
      'karma:single-concat',
      'karma:single-minified',
      'karma:single-amd'
   ]);

   grunt.registerTask('default',      [

      'clear',
      'clean',
      'start-stream-source',

      'browser-build-test',

      'node-build-test',

      'dist-sizes'
   ]);

   // browser-test-auto-run or node-test-auto-run
   //
   // The most useful for developing. Start this task, capture some browsers
   // (unless node) then edit the code. Tests will be run as the code is
   // saved.
   grunt.registerTask('browser-test-auto-run',   [
      'start-stream-source',
      'karma:persist',
      'concurrent:watchDev'
   ]);
   grunt.registerTask('node-test-auto-run',   [
      'start-stream-source',
      'watch:testNode'
   ]);
};<commit_msg>add task for running integration tests on both platform types<commit_after>module.exports = function (grunt) {

   var AUTO_START_BROWSERS = ['Chrome', 'Firefox', 'Safari'];

   var STREAM_SOURCE_PORT = 4567;

   // NB: source files are order sensitive
   var OBOE_BROWSER_SOURCE_FILES = [
      'src/functional.js'
   ,  'src/util.js'
   ,  'src/lists.js'
   ,  'src/libs/clarinet.js'
   ,  'src/clarinetListenerAdaptor.js'
   ,  'src/streamingHttp-browser.js'
   ,  'src/jsonPathSyntax.js'
   ,  'src/incrementalContentBuilder.js'
   ,  'src/jsonPath.js'
   ,  'src/pubSub.js'
   ,  'src/events.js'
   ,  'src/instanceController.js'
   ,  'src/wire.js'
   ,  'src/publicApi.js'
   ];

   var OBOE_NODE_SOURCE_FILES = [
      'src/functional.js'
   ,  'src/util.js'
   ,  'src/lists.js'
   ,  'src/clarinetListenerAdaptor.js'
   ,  'src/streamingHttp-node.js'
   ,  'src/jsonPathSyntax.js'
   ,  'src/incrementalContentBuilder.js'
   ,  'src/jsonPath.js'
   ,  'src/pubSub.js'
   ,  'src/events.js'
   ,  'src/instanceController.js'
   ,  'src/wire.js'
   ,  'src/publicApi.js'
   ];

   var FILES_TRIGGERING_KARMA = [
      'src/**/*.js',
      'test/specs/*.spec.js',
      'test/libs/*.js'
   ];

   grunt.initConfig({

      pkg:grunt.file.readJSON("package.json")

   ,  clean: ['dist/*.js', 'build/*.js']

   ,  concat: {
         browser:{
            src: OBOE_BROWSER_SOURCE_FILES,
            dest: 'build/oboe-browser.concat.js'
         },
         node:{
            src: OBOE_NODE_SOURCE_FILES,
            dest: 'build/oboe-node.concat.js'
         }
      }

   ,  wrap: {
         browserPackage: {
            src: 'build/oboe-browser.concat.js',
            dest: '.',
            wrapper: [
               '// this file is the concatenation of several js files. See https://github.com/jimhigson/oboe-browser.js/tree/master/src ' +
                   'for the unconcatenated source\n' +
               // having a local undefined, window, Object etc allows slightly better minification:
               '(function  (window, Object, Array, Error, undefined ) {\n'

                  // source code here

            ,     '\n\n;' +

                  'if ( typeof define === "function" && define.amd ) {' +
                     'define( "oboe", [], function () { return oboe; } );' +
                  '} else {' +
                     'window.oboe = oboe;' +
                  '}' +
               '})(window, Object, Array, Error);'
            ]
         },

         nodePackage: {
            src: 'build/oboe-node.concat.js',
            dest: '.',
            wrapper: [
               '// this file is the concatenation of several js files. See https://github.com/jimhigson/oboe-browser.js/tree/master/src ' +
                   'for the unconcatenated source\n' +

               'module.exports = (function  () {\n' +
                  'var clarinet = require("clarinet");\n'

                              // source code here

            ,  '\n\n;return oboe;})();'
            ]
         }
      }

   ,  uglify: {
         build:{
            files:{
               'build/oboe-browser.min.js': 'build/oboe-browser.concat.js'
            }
         }
      }

   ,  karma: {
         options:{
            singleRun: true,
            proxies: {
               '/testServer'   : 'http://localhost:' + STREAM_SOURCE_PORT
            },
            // test results reporter to use
            // possible values: 'dots', 'progress', 'junit'
            reporters : ['progress'],

            // enable / disable colors in the output (reporters and logs)
            colors : true
         }

      ,
         'precaptured-dev': {
            // for doing a single test run with already captured browsers during development.
            // this is good for running tests in browsers karma can't easily start such as
            // IE running inside a Windows VM on a unix dev environment
            browsers: [],
            configFile: 'test/unit.conf.js',
            singleRun: 'true'
         }
      ,
         'single-dev': {
            browsers: AUTO_START_BROWSERS,
            configFile: 'test/unit.conf.js'
         }
      ,
         'single-concat': {
            browsers: AUTO_START_BROWSERS,
            configFile: 'test/concat.conf.js'
         }
      ,
         'single-minified': {
            browsers: AUTO_START_BROWSERS,
            configFile: 'test/min.conf.js'
         }

      ,
         'single-amd': {
            browsers: AUTO_START_BROWSERS,
            configFile: 'test/amd.conf.js'
         }

      ,
         'single-browser-http': {
            browsers: AUTO_START_BROWSERS,
            configFile: 'test/http.conf.js'
         }

      ,
         'persist': {
            // for setting up a persistent karma server.
            // To start the server, the task is:
            //    karma:persist
            // To run these, the task is:
            //    karma:persist:run
            configFile: 'test/unit.conf.js',
            browsers: [],
            singleRun:false,
            background:true
         }
      }

   ,  copy: {
         browserDist: {
            files: [
               {src: ['build/oboe-browser.min.js'],    dest: 'dist/oboe-browser.min.js'}
            ,  {src: ['build/oboe-browser.concat.js'], dest: 'dist/oboe-browser.js'    }
            ]
         },
         nodeDist: {
            files: [
               {src: ['build/oboe-node.concat.js'],    dest: 'dist/oboe-node.js'}
            ]
         }
      }

   ,  exec:{
         // these might not go too well on Windows :-) - get Cygwin.
         reportMinifiedSize:{
            command: "echo Minified size to Browser is `wc -c < dist/oboe-browser.min.js` bytes"
         },
         reportMinifiedAndGzippedSize:{
            command: "echo Size after gzip is `gzip --best --stdout dist/oboe-browser.min.js | wc -c` bytes - max 5120"
         }
      }

   ,  watch:{
         karma:{
            files:FILES_TRIGGERING_KARMA,
            tasks:['karma:persist:run']
         },

         // like above but reports the file size. This is good for
         // watching while developing to make sure it doesn't get
         // too big. Doesn't run tests against minified.
         karmaAndSize:{
            files: FILES_TRIGGERING_KARMA,
            tasks:[
               'karma:persist:run',
               'browser-build',
               'dist-sizes']
         },

         // like above but reports the file size. This is good for
         // watching while developing to make sure it doesn't get
         // too big. Doesn't run tests against minified.
         testNode:{
            files: FILES_TRIGGERING_KARMA,
            tasks:[
               'node-build-run']
         },

         restartStreamSourceAndRunTests:{
            // this fails at the moment because start-stream-source
            // fails if run more than once - the port is taken.
            files: ['test/streamsource.js'],
            tasks: ['start-stream-source', 'karma:persist:run']
         }
      }

   ,  concurrent:{
         watchDev: {
            tasks:[ 'watch:karmaAndSize', 'watch:restartStreamSourceAndRunTests' ],
            options:{
               logConcurrentOutput: true
            }
         }
      }

   });

   require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

   var streamSource;

   grunt.registerTask('start-stream-source', function () {
      grunt.log.ok('do we have a streaming source already?', !!streamSource);

      // if we previously loaded the streamsource, stop it to let the new one in:
      if( streamSource ) {
         grunt.log.ok('there seems to be a streaming server already, let\'s stop it');
         streamSource.stop();
      }

      grunt.log.ok('let\'s get a streaming server started');
      streamSource = require('./test/streamsource.js');
      streamSource.start(STREAM_SOURCE_PORT, grunt);
      grunt.log.ok('we started it, but does it work?', streamSource);
   });

   grunt.registerTask("jasmine_node_oboe", "Runs jasmine-node.", function() {

      require('jasmine-node').executeSpecsInFolder({

         "specFolders":[process.cwd() + '/test/specs/'],
         "isVerbose":true,
         "showColors":true,
         "teamcity":false,
         "useRequireJs":false,
         "regExpSpec":/oboe\.(?:integration|performance)\.spec\.(js)$/,
         "junitreport":{"report":false, "savePath":"./reports/", "useDotNotation":true, "consolidate":true},
         "includeStackTrace":true,
         "growl":false,
         onComplete: this.async()

      });
   });

   grunt.registerTask('test-start-server',   [
      'karma:persist'
   ]);

   grunt.registerTask('test-run',   [
      'karma:persist:run'
   ]);

   grunt.registerTask('dist-sizes',   [
      'exec:reportMinifiedSize',
      'exec:reportMinifiedAndGzippedSize'
   ]);

   grunt.registerTask('node-build',      [
      'concat:node',
      'wrap:nodePackage',
      'copy:nodeDist'
   ]);

   grunt.registerTask('node-build-test',      [
      'node-build',
      'jasmine_node_oboe'
   ]);

   grunt.registerTask('node',      [
      'start-stream-source',
      'node-build-test'
   ]);

   grunt.registerTask('browser-build',      [
      'concat:browser',
      'concat:node',
      'wrap:browserPackage',
      'uglify',
      'copy:browserDist'
   ]);

   grunt.registerTask('browser-build-test',      [
      'karma:single-dev',
      'karma:single-browser-http',
      'browser-build',
      'karma:single-concat',
      'karma:single-minified',
      'karma:single-amd'
   ]);

   // build and run just the integration tests.
   grunt.registerTask('build-integration-test',      [
      'browser-build',
      'node-build',
      'start-stream-source',
      'karma:single-concat',
      'jasmine_node_oboe'
   ]);

   grunt.registerTask('default',      [

      'clear',
      'clean',
      'start-stream-source',

      'browser-build-test',

      'node-build-test',

      'dist-sizes'
   ]);

   // browser-test-auto-run or node-test-auto-run
   //
   // The most useful for developing. Start this task, capture some browsers
   // (unless node) then edit the code. Tests will be run as the code is
   // saved.
   grunt.registerTask('browser-test-auto-run',   [
      'start-stream-source',
      'karma:persist',
      'concurrent:watchDev'
   ]);
   grunt.registerTask('node-test-auto-run',   [
      'start-stream-source',
      'watch:testNode'
   ]);
};<|endoftext|>


<commit_before>import qs from 'qs';

class API {
  constructor(core, resource) {
    this.core = core;
    this.resource = resource;
  }

  all(query, actuallyAll){
    if (actuallyAll) { // Quick way to get everything unpaginated
      query.page = 1;
      return this.core.get(this.resource + '?' + qs.stringify(query)).then(results => {
          const pages = Math.ceil(results.total/results.perPage);
          const r = [results];
          for (let i = 2; i <= pages; i++) {
            query.page = i;
            r.push(this.core.get(this.resource + '?' + qs.stringify(query)));
          }
          return Promise.all(r);
        })
        .then(results => {
          return results.reduce((data, cur) => {
            return data.concat(cur.data);
          }, []);
        });
    }
    return this.core.get(this.resource + '?' + qs.stringify(query));
  }

  one(id) {
    return this.core.get(this.resource + '/' + id);
  }

  create(body) {
    return this.core.post(this.resource, body);
  }

  update(id, body) {
    return this.core.put(this.resource + '/' + id, body);
  }

  destroy(id) {
    return this.core.delete(this.resource + '/' + id);
  }
}

export default API;
<commit_msg>Stopped unwrapping data<commit_after>import qs from 'qs';

class API {
  constructor(core, resource) {
    this.core = core;
    this.resource = resource;
  }

  all(query, actuallyAll){
    if (actuallyAll) { // Quick way to get everything unpaginated
      query.page = 1;
      return this.core.get(this.resource + '?' + qs.stringify(query)).then(results => {
        const pages = Math.ceil(results.total/results.perPage);
        const r = [results];
        for (let i = 2; i <= pages; i++) {
          query.page = i;
          r.push(this.core.get(this.resource + '?' + qs.stringify(query)));
        }
        return Promise.all(r);
      }).then(results => {
        return {
          data: results.reduce((data, cur) => {
            return data.concat(cur.data);
          }, []);
        }
      });
    }
    return this.core.get(this.resource + '?' + qs.stringify(query));
  }

  one(id) {
    return this.core.get(this.resource + '/' + id);
  }

  create(body) {
    return this.core.post(this.resource, body);
  }

  update(id, body) {
    return this.core.put(this.resource + '/' + id, body);
  }

  destroy(id) {
    return this.core.delete(this.resource + '/' + id);
  }
}

export default API;
<|endoftext|>


<commit_before>'use strict';

const directory = "./";
var gulp = require('gulp');

function pages() {

    var swig = require('swig');
    var render = require('static-engine-render');
    var content = require('static-engine-content');
    var engine = require('static-engine');
    var cson = require('cson-parser');
    var page;

    return engine(
        content('./content/index.cson', [
            function (page, done) {

                page = cson.parse(page.content);

                done(null, page);
            }
        ]),
        render('./index.html', function(page, done) {

            swig.renderFile('./templates/index.html', page, done);
        })
    );
}

function css(){

    var autoprefixer = require('gulp-autoprefixer');
    var uncss = require('gulp-uncss');
    var csso = require('gulp-csso');
    var glob = require('glob');
    var rework = require('gulp-rework');
    var concat = require('gulp-concat');
    var calc = require('rework-calc');
    var media = require('rework-custom-media');
    var npm = require('rework-npm');
    var vars = require('rework-vars');
    var colors = require('rework-plugin-colors');
    var cheerio = require('gulp-cheerio');

    return gulp.src("./css/app.css")
        .pipe(rework(
            npm(),
            vars(),
            media(),
            calc,
            colors()
        ))
        .pipe(autoprefixer('> 1%', 'last 2 versions'))
        .pipe(concat("index.css"))
        .pipe(uncss({
            html: glob.sync('index.html')
        }))
        .pipe(csso())
        .pipe(gulp.dest(directory));
}

function js() {

    var concat = require('gulp-concat');
    var uglify = require('gulp-uglify');
    var tap = require('gulp-tap');
    var cheerio = require('gulp-cheerio');
    var browserify = require('browserify');
    var source = require('vinyl-source-stream');
    var buffer = require('vinyl-buffer');
    var collapse = require('bundle-collapser/plugin');
    var bundler = browserify({
        entries: "./js/app.js",
        debug: false
    });

    return bundler
        .plugin(collapse)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(tap(function(file){

            file.contents = new Buffer('!function(window, document){ ' + file.contents + '; }(window, document);');
        }))
        .pipe(uglify())
        .pipe(tap(function(file){

            return gulp.src('index.html')
                .pipe(cheerio(function($){

                    $('body').append('<script>'+file.contents+'</script>');
                }))
                .pipe(gulp.dest(directory));
        }));
}

function optimize(){

    var htmlmin = require('gulp-htmlmin');

    return gulp.src('index.html')
        .pipe(htmlmin({
            collapseWhitespace: true
        }))
        .pipe(gulp.dest(directory));
}

function icons() {

    var cheerio = require('gulp-cheerio');
    var fs = require('fs');

    return gulp.src('./index.html')
        .pipe(cheerio(function($){

            var defs = new Set();
            var href;
            var id;
            var paths;
            var get_path = function(id) {

                return fs.readFileSync('./node_modules/geomicons-open/src/paths/'+id+'.d', {encoding:'utf8'}).split("\n").join('');
            };

            $('use').each(function(){

                href = $(this).attr('xlink:href');
                id = href.substring(1);

                if($('use[xlink\\:href="'+href+'"]').length > 1) {

                    defs.add(id);
                }
                else {

                    $(this).replaceWith('<path d="' + get_path(id) + '"/>');
                }
            });

            if(defs.size) {

                paths = [];

                for(id of defs) {

                    paths.push('<path d="' + get_path(id) + '" id="' + id + '"/>');
                }

                $('body').append('<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"><defs>'+paths.join('')+'</defs></svg>')
            }
        }))
        .pipe(gulp.dest(directory));
}

function selectors() {

    var gs = require('gulp-selectors');

    return gulp.src(['index.css', 'index.html'])
        .pipe(gs.run())
        .pipe(gulp.dest(directory));
}

function combine() {

    var path = require('path');
    var tap = require('gulp-tap');
    var cheerio = require('gulp-cheerio');

    return gulp.src('index.css')
        .pipe(tap(function(file){

            gulp.src('index.html')
                .pipe(cheerio(function($){

                    $('head').append('<style type="text/css">'+file.contents+'</style>');

                }))
                .pipe(gulp.dest(directory));
        }));
}

function serve(done){

    var express = require('express');
    var _static = require('express-static');
    var logger = require('express-log');

    var app = express();

    app.use(logger());

    app.use(_static(directory));

    app.use(function(req, res, next){

        res.redirect('/');
    });

    var server = app.listen(8088, function(){
        console.log('server is running at %s', server.address().port);
    });

    done();
}

function watch() {

    gulp.watch(['css/**/*.css', 'js/**/*.js', 'templates/**/*.html', 'content/**/*.cson'], 'default');
}

gulp.task('default', gulp.series( pages, optimize, icons, js, css, selectors, combine ) );

gulp.task('dev', gulp.parallel('default', watch, serve));
<commit_msg>Clarify and standardize naming of functions and variables<commit_after>'use strict';

const directory = "./";
var gulp = require('gulp');

function pages() {

    var swig = require('swig');
    var render = require('static-engine-render');
    var content = require('static-engine-content');
    var engine = require('static-engine');
    var cson = require('cson-parser');
    var page;

    return engine(
        content('./content/index.cson', [
            function (page, done) {

                page = cson.parse(page.content);

                done(null, page);
            }
        ]),
        render('./index.html', function(page, done) {

            swig.renderFile('./templates/index.html', page, done);
        })
    );
}

function css(){

    var autoprefixer = require('gulp-autoprefixer');
    var uncss = require('gulp-uncss');
    var csso = require('gulp-csso');
    var glob = require('glob');
    var rework = require('gulp-rework');
    var concat = require('gulp-concat');
    var calc = require('rework-calc');
    var media = require('rework-custom-media');
    var npm = require('rework-npm');
    var vars = require('rework-vars');
    var colors = require('rework-plugin-colors');
    var cheerio = require('gulp-cheerio');

    return gulp.src("./css/app.css")
        .pipe(rework(
            npm(),
            vars(),
            media(),
            calc,
            colors()
        ))
        .pipe(autoprefixer('> 1%', 'last 2 versions'))
        .pipe(concat("index.css"))
        .pipe(uncss({
            html: glob.sync('index.html')
        }))
        .pipe(csso())
        .pipe(gulp.dest(directory));
}

function js() {

    var concat = require('gulp-concat');
    var uglify = require('gulp-uglify');
    var tap = require('gulp-tap');
    var cheerio = require('gulp-cheerio');
    var browserify = require('browserify');
    var source = require('vinyl-source-stream');
    var buffer = require('vinyl-buffer');
    var collapse = require('bundle-collapser/plugin');
    var bundler = browserify({
        entries: "./js/app.js",
        debug: false
    });

    return bundler
        .plugin(collapse)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(tap(function(file){

            file.contents = new Buffer('!function(window, document){ ' + file.contents + '; }(window, document);');
        }))
        .pipe(uglify())
        .pipe(tap(function(file){

            return gulp.src('index.html')
                .pipe(cheerio(function($){

                    $('body').append('<script>'+file.contents+'</script>');
                }))
                .pipe(gulp.dest(directory));
        }));
}

function minify_html(){

    var htmlmin = require('gulp-htmlmin');

    return gulp.src('index.html')
        .pipe(htmlmin({
            collapseWhitespace: true
        }))
        .pipe(gulp.dest(directory));
}

function icons() {

    var cheerio = require('gulp-cheerio');
    var fs = require('fs');

    return gulp.src('./index.html')
        .pipe(cheerio(function($){

            var defs = new Set();
            var href;
            var id;
            var paths;
            var get_path = function(id) {

                return fs.readFileSync('./node_modules/geomicons-open/src/paths/'+id+'.d', {encoding:'utf8'}).split("\n").join('');
            };

            $('use').each(function(){

                href = $(this).attr('xlink:href');
                id = href.substring(1);

                if($('use[xlink\\:href="'+href+'"]').length > 1) {

                    defs.add(id);
                }
                else {

                    $(this).replaceWith('<path d="' + get_path(id) + '"/>');
                }
            });

            if(defs.size) {

                paths = [];

                for(id of defs) {

                    paths.push('<path d="' + get_path(id) + '" id="' + id + '"/>');
                }

                $('body').append('<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"><defs>'+paths.join('')+'</defs></svg>')
            }
        }))
        .pipe(gulp.dest(directory));
}

function shorten_selectors() {

    var selectors = require('gulp-selectors');

    return gulp.src(['index.css', 'index.html'])
        .pipe(selectors.run())
        .pipe(gulp.dest(directory));
}

function insert_css() {

    var path = require('path');
    var tap = require('gulp-tap');
    var cheerio = require('gulp-cheerio');

    return gulp.src('index.css')
        .pipe(tap(function(file){

            gulp.src('index.html')
                .pipe(cheerio(function($){

                    $('head').append('<style type="text/css">'+file.contents+'</style>');

                }))
                .pipe(gulp.dest(directory));
        }));
}

function serve(done){

    var express = require('express');
    var _static = require('express-static');
    var logger = require('express-log');

    var app = express();

    app.use(logger());

    app.use(_static(directory));

    app.use(function(req, res, next){

        res.redirect('/');
    });

    var server = app.listen(8088, function(){
        console.log('server is running at %s', server.address().port);
    });

    done();
}

function watch() {

    gulp.watch(['css/**/*.css', 'js/**/*.js', 'templates/**/*.html', 'content/**/*.cson'], 'default');
}

gulp.task('default', gulp.series( pages, minify_html, icons, js, css, shorten_selectors, insert_css ) );

gulp.task('dev', gulp.parallel('default', watch, serve));
<|endoftext|>


<commit_before>var params;
function getParams (key) {
	if (!params) {
		params = {};
		var entries = window.location.search.substr(1).split('&');
		entries.forEach(function (entry) {
			entry = entry.split('=');
			if (entry[0]) {
				if (!entry[1]) {
					entry[1] = '';
				}
				params[entry[0]] = entry[1];
			}
		});
	}
	return params[key];
}

var CONFIG = {
	locales: [
		'en-US',
		'fr-FR',
	],
	bundles: [
		'accounts',
		'daysOfWeek',
		'profile',
		'activation',
		'devices',
		'registration',
		'adFormats',
		'errorPage',
		'stripe',
		'ads',
		'errors',
		'tactics',
		'campaigns',
		'invoices',
		'users',
		'common',
		'navbar',
		'widgets',
		'days',
		'payments',
	]
};

angular.module('myApp', [
		'ngLocalize',
		'ngLocalize.Config',
		'ngLocalize.InstalledLanguages',
		'agGrid',
	])
    .value('localeSupported', CONFIG.locales)
    .value('localeConf', {
        basePath: getParams('basePath'),
        defaultLocale: CONFIG.locales[0],
        sharedDictionary: 'common',
        fileExtension: '.lang.json',
        persistSelection: false,
        cookieName: 'COOKIE_LOCALE_LANG',
        observableAttrs: new RegExp('^data-(?!ng-|i18n)'),
        delimiter: '::'
    })
	.controller('myApp', function ($q, $timeout, $scope, $window, $interpolate, localeConf, locale) {
		var downloadjs = $window.download;

		$window.onbeforeunload = function(e) {
		  return 'All work will be lost!!!';
		};

        $($window.document.body).keydown(function (e) {
            var elm = e.target.nodeName.toLowerCase();
            if (e.which == 8 && elm !== 'input' && elm  !== 'textarea') {
                e.preventDefault();
            }
            // stopping event bubbling up the DOM tree..
            e.stopPropagation();
        });

		$scope.localeCache = {};

		$scope.errors = [];

		$scope.localeConf = localeConf;

		$scope.locales = CONFIG.locales.slice(1);
		$scope.selectedLocale = $scope.locales[0];
		$scope.bundles = CONFIG.bundles;

		$scope.gridOptions = {
			singleClickEdit: true,
	        pinnedColumnCount: 1,
	        enableColResize: true,
	        groupUseEntireRow: true,
	        groupKeys: [
	        	'bundle'
	        ],
	        groupDefaultExpanded: true,
		};

		// load everything into memory;
		function loadBundles (localeIndex, cb) {
			var bundleIndex = 0;
			if (!CONFIG.locales[localeIndex]) {
				(cb || angular.noop)();
				return;
			}
			var localeName = CONFIG.locales[localeIndex];
            locale.setLocale(localeName);
			$scope.localeCache[localeName] = {};

			function next() {
				bundleIndex++;
				if (bundleIndex === CONFIG.bundles.length) {
					loadBundles(localeIndex + 1, cb);
				}
			}

			angular.forEach(CONFIG.bundles, function (bundleName) {
				locale.$$bundleReady(bundleName).then(function (bundle) {
					$scope.localeCache[localeName][bundleName] = bundle;
					next();
				}, function () {
					console.error("Failed to find bundle: " + bundleName);
					next();
				});
			});
		}

		function forLocales (cb) {
			angular.forEach(Object.keys($scope.localeCache).sort(), function (locale) {
				cb($scope.localeCache[locale], locale);
			});
		}

		function forBundles (bundles, cb) {
			angular.forEach(Object.keys(bundles).sort(), cb);
		}

		loadBundles(0, function () {
			var bundleNames = {},
				rowData = {},
				headers = [];

			headers.push({
				headerName: 'Bundle',
				field: 'bundleKey',
				editable: true,
				onCellValueChanged: function (e) {
					forLocales(function (bundles, localeName) {
						bundles[e.data.bundle][e.newValue] = bundles[e.data.bundle][e.oldValue];
						delete bundles[e.data.bundle][e.oldValue];
					});
				}
			});
			forLocales(function (bundles, localeName) {
				headers.push({
					headerName: localeName,
					field: localeName,
					editable: true,
					onCellValueChanged: function (e) {
						delete bundles[e.data.bundle][e.data.bundleKey];
						bundles[e.data.bundle][e.data.bundleKey] = e.newValue;
					}
				});
				forBundles(bundles, function (bundleName) {
					bundleNames[bundleName] = 1;
				});
			});
			forLocales(function (bundles, localeName) {
				forBundles(bundles, function (bundleName) {
					angular.forEach(bundles[bundleName], function (message, key) {
						var name = bundleName + '.' + key;
						if (!rowData[name]) {
							rowData[name] = {
								bundle: bundleName,
								bundleKey: key,
							};
						}
						rowData[name][localeName] = message;
					});
				});
			});
			$scope.bundleNames = Object.keys(bundleNames);

			$scope.gridOptions.api.setColumnDefs(headers);
			$scope.gridOptions.api.setRowData(Object.keys(rowData).map(function (key) {
				return rowData[key];
			}));
			$scope.gridOptions.api.refreshView();
		});

		var entry = $interpolate('"{{ key }}":"{{ value }}"');

		function stringify (o) {
			var output = [];
			Object.keys(o).sort().forEach(function (key) {
				output.push(entry({
					key: key,
					value: o[key].replace(/"/g, '\\\"'),
				}));
			});
			return "{" + output.join() + "}";
		}

		$scope.export = function ($event) {
			var zip = new JSZip(),
				date = moment.utc().format('YYYY-MM-DDTHH_mm_00'),
			    base = zip.folder("languages_" + date);

			forLocales(function (bundles, localeName) {
				var localeFolder = base.folder(localeName);
				forBundles(bundles, function (bundleName) {
					var data = stringify(bundles[bundleName]);
					localeFolder.file(bundleName + ".lang.json", js_beautify(data, {

					}));
				});
			});
			download(zip.generate({type:"blob"}), "languages_" + date + ".zip", "application/zip");
		};
	});
<commit_msg>feat(app): Fix the zip files unix permissions<commit_after>var params;
function getParams (key) {
	if (!params) {
		params = {};
		var entries = window.location.search.substr(1).split('&');
		entries.forEach(function (entry) {
			entry = entry.split('=');
			if (entry[0]) {
				if (!entry[1]) {
					entry[1] = '';
				}
				params[entry[0]] = entry[1];
			}
		});
	}
	return params[key];
}

var CONFIG = {
	locales: [
		'en-US',
		'fr-FR',
	],
	bundles: [
		'accounts',
		'daysOfWeek',
		'profile',
		'activation',
		'devices',
		'registration',
		'adFormats',
		'errorPage',
		'stripe',
		'ads',
		'errors',
		'tactics',
		'campaigns',
		'invoices',
		'users',
		'common',
		'navbar',
		'widgets',
		'days',
		'payments',
	]
};

angular.module('myApp', [
		'ngLocalize',
		'ngLocalize.Config',
		'ngLocalize.InstalledLanguages',
		'agGrid',
	])
    .value('localeSupported', CONFIG.locales)
    .value('localeConf', {
        basePath: getParams('basePath'),
        defaultLocale: CONFIG.locales[0],
        sharedDictionary: 'common',
        fileExtension: '.lang.json',
        persistSelection: false,
        cookieName: 'COOKIE_LOCALE_LANG',
        observableAttrs: new RegExp('^data-(?!ng-|i18n)'),
        delimiter: '::'
    })
	.controller('myApp', function ($q, $timeout, $scope, $window, $interpolate, localeConf, locale) {
		var downloadjs = $window.download;

		$window.onbeforeunload = function(e) {
		  return 'All work will be lost!!!';
		};

        $($window.document.body).keydown(function (e) {
            var elm = e.target.nodeName.toLowerCase();
            if (e.which == 8 && elm !== 'input' && elm  !== 'textarea') {
                e.preventDefault();
            }
            // stopping event bubbling up the DOM tree..
            e.stopPropagation();
        });

		$scope.localeCache = {};

		$scope.errors = [];

		$scope.localeConf = localeConf;

		$scope.locales = CONFIG.locales.slice(1);
		$scope.selectedLocale = $scope.locales[0];
		$scope.bundles = CONFIG.bundles;

		$scope.gridOptions = {
			singleClickEdit: true,
	        pinnedColumnCount: 1,
	        enableColResize: true,
	        groupUseEntireRow: true,
	        groupKeys: [
	        	'bundle'
	        ],
	        groupDefaultExpanded: true,
		};

		// load everything into memory;
		function loadBundles (localeIndex, cb) {
			var bundleIndex = 0;
			if (!CONFIG.locales[localeIndex]) {
				(cb || angular.noop)();
				return;
			}
			var localeName = CONFIG.locales[localeIndex];
            locale.setLocale(localeName);
			$scope.localeCache[localeName] = {};

			function next() {
				bundleIndex++;
				if (bundleIndex === CONFIG.bundles.length) {
					loadBundles(localeIndex + 1, cb);
				}
			}

			angular.forEach(CONFIG.bundles, function (bundleName) {
				locale.$$bundleReady(bundleName).then(function (bundle) {
					$scope.localeCache[localeName][bundleName] = bundle;
					next();
				}, function () {
					console.error("Failed to find bundle: " + bundleName);
					next();
				});
			});
		}

		function forLocales (cb) {
			angular.forEach(Object.keys($scope.localeCache).sort(), function (locale) {
				cb($scope.localeCache[locale], locale);
			});
		}

		function forBundles (bundles, cb) {
			angular.forEach(Object.keys(bundles).sort(), cb);
		}

		loadBundles(0, function () {
			var bundleNames = {},
				rowData = {},
				headers = [];

			headers.push({
				headerName: 'Bundle',
				field: 'bundleKey',
				editable: true,
				onCellValueChanged: function (e) {
					forLocales(function (bundles, localeName) {
						bundles[e.data.bundle][e.newValue] = bundles[e.data.bundle][e.oldValue];
						delete bundles[e.data.bundle][e.oldValue];
					});
				}
			});
			forLocales(function (bundles, localeName) {
				headers.push({
					headerName: localeName,
					field: localeName,
					editable: true,
					onCellValueChanged: function (e) {
						delete bundles[e.data.bundle][e.data.bundleKey];
						bundles[e.data.bundle][e.data.bundleKey] = e.newValue;
					}
				});
				forBundles(bundles, function (bundleName) {
					bundleNames[bundleName] = 1;
				});
			});
			forLocales(function (bundles, localeName) {
				forBundles(bundles, function (bundleName) {
					angular.forEach(bundles[bundleName], function (message, key) {
						var name = bundleName + '.' + key;
						if (!rowData[name]) {
							rowData[name] = {
								bundle: bundleName,
								bundleKey: key,
							};
						}
						rowData[name][localeName] = message;
					});
				});
			});
			$scope.bundleNames = Object.keys(bundleNames);

			$scope.gridOptions.api.setColumnDefs(headers);
			$scope.gridOptions.api.setRowData(Object.keys(rowData).map(function (key) {
				return rowData[key];
			}));
			$scope.gridOptions.api.refreshView();
		});

		var entry = $interpolate('"{{ key }}":"{{ value }}"');

		function stringify (o) {
			var output = [];
			Object.keys(o).sort().forEach(function (key) {
				output.push(entry({
					key: key,
					value: o[key].replace(/"/g, '\\\"'),
				}));
			});
			return "{" + output.join() + "}";
		}

		$scope.export = function ($event) {
			var zip = new JSZip(),
				date = moment.utc().format('YYYY-MM-DDTHH_mm_00'),
			    base = zip.folder("languages_" + date),
			    beautifyOpts = {},
			    fileOpts = {
					unixPermissions: "644"
				};

			forLocales(function (bundles, localeName) {
				var localeFolder = base.folder(localeName);
				forBundles(bundles, function (bundleName) {
					var data = stringify(bundles[bundleName]);
					localeFolder.file(bundleName + ".lang.json", js_beautify(data, beautifyOpts), fileOpts);
				});
			});
			download(zip.generate({type:"blob"}), "languages_" + date + ".zip", "application/zip");
		};
	});
<|endoftext|>