<commit_before>var Express = require('express');
var express = Express();
var http = require('http');
var server = http.Server(express);
var WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var exec = require('child_process').exec;
var fs = require('fs');
var viewAccountName = "elijahparker";
var CLIENT_SERVER_PORT = 80;
var CLIENT_WS_PORT = 8101;

var wss = new WebSocketServer({
    port: CLIENT_WS_PORT
});

var EventEmitter = require("events").EventEmitter;

var app = new EventEmitter();
app.remoteEnabled = false;

express.use(Express.static('/home/view/current/frontend/www'));

express.get('/socket/address', function(req, res) {
    var host = req.headers.host;
    var domain = host.split(':')[0];
    res.send({
        address: 'ws://' + domain + ':' + CLIENT_WS_PORT,
        server: 'local'
    });
});

var viewId = null;

wss.broadcast = function broadcast(data) {
    wss.clients.forEach(function each(client) {
        //console.log("client:", client);
        try {
            if (client) client.send(data);
        } catch (err) {
            console.log("broadcast error:", err);
        }
    });
};

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        //console.log('received: %s', message);
        receive_message(message, ws);
    });
});

app.remote = false;
app.authCode = null;
var wsRemote;
var remotePingHandle = null;

function connectRemote() {
    if (app.remote || !app.remoteEnabled) return;
    console.log("connecting to view.tl");
    wsRemote = new WebSocket('ws://incoming.view.tl/socket/device', {
        headers: {
            'x-view-id': viewId
        }
    });

    wsRemote.on('message', function incoming(message) {
        //if (message.type != "pong") console.log('remote: %s', message);
        if(app.remote) {
            receive_message(message, wsRemote);
        } else {
            try {
                var msg = JSON.parse(message);
                if(msg.connected) {
                    app.remote = true;
                    app.authCode = null;
                    app.emit('auth-complete', msg.email);
                    app.emit('connected', true);
                    console.log("Connected to view.tl");
                    remotePingHandle = setInterval(function() {
                        send_message('ping', null, wsRemote);
                    }, 10000);
                    sendLogs();
                } else if(msg.code) {
                    app.authCode = msg.code;
                    app.emit('auth-required', app.authCode);
                }
            } catch (err) {
                console.log("Error while parsing message:", message, err);
                return;
            }
        }
    });

    wsRemote.once('open', function() {
    });

    wsRemote.once('close', function() {
        if (remotePingHandle) clearInterval(remotePingHandle);
        remotePingHandle = null;
        console.log("Disconnected from view.tl");
        app.emit('connected', false);
        app.remote = false;
        setTimeout(connectRemote, 5000);
    });

    wsRemote.once('error', function() {
        if (remotePingHandle) clearInterval(remotePingHandle);
        remotePingHandle = null;
        console.log("Disconnected from view.tl");
        app.emit('connected', false);
        app.remote = false;
        setTimeout(connectRemote, 5000);
    });
}

app.serial = "unknown";
// get cpu serial number as unique id for view device
exec('cat /proc/cpuinfo', function(error, stdout, stderr) {
    lines = stdout.split('\n');
    for(var i = 0; i < lines.length; i++) {
        if(lines[i].indexOf('Serial') === 0) {
            var matches = lines[i].match(/: ([0-9a-f]+)/i);
            if(matches.length > 1) {
                viewId = matches[1];
                console.log("VIEW_ID:", viewId);
                app.serial = viewId;
                connectRemote();
            }
        }
    }
});

function closeApp() {
    app.remoteEnabled = false;
    closeHttpServer();
    if(wsRemote && wsRemote.destroy) {
        wsRemote.close();
    }
    wss.clients.forEach(function (client) {
        try {
            if (client && client.close) client.close();
        } catch (err) {
            console.log("error closing websocket:", err);
        }
    });
}

function sendLog(logfile, logname, callback) {
    if(app.remote) {
        console.log("Reading", logfile);
        fs.readFile(logfile, function(err, file) {
            if(!err) {
                if(file) {
                    console.log("sending log file to proxy: ", logfile);
                    var obj = {
                        logname: logname,
                        bzip2: file.toString('base64')
                    }
                    send_message('log', obj, wsRemote, function(err2) {
                        if(err2) {
                            console.log("error sending log via ws:", err2);
                            callback(err2);
                        } else {
                            callback(null);
                        }
                    });
                } else {
                    console.log("empty log file, continuing anyway");
                    callback(null);
                }
            } else {
                console.log("error sending log: ", err);
                callback(null);
            }
        });
    } else {
        callback(true);
    }
}

function sendLogs(callback, uploaded) {
    if(!uploaded) uploaded = 0;
    if(app.remote) {
        console.log("Checking for logs to upload...", uploaded);
        var logs = null;
        try {
            logs = fs.readdirSync("/home/view/logsForUpload");
            logs = logs.filter(function(log) {
                return log.match(/^(log|TL)/) ? true : false;
            });
        } catch(e) {
            logs = null;
        }

        if(logs && logs.length > 0) {
            var nextLogName = logs.pop();
            var nextLog = "/home/view/logsForUpload/" + nextLogName;
            sendLog(nextLog, nextLogName, function(err) {
                if(!err) {
                    fs.unlink(nextLog, function() {
                        uploaded++;
                        setTimeout(function() {
                            sendLogs(callback, uploaded);
                        }, 15 * 1000);
                    });
                } else {
                    console.log("log upload failed");
                    callback && callback("failed to upload log");
                }
            });
        } else {
            console.log("log uploads complete (" + uploaded + ")");
            callback && callback(null, uploaded);
            if(uploaded > 0) app.emit('logs-uploaded', uploaded);
        }
    } else {
        callback && callback("not connected");
    }
}

function send_message(type, object, socket, callback) {
    if (!object) object = {};
    if (typeof(type) === "string") {
        object.type = type;
    } else if (typeof(type) === "object" && type.type) {
        object = type;
    }

    var msg_string;
    try {
        msg_string = JSON.stringify(object);
    } catch (err) {
        console.log("Error encoding data to send:", err);
        return;
    }
    try {
        if (socket) {
            socket.send(msg_string, callback);
        } else {
            wss.broadcast(msg_string);
            if (app.remote) wsRemote.send(msg_string);
        }
    } catch (err) {
        console.log("Error sending message:", err);
        return;
    }
}

function receive_message(msg_string, socket) {
    try {
    	var buildReply = function(nMsg, nSocket) {
    		return function(type, object, callback) {
    			if(!object) object = {};
    			object.ack = nMsg.ack;
    			object._cbId = nMsg._cbId;

                send_message(type, object, nSocket, callback);
    		}
    	}

        var msg = JSON.parse(msg_string);
        if (!msg || !msg.type) {
            throw "invalid message: no type set";
        } else if (msg.type == "ping") {
            send_message('pong', {}, socket);
        } else if (msg.type == "pong") {
            // ignoring...
        } else {
        	msg.reply = buildReply(msg, socket);
        	app.emit("message", msg);
        }
    } catch (err) {
        console.log("Error while parsing message:", msg_string, err);
        return;
    }
}

app.enableRemote = function() {
    app.remoteEnabled = true;
    connectRemote();
}

app.disableRemote = function() {
    app.remoteEnabled = false;
    if(wsRemote && wsRemote.destroy) {
        wsRemote.close();
    }
    app.emit('connected', false);
}

app.send = send_message;
app.sendLogs = sendLogs;
app.close = closeApp;

var httpServer = server.listen(CLIENT_SERVER_PORT, function() {
    console.log('listening on *:' + CLIENT_SERVER_PORT);
});

var sockets = {}, nextSocketId = 0;
httpServer.on('connection', function (socket) {
  // Add a newly connected socket
  var socketId = nextSocketId++;
  sockets[socketId] = socket;
  console.log('socket', socketId, 'opened');

  // Remove the socket when it closes
  socket.on('close', function () {
    console.log('socket', socketId, 'closed');
    delete sockets[socketId];
  });

  // Extend socket lifetime for demo purposes
  socket.setTimeout(4000);
});

function closeHttpServer() {
    // Close the server
    httpServer.close(function () { console.log('Server closed!'); });
    // Destroy all open sockets
    for (var socketId in sockets) {
        console.log('socket', socketId, 'destroyed');
        sockets[socketId].destroy();
    }
}

module.exports = app;<commit_msg>fix for log upload<commit_after>var Express = require('express');
var express = Express();
var http = require('http');
var server = http.Server(express);
var WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var exec = require('child_process').exec;
var fs = require('fs');
var viewAccountName = "elijahparker";
var CLIENT_SERVER_PORT = 80;
var CLIENT_WS_PORT = 8101;

var wss = new WebSocketServer({
    port: CLIENT_WS_PORT
});

var EventEmitter = require("events").EventEmitter;

var app = new EventEmitter();
app.remoteEnabled = false;

express.use(Express.static('/home/view/current/frontend/www'));

express.get('/socket/address', function(req, res) {
    var host = req.headers.host;
    var domain = host.split(':')[0];
    res.send({
        address: 'ws://' + domain + ':' + CLIENT_WS_PORT,
        server: 'local'
    });
});

var viewId = null;

wss.broadcast = function broadcast(data) {
    wss.clients.forEach(function each(client) {
        //console.log("client:", client);
        try {
            if (client) client.send(data);
        } catch (err) {
            console.log("broadcast error:", err);
        }
    });
};

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        //console.log('received: %s', message);
        receive_message(message, ws);
    });
});

app.remote = false;
app.authCode = null;
var wsRemote;
var remotePingHandle = null;

function connectRemote() {
    if (app.remote || !app.remoteEnabled) return;
    console.log("connecting to view.tl");
    wsRemote = new WebSocket('ws://incoming.view.tl/socket/device', {
        headers: {
            'x-view-id': viewId
        }
    });

    wsRemote.on('message', function incoming(message) {
        //if (message.type != "pong") console.log('remote: %s', message);
        if(app.remote) {
            receive_message(message, wsRemote);
        } else {
            try {
                var msg = JSON.parse(message);
                if(msg.connected) {
                    app.remote = true;
                    app.authCode = null;
                    app.emit('auth-complete', msg.email);
                    app.emit('connected', true);
                    console.log("Connected to view.tl");
                    remotePingHandle = setInterval(function() {
                        send_message('ping', null, wsRemote);
                    }, 10000);
                    sendLogs();
                } else if(msg.code) {
                    app.authCode = msg.code;
                    app.emit('auth-required', app.authCode);
                }
            } catch (err) {
                console.log("Error while parsing message:", message, err);
                return;
            }
        }
    });

    wsRemote.once('open', function() {
    });

    wsRemote.once('close', function() {
        if (remotePingHandle) clearInterval(remotePingHandle);
        remotePingHandle = null;
        console.log("Disconnected from view.tl");
        app.emit('connected', false);
        app.remote = false;
        setTimeout(connectRemote, 5000);
    });

    wsRemote.once('error', function() {
        if (remotePingHandle) clearInterval(remotePingHandle);
        remotePingHandle = null;
        console.log("Disconnected from view.tl");
        app.emit('connected', false);
        app.remote = false;
        setTimeout(connectRemote, 5000);
    });
}

app.serial = "unknown";
// get cpu serial number as unique id for view device
exec('cat /proc/cpuinfo', function(error, stdout, stderr) {
    lines = stdout.split('\n');
    for(var i = 0; i < lines.length; i++) {
        if(lines[i].indexOf('Serial') === 0) {
            var matches = lines[i].match(/: ([0-9a-f]+)/i);
            if(matches.length > 1) {
                viewId = matches[1];
                console.log("VIEW_ID:", viewId);
                app.serial = viewId;
                connectRemote();
            }
        }
    }
});

function closeApp() {
    app.remoteEnabled = false;
    closeHttpServer();
    if(wsRemote && wsRemote.destroy) {
        wsRemote.close();
    }
    wss.clients.forEach(function (client) {
        try {
            if (client && client.close) client.close();
        } catch (err) {
            console.log("error closing websocket:", err);
        }
    });
}

function sendLog(logfile, logname, callback) {
    if(app.remote) {
        console.log("Reading", logfile);
        fs.readFile(logfile, function(err, file) {
            if(!err) {
                if(file) {
                    console.log("sending log file to proxy: ", logfile);
                    var obj = {
                        logname: logname,
                        bzip2: file.toString('base64')
                    }
                    send_message('log', obj, wsRemote, function(err2) {
                        if(err2) {
                            console.log("error sending log via ws:", err2);
                            callback(err2);
                        } else {
                            callback(null);
                        }
                    });
                } else {
                    console.log("empty log file, continuing anyway");
                    callback(null);
                }
            } else {
                console.log("error sending log: ", err);
                callback(null);
            }
        });
    } else {
        callback(true);
    }
}

function sendLogs(callback, uploaded) {
    if(!uploaded) uploaded = 0;
    if(app.remote) {
        console.log("Checking for logs to upload...", uploaded);
        var logs = null;
        try {
            logs = fs.readdirSync("/home/view/logsForUpload");
            logs = logs.filter(function(log) {
                return log.match(/^(log|TL|view-)/) ? true : false;
            });
        } catch(e) {
            logs = null;
        }

        if(logs && logs.length > 0) {
            var nextLogName = logs.pop();
            var nextLog = "/home/view/logsForUpload/" + nextLogName;
            sendLog(nextLog, nextLogName, function(err) {
                if(!err) {
                    fs.unlink(nextLog, function() {
                        uploaded++;
                        setTimeout(function() {
                            sendLogs(callback, uploaded);
                        }, 15 * 1000);
                    });
                } else {
                    console.log("log upload failed");
                    callback && callback("failed to upload log");
                }
            });
        } else {
            console.log("log uploads complete (" + uploaded + ")");
            callback && callback(null, uploaded);
            if(uploaded > 0) app.emit('logs-uploaded', uploaded);
        }
    } else {
        callback && callback("not connected");
    }
}

function send_message(type, object, socket, callback) {
    if (!object) object = {};
    if (typeof(type) === "string") {
        object.type = type;
    } else if (typeof(type) === "object" && type.type) {
        object = type;
    }

    var msg_string;
    try {
        msg_string = JSON.stringify(object);
    } catch (err) {
        console.log("Error encoding data to send:", err);
        return;
    }
    try {
        if (socket) {
            socket.send(msg_string, callback);
        } else {
            wss.broadcast(msg_string);
            if (app.remote) wsRemote.send(msg_string);
        }
    } catch (err) {
        console.log("Error sending message:", err);
        return;
    }
}

function receive_message(msg_string, socket) {
    try {
    	var buildReply = function(nMsg, nSocket) {
    		return function(type, object, callback) {
    			if(!object) object = {};
    			object.ack = nMsg.ack;
    			object._cbId = nMsg._cbId;

                send_message(type, object, nSocket, callback);
    		}
    	}

        var msg = JSON.parse(msg_string);
        if (!msg || !msg.type) {
            throw "invalid message: no type set";
        } else if (msg.type == "ping") {
            send_message('pong', {}, socket);
        } else if (msg.type == "pong") {
            // ignoring...
        } else {
        	msg.reply = buildReply(msg, socket);
        	app.emit("message", msg);
        }
    } catch (err) {
        console.log("Error while parsing message:", msg_string, err);
        return;
    }
}

app.enableRemote = function() {
    app.remoteEnabled = true;
    connectRemote();
}

app.disableRemote = function() {
    app.remoteEnabled = false;
    if(wsRemote && wsRemote.destroy) {
        wsRemote.close();
    }
    app.emit('connected', false);
}

app.send = send_message;
app.sendLogs = sendLogs;
app.close = closeApp;

var httpServer = server.listen(CLIENT_SERVER_PORT, function() {
    console.log('listening on *:' + CLIENT_SERVER_PORT);
});

var sockets = {}, nextSocketId = 0;
httpServer.on('connection', function (socket) {
  // Add a newly connected socket
  var socketId = nextSocketId++;
  sockets[socketId] = socket;
  console.log('socket', socketId, 'opened');

  // Remove the socket when it closes
  socket.on('close', function () {
    console.log('socket', socketId, 'closed');
    delete sockets[socketId];
  });

  // Extend socket lifetime for demo purposes
  socket.setTimeout(4000);
});

function closeHttpServer() {
    // Close the server
    httpServer.close(function () { console.log('Server closed!'); });
    // Destroy all open sockets
    for (var socketId in sockets) {
        console.log('socket', socketId, 'destroyed');
        sockets[socketId].destroy();
    }
}

module.exports = app;<|endoftext|>


<commit_before>/*
 * grunt-csso
 * http://github.com/t32k/grunt-csso
 *
 * Copyright (c) 2013 - 2014 Koji Ishimoto
 * Licensed under the MIT license.
 */
'use strict';

module.exports = function (grunt) {

  var fs = require('fs');
  var path = require('path');

  var csso = require('csso');
  var chalk = require('chalk');
  var maxmin = require('maxmin');

  grunt.registerMultiTask('csso', 'Minify CSS files with CSSO.', function () {

    var options = this.options({
      restructure: true,
      banner: '',
      report: false
    });

    // Process banner.
    var banner = grunt.template.process(options.banner);

    this.files.forEach(function (file) {

      // 1. check existence
      // 2. check file extension
      // 3. load and concatenate css files
      var original = file.src.filter(function (p) {
        if (!fs.existsSync(p)) {
          grunt.log.warn('Source file "' + p + '" is not found.');
          return false;
        } else {
          return true;
        }
      }).filter(function (p) {
        if (path.extname(p) !== '.css') {
          grunt.log.warn('Source file "' + p + '" is not css.');
          return false;
        } else {
          return true;
        }
      }).map(function (p) {
        return fs.readFileSync(p, {
          encoding: 'utf8'
        });
      }).join(grunt.util.normalizelf(grunt.util.linefeed));

      // reverse flag
      var proceed = csso.justDoIt(original, !options.restructure);

      if (proceed.length === 0) {
        grunt.log.warn('Destination is not created because minified CSS was empty.');
      } else {
        // add banner.
        proceed = banner + proceed;

        grunt.file.write(file.dest, proceed);
        grunt.log.writeln('File ' + chalk.green(file.dest) + ' created.');
        if (options.report) {
          grunt.log.writeln(maxmin(original, proceed, options.report === 'gzip'));
        }
      }
    });
  });
};<commit_msg>maxmin report refactored to follow general convention<commit_after>/*
 * grunt-csso
 * http://github.com/t32k/grunt-csso
 *
 * Copyright (c) 2013 - 2014 Koji Ishimoto
 * Licensed under the MIT license.
 */
'use strict';

module.exports = function (grunt) {

  var fs = require('fs');
  var path = require('path');

  var csso = require('csso');
  var chalk = require('chalk');
  var maxmin = require('maxmin');

  grunt.registerMultiTask('csso', 'Minify CSS files with CSSO.', function () {

    var options = this.options({
      restructure: true,
      banner: '',
      report: false
    });

    // Process banner.
    var banner = grunt.template.process(options.banner);

    this.files.forEach(function (file) {

      // 1. check existence
      // 2. check file extension
      // 3. load and concatenate css files
      var original = file.src.filter(function (p) {
        if (!fs.existsSync(p)) {
          grunt.log.warn('Source file "' + p + '" is not found.');
          return false;
        } else {
          return true;
        }
      }).filter(function (p) {
        if (path.extname(p) !== '.css') {
          grunt.log.warn('Source file "' + p + '" is not css.');
          return false;
        } else {
          return true;
        }
      }).map(function (p) {
        return fs.readFileSync(p, {
          encoding: 'utf8'
        });
      }).join(grunt.util.normalizelf(grunt.util.linefeed));

      // reverse flag
      var proceed = csso.justDoIt(original, !options.restructure);

      if (proceed.length === 0) {
        grunt.log.warn('Destination is not created because minified CSS was empty.');
      } else {
        // add banner.
        proceed = banner + proceed;

        grunt.file.write(file.dest, proceed);
        if (options.report) {
          var report =(maxmin(original, proceed, options.report === 'gzip'));
        }
        grunt.log.writeln('File ' + chalk.cyan(file.dest) + ' created' + ((report) ? ': ' + report : '.'));
      }
    });
  });
};
<|endoftext|>


<commit_before>const gulp = require('gulp')
const $ = require('gulp-load-plugins')()
const fs = require('fs')
const {join} = require('path')
const mkdirp = require('mkdirp')
const {series, each} = require('async')
const del = require('del')

const log = $.util.log

function fail (msg) {
  log($.util.colors.red(msg))
  process.exit(1)
}

const RELEASE_PATH = join(__dirname, '..', 'releases')
const SITE_PATH = join(__dirname, '..', 'site', 'public', 'releases')
const DIST_PATH = join(__dirname, '..', 'dists')

function getVersion (type, done) {
  const p = join(DIST_PATH, type, 'current')

  fs.readFile(p, (err, version) => {
    if (err) return done(err)
    done(null, version.toString().trim())
  })
}

function writeData (type, version, done) {
  const dataPath = join(RELEASE_PATH, type, version, 'dist.json')
  const data = JSON.parse(fs.readFileSync(dataPath).toString())

  const dataTargetPath = join(SITE_PATH, type)
  series([
    mkdirp.bind(mkdirp, dataTargetPath),
    fs.writeFile.bind(fs, join(dataTargetPath, '_data.json'), JSON.stringify(data, null, 2)),
    fs.writeFile.bind(fs, join(dataTargetPath, 'index.md'), data.description)
  ], done)
}

function writeSiteFiles (type, done) {
  fs.stat(join(RELEASE_PATH, type), (err, stats) => {
    if (err) return done(err)

    if (stats.isDirectory()) {
      getVersion(type, (err, version) => {
        if (err) return done(err)

        writeData(type, version, done)
      })
    } else {
      done()
    }
  })
}

gulp.task('clean:release:site', () => {
  return del([
    './releases/*.html',
    './releases/css',
    './releases/build',
    './releases/releases'
  ])
})

gulp.task('dist', ['clean:release:site'], done => {
  fs.readdir(RELEASE_PATH, (err, types) => {
    if (err) return fail(err.msg)

    each(types, writeSiteFiles, done)
  })
})
<commit_msg>fix(site): Ignore fonts directory<commit_after>const gulp = require('gulp')
const $ = require('gulp-load-plugins')()
const fs = require('fs')
const {join} = require('path')
const mkdirp = require('mkdirp')
const {series, each} = require('async')
const del = require('del')
const _ = require('lodash')

const log = $.util.log

function fail (msg) {
  log($.util.colors.red(msg))
  process.exit(1)
}

const RELEASE_PATH = join(__dirname, '..', 'releases')
const SITE_PATH = join(__dirname, '..', 'site', 'public', 'releases')
const DIST_PATH = join(__dirname, '..', 'dists')

function getVersion (type, done) {
  const p = join(DIST_PATH, type, 'current')

  fs.readFile(p, (err, version) => {
    if (err) return done(err)
    done(null, version.toString().trim())
  })
}

function writeData (type, version, done) {
  const dataPath = join(RELEASE_PATH, type, version, 'dist.json')
  const data = JSON.parse(fs.readFileSync(dataPath).toString())

  const dataTargetPath = join(SITE_PATH, type)
  series([
    mkdirp.bind(mkdirp, dataTargetPath),
    fs.writeFile.bind(fs, join(dataTargetPath, '_data.json'), JSON.stringify(data, null, 2)),
    fs.writeFile.bind(fs, join(dataTargetPath, 'index.md'), data.description)
  ], done)
}

function writeSiteFiles (type, done) {
  fs.stat(join(RELEASE_PATH, type), (err, stats) => {
    if (err) return done(err)

    if (stats.isDirectory() && !_.contains(['fonts'], type)) {
      getVersion(type, (err, version) => {
        if (err) return done(err)

        writeData(type, version, done)
      })
    } else {
      done()
    }
  })
}

gulp.task('clean:release:site', () => {
  return del([
    './releases/*.html',
    './releases/css',
    './releases/build',
    './releases/releases'
  ])
})

gulp.task('dist', ['clean:release:site'], done => {
  fs.readdir(RELEASE_PATH, (err, types) => {
    if (err) return fail(err.msg)

    each(types, writeSiteFiles, done)
  })
})
<|endoftext|>


<commit_before>/*
 * grunt-docs
 * https://github.com/shama/grunt-docs
 *
 * Copyright (c) 2013 Kyle Robinson Young
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  'use strict';

  var docpad = require('docpad');

  grunt.registerTask('docs', 'Compile with DocPad', function() {
    var done = this.async();
    var config = grunt.config(this.name || 'docs');
    var srcPath = config.srcPath || 'src';

    // To allow paths config to use patterns
    Object.keys(config).forEach(function(key) {
      if (key.slice(-5) === 'Paths') {
        var options = {};

        switch (key) {
        case 'documentsPaths':
        case 'filesPaths':
        case 'layoutsPaths':
          options.cwd = srcPath;
          break;
        }

        config[key] = grunt.file.expand(options, config[key]);
      }
    });

    docpad.createInstance(config, function(err, inst) {
      inst.action('generate', function(err) {
        if (err) { return grunt.warn(err); }
        done();
      });
    });
  });

};
<commit_msg>nitpick style<commit_after>/*
 * grunt-docs
 * https://github.com/shama/grunt-docs
 *
 * Copyright (c) 2013 Kyle Robinson Young
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  'use strict';

  var docpad = require('docpad');

  grunt.registerTask('docs', 'Compile with DocPad', function() {
    var done = this.async();
    var config = grunt.config(this.name || 'docs');
    var srcPath = config.srcPath || 'src';

    // To allow paths config to use patterns
    Object.keys(config).forEach(function(key) {
      if (key.slice(-5) === 'Paths') {
        var options = {};

        switch (key) {
          case 'documentsPaths':
          case 'filesPaths':
          case 'layoutsPaths':
            options.cwd = srcPath;
            break;
        }

        config[key] = grunt.file.expand(options, config[key]);
      }
    });

    docpad.createInstance(config, function(err, inst) {
      inst.action('generate', function(err) {
        if (err) { return grunt.warn(err); }
        done();
      });
    });
  });

};
<|endoftext|>


<commit_before>/*
 * grunt-nose
 * https://github.com/tarjei/grunt-nose
 *
 * Copyright (c) 2013 Tarjei Husøy
 * Licensed under the Apache, 2.0 licenses.
 */

'use strict';

module.exports = function(grunt) {

  var path = require('path');

  var getVirtualenvActivationCode = function(virtualenv){
      var activateThisPath;
      var activeThisPathAlternatives = [
        // *nix activate_this path:
        path.join(virtualenv, 'bin', 'activate_this.py'),
        // windows style path:
        path.join(virtualenv, 'Scripts', 'activate_this.py'),
      ];
      grunt.util._.forEach(activeThisPathAlternatives, function(path){
        if (grunt.file.exists(path)){
          activateThisPath = path;
          return false; // stops iteration
        }
      });
      if (activateThisPath === undefined){
        grunt.fail.warn('Tried to activate virtualenv "' + virtualenv + '", but did not ' +
          'find the file "activate_this.py" required for activation, after trying ' +
          'these locations:\n' + activeThisPathAlternatives.join("\n") +
          '\nMake sure this file exist at either of these locations, and try again.');
      }
      var activationCode = 'execfile(r"' + activateThisPath + '", ' +
        'dict(__file__=r"' + activateThisPath + '")); ';

      return activationCode;
  };

  grunt.registerMultiTask('nose', 'Run python unit tests with nose.', function() {
    var done = this.async();

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({});

    // Fail if the 'where' option is given
    if (options['where'] !== undefined){
      grunt.fail.warn("Dont't specify the 'where' option in the options, use the task src property instead!");
    }

    // Arguments to be passed along to nose
    var args = [];

    // Extract options not to be passed along to nose
    var virtualenv = 'pass;';
    if (options.virtualenv){
      virtualenv = getVirtualenvActivationCode(options.virtualenv);
      grunt.log.verbose.writeln("Using virtualenv at " + options.virtualenv);
      delete options.virtualenv;
    }

    // Set the nose 'where' option for each of the files specified for the task
    this.filesSrc.forEach(function(filepath){
      args.push('--where=' + path.join(process.cwd(), filepath));
    });

    for (var prop in options){
      if (!options.hasOwnProperty(prop)){
        continue;
      }

      var cli_arg = '--' + prop;
      while (cli_arg.indexOf("_") !== -1){
        cli_arg = cli_arg.replace('_', '-');
      }

      // If the property is not a flag, add the desired option value
      // We count the option as a flag if the property === true
      // Note: Specifying false as a value will not exclude the flag, omit the option entirely to do so
      if (options[prop] !== true){

        // If the option value is a file path, make sure it's relative the the process cwd, since
        // the node process is spawned with a different cwd.
        var fileOptions = [
          'config',
          'debug_log',
          'logging_config',
          'log_config',
          'cover_html_dir',
          'cover_xml_file',
          'profile_stats_file',
          'id_file',
          'xunit_file'
        ];

        // Several config files can be merged
        if (prop === 'config' && typeof options[prop] === 'Object'){
          for(var i = 0; i < options[prop].length; i++){
            var configFile = options[prop][i];
            args.push('--config=' + configFile);
          }
          continue;
        }

        // Options that create a file
        // For convenience, we will make sure to create the directory where these files
        // will be stored, since nose won't do this for us
        var createsFileOpts = [
          'debug_log',
          'cover_html_dir', // Certain that this is needed?
          'cover_xml_file',
          'profile_stats_file',
          'id_file',
          'xunit_file'
        ];

        if (fileOptions.indexOf(prop) === -1){
          cli_arg += "=" + options[prop];
        } else {
          cli_arg += "=" + path.join(process.cwd(), options[prop]);

          // Add some convenience lacking in nose, make sure to create the output directory if not present
          // Only do this for the options creating a output file
          if (createsFileOpts.indexOf(prop) !== -1){
            var targetDir = path.join(process.cwd(), path.dirname(options[prop]));
            if (!grunt.file.isDir(targetDir)){
              grunt.log.verbose.writeln("Created folder " + targetDir);
              grunt.file.mkdir(targetDir);
            }
          }
        }
      }
      args.push(cli_arg);
    }

    grunt.log.verbose.writeln("Running nose with the following args: " + args.join(", "));

    var nose = grunt.util.spawn({
      'cmd': 'python',
      'args': ['-c', virtualenv + 'import sys; sys.path.insert(0, "'+path.join(__dirname, 'lib')+'"); from nose.core import run_exit; run_exit()'].concat(args),
      'opts': {
        'cwd': process.cwd(),
        'stdio': 'inherit',
      }
    }, function(error, result, code){
      if (code === 0){
        grunt.log.ok("Python unit tests completed successfully.");
      }
      done(code === 0);
    });

  });

};
<commit_msg>Refactor bulding the arguments list to python.<commit_after>/*
 * grunt-nose
 * https://github.com/tarjei/grunt-nose
 *
 * Copyright (c) 2013 Tarjei Husøy
 * Licensed under the Apache, 2.0 licenses.
 */

'use strict';

module.exports = function(grunt) {

  var path = require('path');

  var getVirtualenvActivationCode = function(virtualenv){
      var activateThisPath;
      var activeThisPathAlternatives = [
        // *nix activate_this path:
        path.join(virtualenv, 'bin', 'activate_this.py'),
        // windows style path:
        path.join(virtualenv, 'Scripts', 'activate_this.py'),
      ];
      grunt.util._.forEach(activeThisPathAlternatives, function(path){
        if (grunt.file.exists(path)){
          activateThisPath = path;
          return false; // stops iteration
        }
      });
      if (activateThisPath === undefined){
        grunt.fail.warn('Tried to activate virtualenv "' + virtualenv + '", but did not ' +
          'find the file "activate_this.py" required for activation, after trying ' +
          'these locations:\n' + activeThisPathAlternatives.join("\n") +
          '\nMake sure this file exist at either of these locations, and try again.');
      }
      var activationCode = 'execfile(r"' + activateThisPath + '", ' +
        'dict(__file__=r"' + activateThisPath + '"))';

      return activationCode;
  };

  grunt.registerMultiTask('nose', 'Run python unit tests with nose.', function() {
    var done = this.async();

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({});

    // Fail if the 'where' option is given
    if (options['where'] !== undefined){
      grunt.fail.warn("Dont't specify the 'where' option in the options, use the task src property instead!");
    }

    // Arguments to be passed along to nose
    var args = [];

    // Extract options not to be passed along to nose
    var virtualenv = 'pass';
    if (options.virtualenv){
      virtualenv = getVirtualenvActivationCode(options.virtualenv);
      grunt.log.verbose.writeln("Using virtualenv at " + options.virtualenv);
      delete options.virtualenv;
    }

    var baseArgs = [
      '-c',
      [
        virtualenv,
        'import sys',
        'sys.path.insert(0, r"'+path.join(__dirname, 'lib')+'")',
        'from nose.core import run_exit',
        'run_exit()'
      ].join('; ')
    ];

    // Set the nose 'where' option for each of the files specified for the task
    this.filesSrc.forEach(function(filepath){
      args.push('--where=' + path.join(process.cwd(), filepath));
    });

    for (var prop in options){
      if (!options.hasOwnProperty(prop)){
        continue;
      }

      var cli_arg = '--' + prop;
      while (cli_arg.indexOf("_") !== -1){
        cli_arg = cli_arg.replace('_', '-');
      }

      // If the property is not a flag, add the desired option value
      // We count the option as a flag if the property === true
      // Note: Specifying false as a value will not exclude the flag, omit the option entirely to do so
      if (options[prop] !== true){

        // If the option value is a file path, make sure it's relative the the process cwd, since
        // the node process is spawned with a different cwd.
        var fileOptions = [
          'config',
          'debug_log',
          'logging_config',
          'log_config',
          'cover_html_dir',
          'cover_xml_file',
          'profile_stats_file',
          'id_file',
          'xunit_file'
        ];

        // Several config files can be merged
        if (prop === 'config' && typeof options[prop] === 'Object'){
          for(var i = 0; i < options[prop].length; i++){
            var configFile = options[prop][i];
            args.push('--config=' + configFile);
          }
          continue;
        }

        // Options that create a file
        // For convenience, we will make sure to create the directory where these files
        // will be stored, since nose won't do this for us
        var createsFileOpts = [
          'debug_log',
          'cover_html_dir', // Certain that this is needed?
          'cover_xml_file',
          'profile_stats_file',
          'id_file',
          'xunit_file'
        ];

        if (fileOptions.indexOf(prop) === -1){
          cli_arg += "=" + options[prop];
        } else {
          cli_arg += "=" + path.join(process.cwd(), options[prop]);

          // Add some convenience lacking in nose, make sure to create the output directory if not present
          // Only do this for the options creating a output file
          if (createsFileOpts.indexOf(prop) !== -1){
            var targetDir = path.join(process.cwd(), path.dirname(options[prop]));
            if (!grunt.file.isDir(targetDir)){
              grunt.log.verbose.writeln("Created folder " + targetDir);
              grunt.file.mkdir(targetDir);
            }
          }
        }
      }
      args.push(cli_arg);
    }

    grunt.log.verbose.writeln("Running nose with the following args: " + args.join(", "));

    var nose = grunt.util.spawn({
      'cmd': 'python',
      'args': baseArgs.concat(args),
      'opts': {
        'cwd': process.cwd(),
        'stdio': 'inherit',
      }
    }, function(error, result, code){
      if (code === 0){
        grunt.log.ok("Python unit tests completed successfully.");
      }
      done(code === 0);
    });

  });

};
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var eachAsync = require('each-async');
var assign = require('object-assign');
var sass = require('node-sass');

module.exports = function (grunt) {
	grunt.verbose.writeln('\n' + sass.info + '\n');

	grunt.registerMultiTask('sass', 'Compile Sass to CSS', function () {
		eachAsync(this.files, function (el, i, next) {
			var opts = this.options({
				precision: 10
			});

			var src = el.src[0];

			if (!src || path.basename(src)[0] === '_') {
				next();
				return;
			}

			grunt.log.writeln('Processing ' + src);

			sass.render(assign({}, opts, {
				file: src,
				outFile: el.dest
			}), function (err, res) {
				if (err) {
					grunt.log.error(err.message + '\n  ' + 'Line ' + err.line + '  Column ' + err.column + '  ' + path.relative(process.cwd(), err.file) + '\n');
					grunt.warn('');
					next(err);
					return;
				}

				grunt.file.write(el.dest, res.css);

				if (opts.sourceMap) {
					grunt.file.write(this.options.sourceMap, res.map);
				}

				next();
			});
		}.bind(this), this.async());
	});
};
<commit_msg>Added output for total files processed.<commit_after>'use strict';
var path = require('path');
var eachAsync = require('each-async');
var assign = require('object-assign');
var sass = require('node-sass');

module.exports = function (grunt) {

	grunt.verbose.writeln('\n' + sass.info + '\n');

	grunt.registerMultiTask('sass', 'Compile Sass to CSS', function () {

    var done = this.async();
    var counter = 0;

    eachAsync(this.files, function (el, i, next) {
			var opts = this.options({
				precision: 10
			});

			var src = el.src[0];

			if (!src || path.basename(src)[0] === '_') {
				next();
				return;
			}

			sass.render(assign({}, opts, {
				file: src,
				outFile: el.dest
			}), function (err, res) {
				if (err) {
					grunt.log.error(err.message + '\n  ' + 'Line ' + err.line + '  Column ' + err.column + '  ' + path.relative(process.cwd(), err.file) + '\n');
					grunt.warn('');
					next(err);
					return;
				}

				grunt.file.write(el.dest, res.css);
        counter++;

				if (opts.sourceMap) {
					grunt.file.write(this.options.sourceMap, res.map);
				}

				next();
			});
		}.bind(this), function(err) {
          grunt.log.writeln(counter === 1 ? counter + ' stylesheet processed.' : counter + ' stylesheets processed.');
          done(err);
        }
      );
	});
};
<|endoftext|>


<commit_before>"use strict";
/*
 Created by lx on 2016/11/17
 Name: Xinyu Ge
 */
const dbConnection = require("../config/mongoConnection");
const uuid = require("node-uuid");

dbConnection().then(db => {
    return db.collection("city").drop().then(function() {
        return db;
    }, function() {
        return db;
    }).then((db) => {
        return db.createCollection("city");
    }).then(function(cityCollection) {

        var createCity = (name, province, description, traffic, weather, history, culture, currency, mainImage, tag) => {
            return {
                _id: uuid.v4(),
                name: name,
                province: province,
                description: description,
                traffic: traffic,
                weather: weather,
                history: history,
                culture: culture,
                currency: currency,
                mainImage: mainImage,
                tag: tag
            }
        }

        var listOfCities = [];

        // city_1 Beijing
        var BeijingTag = ["capital", "tian'anmen"];
        var BeijingCity = createCity("Beijing", "Beijing", "Beijing Description", "Beijing Traffic", "Beijing Weather", "Beijing History", "Beijing Culture", "RMB", "Beijing Image", BeijingTag);

        // city_2 Shanghai
        var ShanghaiTag = ["Shanghai Shibohui", "Dofangmingzhu"];
        var ShanghaiCity = createCity("Shanghai", "Shanghai", "Shanghai Description", "Shanghai Traffic", "Shanghai Weather", "Shanghai History", "Shanghai Culture", "RMB", "Shanghai Image", ShanghaiTag);

        // city_3 Shenzhen
        var ShenzhenTag = ["guandong", "tequ"];
        var ShenzhenCity = createCity("Shenzhen", "Shenzhen", "Shenzhen Description", "Shenzhen Traffic", "Shenzhen Weather", "Shenzhen History", "Shenzhen Culture", "RMB", "Shenzhen Image", ShenzhenTag);

        //
        listOfCities.push(BeijingCity, ShanghaiCity, ShenzhenCity);

        return cityCollection.insertMany(listOfCities).then(() => {
            return cityCollection.find().toArray();
        });
    });
});

module.exports = router;
<commit_msg>Update seed.js<commit_after>"use strict";
/*
 Created by lx on 2016/11/17
 Name: Xinyu Ge
 */
const dbConnection = require("../config/mongoConnection");
const uuid = require("node-uuid");

dbConnection().then(db => {
    return db.collection("city").drop().then(function() {
        return db;
    }, function() {
        return db;
    }).then((db) => {
        return db.createCollection("city");
    }).then(function(cityCollection) {

        var createCity = (name, province, description, traffic, weather, history, culture, currency, mainImage, tag) => {
            return {
                _id: uuid.v4(),
                name: name,
                province: province,
                description: description,
                traffic: traffic,
                weather: weather,
                history: history,
                culture: culture,
                currency: currency,
                mainImage: mainImage,
                tag: tag
            }
        }

        var listOfCities = [];

        // city_1 Beijing
        var BeijingTag = ["capital", "tian'anmen"];
        var BeijingCity = createCity("Beijing", "Beijing", "Beijing Description", "Beijing Traffic", "Beijing Weather", "Beijing History", "Beijing Culture", "RMB", "Beijing Image", BeijingTag);

        // city_2 Shanghai
        var ShanghaiTag = ["Shanghai Shibohui", "Dofangmingzhu"];
        var ShanghaiCity = createCity("Shanghai", "Shanghai", "Shanghai Description", "Shanghai Traffic", "Shanghai Weather", "Shanghai History", "Shanghai Culture", "RMB", "Shanghai Image", ShanghaiTag);

        // city_3 Shenzhen
        var ShenzhenTag = ["guandong", "tequ"];
        var ShenzhenCity = createCity("Shenzhen", "Shenzhen", "Shenzhen Description", "Shenzhen Traffic", "Shenzhen Weather", "Shenzhen History", "Shenzhen Culture", "RMB", "Shenzhen Image", ShenzhenTag);

        //
        listOfCities.push(BeijingCity, ShanghaiCity, ShenzhenCity);

        return cityCollection.insertMany(listOfCities).then(() => {
            return cityCollection.find().toArray();
        });
    }).then((addedCity) => {
		     return sites.addSite("QianFoMountain", "N36°E117°", "JingShi road, JiNan, ShanDong", "Bus", "30￥", "6:00PM", "2016681367", "www.qianfoshan.com", "qianfoshan", "1.png", 1, ["climb","cable"],["mountain", "famous", "JiNan"], "fk_city");
	   }).then((addedSite) => {
		     return sites.addSite("DaMingLake", "N50°E120°", "MingHu road, JiNan, ShanDong", "Bus", "60￥", "6:00PM", "2016681367", "www.daminghu.com", "daminghu", "2.png", 1, ["boat","landscape"],["lake", "famous", "JiNan", "XiaYuHe"], "fk_city");
	   }).then((addedSite) => {
		     return sites.addSite("BaoTuFountain", "N45°E116°", "XiMen road, JiNan, ShanDong", "Bus", "50￥", "6:00PM", "2016681367", "www.baotuquan.com", "baotuquan", "3.png", 1, ["seal","tea"],["fountain", "famous", "JiNan"], "fk_city");
	   }).then((addedSite) => {
		     return food.addFood("BaZiRou", "bengrouganfan", "N36°E117°", "YaoShan", "20￥", "9:30PM", "18615213327", "www.bazirou.com", "4.png", 2, "fk_city");
	   }).then((addedFood) => {
		     return food.addFood("TianMo", "salty vegetable porridge", "N36°E117°", "XiaoTan", "1.5￥", "10:00AM", "18615213327", "www.tianmo.com", "5.png", 2, "fk_city");
	   }).then((addedFood) => {
		     return food.addFood("YouXuan", "fried dough", "N36°E117°", "FuRongJie", "0.5￥", "10:30PM", "18615213327", "www.youxuan.com", "6.png", 2, "fk_city");
	   }).then((added) => {
		     console.log("Done seeding database!");
		     db.close();
	   });
}), (error) => {
     console.error(error);
};

module.exports = router;
<|endoftext|>


<commit_before>var jira = function() {};
jira.ticketviewer = function() {};
jira.ticketviewer.ticketgenerator = function() {};
jira.ticketviewer.ExampleClass = function(divId, url)
{
	document.getElementById(divId).innerHTML = '';
}

jira.ticketviewer.ticketgenerator.TicketGenerator = function(divId,url, jira, estimate, summary, color)
{
	//if (pagebreak)
		//this.createNewPage();
	this.divId = divId + "" + jira
	console.log("!!!!!!!!", color);
	this.element = document.getElementById(divId);
	this.setWidth(350);
	this.setHeight();
	this.addDefaultBorder();

	this.addTitle(jira,estimate, color);
	this.addSideBar();
	this.addSummary(summary);
	this.addQRCode(url);
};

jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.setWidth = function(width)
{
	this.element.style.margin = "auto";
	this.element.style.float = "left";
	this.element.style.width = width + "px";
	this.element.style.position = "relative";
	this.element.style.marginLeft = 50 + "px";

}
jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.setHeight = function()
{
	this.element.style.height = 250 + "px";
	this.element.style.marginBottom = 50 + "px";
}
jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.addDefaultBorder = function(width)
{
	this.element.style.border = "2px solid black"
}

jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.addTitle = function(jira, estimate, color)
{

	var jiraElement = this.createTitleElement(this.divId + "_jira", jira || "Jira", "35%");
	var estimateElement = this.createTitleElement(this.divId + "_estimate", estimate || "Estimate", "15%");
	var actualElement = this.createTitleElement(this.divId + "_actual", "Actual", "15%");
	var ownerElement = this.createTitleElement(this.divId + "_owner", "Owner", "35%");

	var titleElement = document.createElement("div");
	titleElement.style.height = "50px";

	jiraElement.style.backgroundColor = color;
	jiraElement.style["-webkit-print-color-adjust"] = "exact";
	jiraElement.style.fontSize = "80%";
	jiraElement.style.fontWeight = "Bolder";

	titleElement.appendChild(jiraElement);
	titleElement.appendChild(estimateElement);
	titleElement.appendChild(actualElement);
	titleElement.appendChild(ownerElement);

	this.element.appendChild(titleElement);
}

jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.addSummary = function(summary)
{
	var sideElement = document.createElement("div");
	sideElement.style.marginRight = "5em";
	sideElement.style.padding = "1em";
	sideElement.style.fontSize= "23px";
	sideElement.innerHTML = summary;

	this.element.appendChild(sideElement);
}

jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.addSideBar = function()
{
	var sideElement = document.createElement("div");
	sideElement.style.textAlign = "center";
	sideElement.style.width = "70px";
	sideElement.style.height = "198px";
	sideElement.style.clear = "both";
	sideElement.style.position = "absolute";
	sideElement.style.top = "52px";
	sideElement.style.bottom = "0";
	sideElement.style.right = "0";
	sideElement.style.outline = "2px solid black";
	sideElement.setAttribute("id", "sidebar");

	var docElement = this.createTitleElement(this.divId + "_doc", "Doc", "100%",40);
	var demoElement = this.createTitleElement(this.divId + "_demo", "Demo", "100%",40);
	var reviewElement = this.createTitleElement(this.divId + "_review", "Review", "100%",40);
	var qrcodeElement = this.createTitleElement(this.divId + "_qrcode", "QRCode", "100%", 78);

	sideElement.appendChild(docElement);
	sideElement.appendChild(demoElement);
	sideElement.appendChild(reviewElement);
	sideElement.appendChild(qrcodeElement);

	this.element.appendChild(sideElement);
}

jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.createTitleElement = function(id,text,width,height)
{
	var titleElement = document.createElement("span");
	titleElement.style.textAlign = "center";
	titleElement.style.width = width;
	if (height != undefined)
		titleElement.style.height = height + "px";
	else
		titleElement.style.height = "50px";
	titleElement.style.float = "left";
	titleElement.style.outline = "2px solid black";
	titleElement.style.verticalAlign = "middle";
	height = height || 50;
	titleElement.style.lineHeight = height + "px";
	titleElement.style.fontSize= "12px";

	titleElement.setAttribute("id", id);
	titleElement.appendChild(document.createTextNode(text));
	return titleElement;
}

jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.addQRCode = function(url)
{
	new jira.ticketviewer.ExampleClass(this.divId + "_qrcode",url);
}
<commit_msg>Text is now white on color backgrounds<commit_after>var jira = function() {};
jira.ticketviewer = function() {};
jira.ticketviewer.ticketgenerator = function() {};
jira.ticketviewer.ExampleClass = function(divId, url)
{
	document.getElementById(divId).innerHTML = '';
}

jira.ticketviewer.ticketgenerator.TicketGenerator = function(divId,url, jira, estimate, summary, color)
{
	//if (pagebreak)
		//this.createNewPage();
	this.divId = divId + "" + jira
	console.log("!!!!!!!!", color);
	this.element = document.getElementById(divId);
	this.setWidth(350);
	this.setHeight();
	this.addDefaultBorder();

	this.addTitle(jira,estimate, color);
	this.addSideBar();
	this.addSummary(summary);
	this.addQRCode(url);
};

jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.setWidth = function(width)
{
	this.element.style.margin = "auto";
	this.element.style.float = "left";
	this.element.style.width = width + "px";
	this.element.style.position = "relative";
	this.element.style.marginLeft = 50 + "px";

}
jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.setHeight = function()
{
	this.element.style.height = 250 + "px";
	this.element.style.marginBottom = 50 + "px";
}
jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.addDefaultBorder = function(width)
{
	this.element.style.border = "2px solid black"
}

jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.addTitle = function(jira, estimate, color)
{

	var jiraElement = this.createTitleElement(this.divId + "_jira", jira || "Jira", "35%");
	var estimateElement = this.createTitleElement(this.divId + "_estimate", estimate || "Estimate", "15%");
	var actualElement = this.createTitleElement(this.divId + "_actual", "Actual", "15%");
	var ownerElement = this.createTitleElement(this.divId + "_owner", "Owner", "35%");

	var titleElement = document.createElement("div");
	titleElement.style.height = "50px";

    if (color !== null) {
        jiraElement.style.backgroundColor = color;
        jiraElement.style.color = "white";
    }
	jiraElement.style["-webkit-print-color-adjust"] = "exact";
	jiraElement.style.fontSize = "80%";
	jiraElement.style.fontWeight = "Bolder";
    jiraElement.style.textShadow = "-1px 0 black, 0 1px black, 1px 0 black, 0 -1px black";

	titleElement.appendChild(jiraElement);
	titleElement.appendChild(estimateElement);
	titleElement.appendChild(actualElement);
	titleElement.appendChild(ownerElement);

	this.element.appendChild(titleElement);
}

jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.addSummary = function(summary)
{
	var sideElement = document.createElement("div");
	sideElement.style.marginRight = "5em";
	sideElement.style.padding = "1em";
	sideElement.style.fontSize= "23px";
	sideElement.innerHTML = summary;

	this.element.appendChild(sideElement);
}

jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.addSideBar = function()
{
	var sideElement = document.createElement("div");
	sideElement.style.textAlign = "center";
	sideElement.style.width = "70px";
	sideElement.style.height = "198px";
	sideElement.style.clear = "both";
	sideElement.style.position = "absolute";
	sideElement.style.top = "52px";
	sideElement.style.bottom = "0";
	sideElement.style.right = "0";
	sideElement.style.outline = "2px solid black";
	sideElement.setAttribute("id", "sidebar");

	var docElement = this.createTitleElement(this.divId + "_doc", "Doc", "100%",40);
	var demoElement = this.createTitleElement(this.divId + "_demo", "Demo", "100%",40);
	var reviewElement = this.createTitleElement(this.divId + "_review", "Review", "100%",40);
	var qrcodeElement = this.createTitleElement(this.divId + "_qrcode", "QRCode", "100%", 78);

	sideElement.appendChild(docElement);
	sideElement.appendChild(demoElement);
	sideElement.appendChild(reviewElement);
	sideElement.appendChild(qrcodeElement);

	this.element.appendChild(sideElement);
}

jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.createTitleElement = function(id,text,width,height)
{
	var titleElement = document.createElement("span");
	titleElement.style.textAlign = "center";
	titleElement.style.width = width;
	if (height != undefined)
		titleElement.style.height = height + "px";
	else
		titleElement.style.height = "50px";
	titleElement.style.float = "left";
	titleElement.style.outline = "2px solid black";
	titleElement.style.verticalAlign = "middle";
	height = height || 50;
	titleElement.style.lineHeight = height + "px";
	titleElement.style.fontSize= "12px";

	titleElement.setAttribute("id", id);
	titleElement.appendChild(document.createTextNode(text));
	return titleElement;
}

jira.ticketviewer.ticketgenerator.TicketGenerator.prototype.addQRCode = function(url)
{
	new jira.ticketviewer.ExampleClass(this.divId + "_qrcode",url);
}
<|endoftext|>


<commit_before>'use strict';

angular.module('publisherApp', ['LocalStorageModule', 'tmh.dynamicLocale', 'ngResource', 'ui.router', 'checklist-model', /*'ngAnimate',*/ 'angularSpinner',/*'infinite-scroll',*/
    'ngCookies', 'pascalprecht.translate', 'ngCacheBuster', 'ui.bootstrap','angular.filter', 'isteven-multi-select', 'jsTree.directive', 'ui.bootstrap.tooltip','ui.bootstrap.pagination',
    'textAngular', 'ngFileUpload', 'ngImgCrop', 'ImageCropper'])

    .run(function ($rootScope, $location, $window, $http, $state, $translate, Auth, Principal, Language, ENV, VERSION) {
        $rootScope.ENV = ENV;
        $rootScope.VERSION = VERSION;
        //$rootScope.showSpinner = false;
        $rootScope.$on('$stateChangeStart', function (event, toState, toStateParams) {
            //console.log("$stateChangeStart");
            $rootScope.toState = toState;
            $rootScope.toStateParams = toStateParams;

            /*if (toState.resolve) {
                $rootScope.showSpinner = true;
            }*/

            var requireLogin = toState.data.requireLogin;

            if (requireLogin && !Principal.isAuthenticated() && !$rootScope.modalOpened ) {
                event.preventDefault();
                Auth.login().then(function () {
                    return $state.transitionTo(toState.name, toStateParams, {reload: true});
                })
                    .catch(function () {
                        return $state.transitionTo('home', {}, {reload: true});
                    });
            }

            if (Principal.isIdentityResolved()) {
                Auth.authorize();
            }

            // Update the language
            Language.getCurrent().then(function (language) {
                $translate.use(language);
            });
        });

        $rootScope.$on('$stateChangeSuccess',  function(event, toState, toParams, fromState, fromParams) {
            //console.log("$stateChangeSuccess");
            var titleKey = 'global.title';
            $rootScope.previousStateName = fromState.name;
            $rootScope.previousStateParams = fromParams;

            /*if (toState.resolve) {
                console.log("set showspinner");
                $rootScope.showSpinner = false;
            }*/

            // Set the page title key to the one configured in state or use default one
            if (toState.data.pageTitle) {
                titleKey = toState.data.pageTitle;
            }
            $translate(titleKey).then(function (title) {
                // Change window title with translated one
                $window.document.title = title;
            });
        });

        /*$rootScope.$on('$stateChangeError', function (event, toState, toStateParams) {
            console.log("$stateChangeError");
           // $rootScope.showSpinner = false;
        });*/

        $rootScope.back = function() {
            // If previous state is 'activate' or do not exist go to 'home'
            if ($rootScope.previousStateName === 'activate' || $state.get($rootScope.previousStateName) === null) {
                $state.go('home');
            } else {
                $state.go($rootScope.previousStateName, $rootScope.previousStateParams);
            }
        };

        $rootScope.inArray = function (item, array) {
            if (!angular.isDefined(array) || !angular.isArray(array)) return false;
            return (-1 !== array.indexOf(item));
        };
    })
    .config(function ($stateProvider, $urlRouterProvider, $httpProvider, $locationProvider, $translateProvider, tmhDynamicLocaleProvider,
                      httpRequestInterceptorCacheBusterProvider, usSpinnerConfigProvider, $provide) {
        //enable CSRF
        $httpProvider.defaults.xsrfCookieName= 'CSRF-TOKEN';
        $httpProvider.defaults.xsrfHeaderName= 'X-CSRF-TOKEN';

        usSpinnerConfigProvider.setDefaults({color: 'white'});

        // configure textAngular
        $provide.decorator('taOptions', ['taRegisterTool', '$delegate', function(taRegisterTool, taOptions){

            /*['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'pre', 'quote'],
                ['bold', 'italics', 'underline', 'strikeThrough', 'ul', 'ol', 'redo', 'undo', 'clear'],
                ['justifyLeft','justifyCenter','justifyRight','justifyFull','indent','outdent'],
                ['html', 'insertImage', 'insertLink', 'insertVideo', 'wordcount', 'charcount']*/

            taOptions.toolbar = [
                ['h1', 'h2', 'h3', 'p', 'quote'],
                ['bold', 'italics', 'underline', 'strikeThrough','ul', 'ol', 'redo', 'undo'],
                ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
                ['backgroundColor', 'fontColor', 'clear'], /* 'fontSize', 'fontName',*/
                ['html', 'insertImage', 'insertVideo', 'insertLink']
            ];
            taOptions.classes = {
                focussed: "focussed",
                    toolbar: "btn-toolbar",
                    toolbarGroup: "btn-group",
                    toolbarButton: "btn btn-primary",
                    toolbarButtonActive: "active",
                    disabled: "disabled",
                    textEditor: 'form-control',
                    htmlEditor: 'form-control'
            };
            /*taRegisterTool('insertClassicVideo', {
                iconclass: 'fa fa-youtube-play',
                tooltiptext: taTranslations.insertVideo.tooltip,
                action: function(){
                    var videoLink;
                    videoLink = $window.prompt(taTranslations.insertImage.dialogPrompt, 'http://');
                    if(videoLink && videoLink !== '' && videoLink !== 'http://'){
                        return this.$editor().wrapSelection('insertVideo', videoLink, true);
                    }
                },
                onElementSelect: {
                    element: 'video',
                    action: taToolFunctions.imgOnSelectAction
                }
            });*/

            taRegisterTool('fontColor', {
                display: "<button colorpicker type='button' title='Font Color'  colorpicker-close-on-select colorpicker-position='bottom' ng-model='fontColor' style='color: {{fontColor}}'></button>",
                action: function (deferred) {
                    var self = this;
                    if (typeof self.listener == 'undefined') {
                        self.listener = self.$watch('fontColor', function (newValue) {
                            self.$editor().wrapSelection('foreColor', newValue);
                        });
                    }
                    self.$on('colorpicker-selected', function () {
                        deferred.resolve();
                    });
                    self.$on('colorpicker-closed', function () {
                        deferred.resolve();
                    });
                    return false;
                }
            });

            taRegisterTool('backgroundColor', {
                display: "<button colorpicker type='button' title='Background Color' colorpicker-close-on-select colorpicker-position='bottom' ng-model='backgroundColor' style='background-color: {{backgroundColor}}'></button>",
                action: function (deferred) {
                    var self = this;
                    this.$editor().wrapSelection('backgroundColor', this.backgroundColor);
                    if (typeof self.listener == 'undefined') {
                        self.listener = self.$watch('backgroundColor', function (newValue) {
                            self.$editor().wrapSelection('backColor', newValue);
                        });
                    }
                    self.$on('colorpicker-selected', function () {
                        deferred.resolve();
                    });
                    self.$on('colorpicker-closed', function () {
                        deferred.resolve();
                    });
                    return;
                }
            });
            //taOptions.defaultFileDropHandler =
            ///* istanbul ignore next: untestable image processing */
            //function(file, insertAction){
            //    console.log("dropped file upload", file.type);
            //    var reader = new FileReader();
            //    if(file.type.substring(0, 5) === 'image'){
            //        reader.onload = function() {
            //            if(reader.result !== '') insertAction('insertImage', reader.result, true);
            //        };
            //
            //        reader.readAsDataURL(file);
            //        // NOTE: For async procedures return a promise and resolve it when the editor should update the model.
            //        return true;
            //    } else if(file.type.substring(0, 5) === 'video'){
            //        reader.onload = function() {
            //            if(reader.result !== '') insertAction('insertVideo', reader.result, true);
            //        };
            //
            //        reader.readAsDataURL(file);
            //        // NOTE: For async procedures return a promise and resolve it when the editor should update the model.
            //        return true;
            //    }
            //    return false;
            //};

            /*taOptions.toolbar[1].push('backgroundColor');
            taOptions.toolbar[1].push('fontColor');

            taOptions.toolbar[0].splice( taOptions.toolbar[0].indexOf("h4"), 1 );
            taOptions.toolbar[0].splice( taOptions.toolbar[0].indexOf("h5"), 1 );
            taOptions.toolbar[0].splice( taOptions.toolbar[0].indexOf("h6"), 1 );*/

            return taOptions;
        }]);

//cfpLoadingBarProvider.parentSelector = 'container';

//Cache everything except rest api requests
        httpRequestInterceptorCacheBusterProvider.setMatchlist([/.*api.*/, /.*protected.*/], true);

        $httpProvider.interceptors.push('AuthInterceptor');
//$httpProvider.interceptors.push('loadingDialogInterceptor');
//$httpProvider.interceptors.push('loadingDialogInterceptor');

        $urlRouterProvider.otherwise('/');
        $stateProvider.state('site', {
            'abstract': true,
            views: {
                /*'navbar@': {
                 templateUrl: 'scripts/components/navbar/navbar.html',
                 controller: 'NavbarController'
                 }*/
            },
            data: {
                requireLogin: true, // this property will apply to all children of 'site'
                roles: ['ROLE_USER']
            },
            resolve: {
                authorize: ['Auth',
                    function (Auth) {
                        return Auth.authorize();
                    }
                ],
                translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
                    //console.log("add partials");
                    $translatePartialLoader.addPart('global');
                    $translatePartialLoader.addPart('language');
                    $translatePartialLoader.addPart('enum');
                    $translatePartialLoader.addPart('subject');

                    return $translate.refresh();
                }],
                initData: [ 'EnumDatas', '$q', function(EnumDatas, $q){
                    return EnumDatas.init();
                }]
            }
        });

// Initialize angular-translate
        $translateProvider.useLoader('$translatePartialLoader', {
            urlTemplate: 'i18n/{lang}/{part}.json'
        });

        $translateProvider.registerAvailableLanguageKeys(['en', 'fr'], {
            'en_US': 'en',
            'en_UK': 'en',
            'fr_FR': 'fr'
        });

        $translateProvider.fallbackLanguage('en')
            .determinePreferredLanguage();
        //$translateProvider.useSanitizeValueStrategy('escaped');
        $translateProvider.useCookieStorage();

        tmhDynamicLocaleProvider.localeLocationPattern('bower_components/angular-i18n/angular-locale_{{locale}}.js');
        tmhDynamicLocaleProvider.useCookieStorage('NG_TRANSLATE_LANG_KEY');
    });
<commit_msg>solving problems of i18n loading on login page<commit_after>'use strict';

angular.module('publisherApp', ['LocalStorageModule', 'tmh.dynamicLocale', 'ngResource', 'ui.router', 'checklist-model', /*'ngAnimate',*/ 'angularSpinner',/*'infinite-scroll',*/
    'ngCookies', 'pascalprecht.translate', 'ngCacheBuster', 'ui.bootstrap','angular.filter', 'isteven-multi-select', 'jsTree.directive', 'ui.bootstrap.tooltip','ui.bootstrap.pagination',
    'textAngular', 'ngFileUpload', 'ngImgCrop', 'ImageCropper'])

    .run(function ($rootScope, $location, $window, $http, $state, $translate, Auth, Principal, Language, ENV, VERSION) {
        $rootScope.ENV = ENV;
        $rootScope.VERSION = VERSION;
        //$rootScope.showSpinner = false;
        $rootScope.$on('$stateChangeStart', function (event, toState, toStateParams) {
            //console.log("$stateChangeStart");
            $rootScope.toState = toState;
            $rootScope.toStateParams = toStateParams;

            /*if (toState.resolve) {
                $rootScope.showSpinner = true;
            }*/

            var requireLogin = toState.data.requireLogin;

            if (requireLogin && !Principal.isAuthenticated() && !$rootScope.modalOpened ) {
                event.preventDefault();
                Auth.login().then(function () {
                    return $state.transitionTo(toState.name, toStateParams, {reload: true});
                })
                    .catch(function () {
                        return $state.transitionTo('home', {}, {reload: true});
                    });
            }

            if (Principal.isIdentityResolved()) {
                Auth.authorize();
            }

            // Update the language
            Language.getCurrent().then(function (language) {
                $translate.use(language);
            });
        });

        $rootScope.$on('$stateChangeSuccess',  function(event, toState, toParams, fromState, fromParams) {
            //console.log("$stateChangeSuccess");
            var titleKey = 'global.title';
            $rootScope.previousStateName = fromState.name;
            $rootScope.previousStateParams = fromParams;

            /*if (toState.resolve) {
                console.log("set showspinner");
                $rootScope.showSpinner = false;
            }*/

            // Set the page title key to the one configured in state or use default one
            if (toState.data.pageTitle) {
                titleKey = toState.data.pageTitle;
            }
            $translate(titleKey).then(function (title) {
                // Change window title with translated one
                $window.document.title = title;
            });
        });

        /*$rootScope.$on('$stateChangeError', function (event, toState, toStateParams) {
            console.log("$stateChangeError");
           // $rootScope.showSpinner = false;
        });*/

        $rootScope.back = function() {
            // If previous state is 'activate' or do not exist go to 'home'
            if ($rootScope.previousStateName === 'activate' || $state.get($rootScope.previousStateName) === null) {
                $state.go('home');
            } else {
                $state.go($rootScope.previousStateName, $rootScope.previousStateParams);
            }
        };

        $rootScope.inArray = function (item, array) {
            if (!angular.isDefined(array) || !angular.isArray(array)) return false;
            return (-1 !== array.indexOf(item));
        };
    })
    .config(function ($stateProvider, $urlRouterProvider, $httpProvider, $locationProvider, $translateProvider, $translatePartialLoaderProvider, tmhDynamicLocaleProvider,
                      httpRequestInterceptorCacheBusterProvider, usSpinnerConfigProvider, $provide) {
        //enable CSRF
        $httpProvider.defaults.xsrfCookieName= 'CSRF-TOKEN';
        $httpProvider.defaults.xsrfHeaderName= 'X-CSRF-TOKEN';

        usSpinnerConfigProvider.setDefaults({color: 'white'});

        // configure textAngular
        $provide.decorator('taOptions', ['taRegisterTool', '$delegate', function(taRegisterTool, taOptions){

            /*['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'pre', 'quote'],
                ['bold', 'italics', 'underline', 'strikeThrough', 'ul', 'ol', 'redo', 'undo', 'clear'],
                ['justifyLeft','justifyCenter','justifyRight','justifyFull','indent','outdent'],
                ['html', 'insertImage', 'insertLink', 'insertVideo', 'wordcount', 'charcount']*/

            taOptions.toolbar = [
                ['h1', 'h2', 'h3', 'p', 'quote'],
                ['bold', 'italics', 'underline', 'strikeThrough','ul', 'ol', 'redo', 'undo'],
                ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
                ['backgroundColor', 'fontColor', 'clear'], /* 'fontSize', 'fontName',*/
                ['html', 'insertImage', 'insertVideo', 'insertLink']
            ];
            taOptions.classes = {
                focussed: "focussed",
                    toolbar: "btn-toolbar",
                    toolbarGroup: "btn-group",
                    toolbarButton: "btn btn-primary",
                    toolbarButtonActive: "active",
                    disabled: "disabled",
                    textEditor: 'form-control',
                    htmlEditor: 'form-control'
            };
            /*taRegisterTool('insertClassicVideo', {
                iconclass: 'fa fa-youtube-play',
                tooltiptext: taTranslations.insertVideo.tooltip,
                action: function(){
                    var videoLink;
                    videoLink = $window.prompt(taTranslations.insertImage.dialogPrompt, 'http://');
                    if(videoLink && videoLink !== '' && videoLink !== 'http://'){
                        return this.$editor().wrapSelection('insertVideo', videoLink, true);
                    }
                },
                onElementSelect: {
                    element: 'video',
                    action: taToolFunctions.imgOnSelectAction
                }
            });*/

            taRegisterTool('fontColor', {
                display: "<button colorpicker type='button' title='Font Color'  colorpicker-close-on-select colorpicker-position='bottom' ng-model='fontColor' style='color: {{fontColor}}'></button>",
                action: function (deferred) {
                    var self = this;
                    if (typeof self.listener == 'undefined') {
                        self.listener = self.$watch('fontColor', function (newValue) {
                            self.$editor().wrapSelection('foreColor', newValue);
                        });
                    }
                    self.$on('colorpicker-selected', function () {
                        deferred.resolve();
                    });
                    self.$on('colorpicker-closed', function () {
                        deferred.resolve();
                    });
                    return false;
                }
            });

            taRegisterTool('backgroundColor', {
                display: "<button colorpicker type='button' title='Background Color' colorpicker-close-on-select colorpicker-position='bottom' ng-model='backgroundColor' style='background-color: {{backgroundColor}}'></button>",
                action: function (deferred) {
                    var self = this;
                    this.$editor().wrapSelection('backgroundColor', this.backgroundColor);
                    if (typeof self.listener == 'undefined') {
                        self.listener = self.$watch('backgroundColor', function (newValue) {
                            self.$editor().wrapSelection('backColor', newValue);
                        });
                    }
                    self.$on('colorpicker-selected', function () {
                        deferred.resolve();
                    });
                    self.$on('colorpicker-closed', function () {
                        deferred.resolve();
                    });
                    return;
                }
            });
            //taOptions.defaultFileDropHandler =
            ///* istanbul ignore next: untestable image processing */
            //function(file, insertAction){
            //    console.log("dropped file upload", file.type);
            //    var reader = new FileReader();
            //    if(file.type.substring(0, 5) === 'image'){
            //        reader.onload = function() {
            //            if(reader.result !== '') insertAction('insertImage', reader.result, true);
            //        };
            //
            //        reader.readAsDataURL(file);
            //        // NOTE: For async procedures return a promise and resolve it when the editor should update the model.
            //        return true;
            //    } else if(file.type.substring(0, 5) === 'video'){
            //        reader.onload = function() {
            //            if(reader.result !== '') insertAction('insertVideo', reader.result, true);
            //        };
            //
            //        reader.readAsDataURL(file);
            //        // NOTE: For async procedures return a promise and resolve it when the editor should update the model.
            //        return true;
            //    }
            //    return false;
            //};

            /*taOptions.toolbar[1].push('backgroundColor');
            taOptions.toolbar[1].push('fontColor');

            taOptions.toolbar[0].splice( taOptions.toolbar[0].indexOf("h4"), 1 );
            taOptions.toolbar[0].splice( taOptions.toolbar[0].indexOf("h5"), 1 );
            taOptions.toolbar[0].splice( taOptions.toolbar[0].indexOf("h6"), 1 );*/

            return taOptions;
        }]);

//Cache everything except rest api requests
        httpRequestInterceptorCacheBusterProvider.setMatchlist([/.*api.*/, /.*protected.*/], true);

        $httpProvider.interceptors.push('AuthInterceptor');
//$httpProvider.interceptors.push('loadingDialogInterceptor');

        $urlRouterProvider.otherwise('/');
        $stateProvider.state('site', {
            'abstract': true,
            views: {
                /*'navbar@': {
                 templateUrl: 'scripts/components/navbar/navbar.html',
                 controller: 'NavbarController'
                 }*/
            },
            data: {
                requireLogin: true, // this property will apply to all children of 'site'
                roles: ['ROLE_USER']
            },
            resolve: {
                authorize: ['Auth',
                    function (Auth) {
                        return Auth.authorize();
                    }
                ],
                translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
                    //console.log("add partials");
                    $translatePartialLoader.addPart('global');
                    $translatePartialLoader.addPart('language');
                    $translatePartialLoader.addPart('enum');
                    $translatePartialLoader.addPart('subject');

                    return $translate.refresh();
                }],
                initData: [ 'EnumDatas', '$q', function(EnumDatas, $q){
                    return EnumDatas.init();
                }]
            }
        });

// Initialize angular-translate
        $translateProvider.useLoader('$translatePartialLoader', {
            urlTemplate: 'i18n/{lang}/{part}.json'
        });

        $translateProvider.registerAvailableLanguageKeys(['en', 'fr'], {
            'en_US': 'en',
            'en_UK': 'en',
            'fr_FR': 'fr'
        });

        $translateProvider.fallbackLanguage('en')
            .determinePreferredLanguage();
        //$translateProvider.useSanitizeValueStrategy('escaped');
        $translateProvider.useCookieStorage();

        $translatePartialLoaderProvider.addPart('login');

        tmhDynamicLocaleProvider.localeLocationPattern('bower_components/angular-i18n/angular-locale_{{locale}}.js');
        tmhDynamicLocaleProvider.useCookieStorage('NG_TRANSLATE_LANG_KEY');
    });
<|endoftext|>


<commit_before>define('views/feed_builder', ['forms_transonic', 'jquery', 'jquery-sortable', 'format', 'l10n', 'models', 'notification', 'nunjucks', 'requests',  'urls', 'utils', 'z'],
    function(forms_transonic, $, sortable, format, l10n, models, notification, nunjucks, requests, urls, utils, z) {
    'use strict';
    var format = format.format;
    var gettext = l10n.gettext;

    // Keep track of what regions we look at to limit the queries on the backend if we publish.
    var modified_regions = ['restofworld'];

    z.page.on('change', '.feed-region-switcher', function() {
        /* Look at a different feed. */
        var region = this.value;
        $('.feed-builder .submit').prop('disabled', true);
        $('.feeds .loading').show();

        requests.get(urls.api.url('feed-items', [], {'region': region, 'ordering': 'order'})).done(function(feed_items) {
            feed_items = feed_items.objects;
            var $feed = $('.localized').addClass('hidden')
                                       .filter('[data-region=' + region + ']').removeClass('hidden');
            modified_regions.push(region);

            for (var i = 0; i < feed_items.length; i++) {
                var type = feed_items[i].item_type;
                if (type == 'shelf') {
                    // Don't render shelves because they are immutable in feed.
                    continue;
                }

                var context = {
                    feed: require('feed'),
                    is_builder: true
                };
                context[type] = feed_items[i][type];
                var $feed_element = $(nunjucks.env.render(format('listing/{0}.html', [type]), context));

                models('feed-' + type).cast(feed_items[i][type]);
                append($feed, $feed_element);
            }

            $('.feeds .loading').hide();
            $('.feed-builder .submit').prop('disabled', false);
            z.page.trigger('refresh_preview');
        });
    })
    .on('click', '.feed-builder .manage-modules-listing .feed-element', function() {
        /* Add feed element to feed. */
        append(get_region_feed(), $(this));
    })
    .on('click', '.feed-builder .manage-modules-listing .feed-element > a', function(e) {
        /* Stop search results from getting navigated. */
        e.preventDefault();
        e.stopPropagation();
        append(get_region_feed(), $(this).closest('.feed-element'));
    })
    .on('click', '.feed-builder .region-feed .feed-element .delete', function() {
        /* Remove element from feed. */
        remove($(this).closest('.feed-element'));
    })
    .on('click', '.feed-builder .region-feed .feed-element .reorder', function() {
         /* Reorder elements. */
        var $this = $(this);
        var $item = $this.closest('.feed-element');
        var is_prev = $this.hasClass('prev');
        var $items = $this.closest('.feed-elements').find('.feed-element');
        var pos = $items.index($item);

        if ((is_prev && pos === 0) || (!is_prev && pos == $items.length - 1)) {
            // Don't swap if trying to move the first element up or last element down.
            return;
        }

        var swap_pos = is_prev ? pos - 1 : pos + 1;
        var $swap_with = $items.eq(swap_pos);

        if (is_prev) {
            $item.clone().insertBefore($swap_with);
        } else {
            $item.clone().insertAfter($swap_with);
        }
        $item.remove();
        z.page.trigger('refresh_preview');
    })
    .on('click', '.feed-builder .submit', utils._pd(function() {
        /* Publish changes. */
        var $this = $(this);
        $this.html(gettext('Publishing...')).attr('disabled', true);

        forms_transonic.feed_items($('.feeds'), modified_regions).done(function() {
            notification.notification({message: gettext('Feed changes successfully published!')});
            $this.html(gettext('Publish')).removeAttr('disabled');
        }).fail(function(err) {
            notification.notification({message: gettext('Sorry, there was an error publishing your changes.')});
            $this.html(gettext('Publish')).removeAttr('disabled');
        });
    }));

    function append($feed, $feed_element) {
        var type = $feed_element.data('type');
        var id = $feed_element.data('id');
        if ($feed.find(format('[data-type="{0}"][data-id="{1}"]', [type, id])).length) {
            // Already exists.
            return;
        }
        $feed.find('.empty-results').hide();
        $feed.find('.feed-elements').append($feed_element.clone());
        $('.feed-elements').sortable({
            onDrop: function($item) {
                $item.removeClass('dragged').removeAttr('style')
                z.body.removeClass('dragging');
                z.page.trigger('refresh_preview');
            }
        });
        z.page.trigger('refresh_preview');
    }

    function remove($feed_element) {
        var $feed= $feed_element.closest('.region-feed');
        $feed_element.remove();
        if (!$feed.find('.feed-element').length) {
            $feed.find('.empty-results').show();
        }
        z.page.trigger('refresh_preview');
    }

    function get_region_feed() {
        var region = $('.feed-region-switcher :checked').val();
        return $('.region-feed[data-region="' + region + '"]');
    }

    return function(builder) {
        builder.z('title', gettext('Feed Builder'));
        builder.z('type', 'publish');
        builder.start('feed_builder.html', {
            is_builder: true  // To flip some stuff in the included manage_listing.html.
        }).done(function() {
            modified_regions = ['restofworld'];

            // Load existing FeedItems.
            $('.feed-region-switcher').trigger('change');
        });
    };
});
<commit_msg>render feed builder even on 404<commit_after>define('views/feed_builder', ['forms_transonic', 'jquery', 'jquery-sortable', 'format', 'l10n', 'models', 'notification', 'nunjucks', 'requests',  'urls', 'utils', 'z'],
    function(forms_transonic, $, sortable, format, l10n, models, notification, nunjucks, requests, urls, utils, z) {
    'use strict';
    var format = format.format;
    var gettext = l10n.gettext;

    // Keep track of what regions we look at to limit the queries on the backend if we publish.
    var modified_regions = ['restofworld'];

    z.page.on('change', '.feed-region-switcher', function() {
        /* Look at a different feed. */
        var region = this.value;
        $('.feed-builder .submit').prop('disabled', true);
        $('.feeds .loading').show();

        requests.get(urls.api.url('feed-items', [], {'region': region, 'ordering': 'order'})).always(function(feed_items) {
            feed_items = feed_items.objects;
            var $feed = $('.localized').addClass('hidden')
                                       .filter('[data-region=' + region + ']').removeClass('hidden');
            modified_regions.push(region);

            for (var i = 0; i < feed_items.length; i++) {
                var type = feed_items[i].item_type;
                if (type == 'shelf') {
                    // Don't render shelves because they are immutable in feed.
                    continue;
                }

                var context = {
                    feed: require('feed'),
                    is_builder: true
                };
                context[type] = feed_items[i][type];
                var $feed_element = $(nunjucks.env.render(format('listing/{0}.html', [type]), context));

                models('feed-' + type).cast(feed_items[i][type]);
                append($feed, $feed_element);
            }

            $('.feeds .loading').hide();
            $('.feed-builder .submit').prop('disabled', false);
            z.page.trigger('refresh_preview');
        });
    })
    .on('click', '.feed-builder .manage-modules-listing .feed-element', function() {
        /* Add feed element to feed. */
        append(get_region_feed(), $(this));
    })
    .on('click', '.feed-builder .manage-modules-listing .feed-element > a', function(e) {
        /* Stop search results from getting navigated. */
        e.preventDefault();
        e.stopPropagation();
        append(get_region_feed(), $(this).closest('.feed-element'));
    })
    .on('click', '.feed-builder .region-feed .feed-element .delete', function() {
        /* Remove element from feed. */
        remove($(this).closest('.feed-element'));
    })
    .on('click', '.feed-builder .region-feed .feed-element .reorder', function() {
         /* Reorder elements. */
        var $this = $(this);
        var $item = $this.closest('.feed-element');
        var is_prev = $this.hasClass('prev');
        var $items = $this.closest('.feed-elements').find('.feed-element');
        var pos = $items.index($item);

        if ((is_prev && pos === 0) || (!is_prev && pos == $items.length - 1)) {
            // Don't swap if trying to move the first element up or last element down.
            return;
        }

        var swap_pos = is_prev ? pos - 1 : pos + 1;
        var $swap_with = $items.eq(swap_pos);

        if (is_prev) {
            $item.clone().insertBefore($swap_with);
        } else {
            $item.clone().insertAfter($swap_with);
        }
        $item.remove();
        z.page.trigger('refresh_preview');
    })
    .on('click', '.feed-builder .submit', utils._pd(function() {
        /* Publish changes. */
        var $this = $(this);
        $this.html(gettext('Publishing...')).attr('disabled', true);

        forms_transonic.feed_items($('.feeds'), modified_regions).done(function() {
            notification.notification({message: gettext('Feed changes successfully published!')});
            $this.html(gettext('Publish')).removeAttr('disabled');
        }).fail(function(err) {
            notification.notification({message: gettext('Sorry, there was an error publishing your changes.')});
            $this.html(gettext('Publish')).removeAttr('disabled');
        });
    }));

    function append($feed, $feed_element) {
        var type = $feed_element.data('type');
        var id = $feed_element.data('id');
        if ($feed.find(format('[data-type="{0}"][data-id="{1}"]', [type, id])).length) {
            // Already exists.
            return;
        }
        $feed.find('.empty-results').hide();
        $feed.find('.feed-elements').append($feed_element.clone());
        $('.feed-elements').sortable({
            onDrop: function($item) {
                $item.removeClass('dragged').removeAttr('style')
                z.body.removeClass('dragging');
                z.page.trigger('refresh_preview');
            }
        });
        z.page.trigger('refresh_preview');
    }

    function remove($feed_element) {
        var $feed= $feed_element.closest('.region-feed');
        $feed_element.remove();
        if (!$feed.find('.feed-element').length) {
            $feed.find('.empty-results').show();
        }
        z.page.trigger('refresh_preview');
    }

    function get_region_feed() {
        var region = $('.feed-region-switcher :checked').val();
        return $('.region-feed[data-region="' + region + '"]');
    }

    return function(builder) {
        builder.z('title', gettext('Feed Builder'));
        builder.z('type', 'publish');
        builder.start('feed_builder.html', {
            is_builder: true  // To flip some stuff in the included manage_listing.html.
        }).done(function() {
            modified_regions = ['restofworld'];

            // Load existing FeedItems.
            $('.feed-region-switcher').trigger('change');
        });
    };
});
<|endoftext|>


<commit_before>ART.Sheet.defineStyle('window.browser', {
	'header-height': 60,
	'header-overflow': 'visible'
});

ART.Sheet.defineStyle('history.browser', {
	'top':30,
	'padding': '0 8px 0 10px'
});

ART.Sheet.defineStyle('history input', {
	'left': 66
});

ART.Sheet.defineStyle('history input.disabled', {
	'left': 66
});

ART.Browser = new Class({

	Extends: ART.Window,

	options: {
		className: 'browser',
		historyOptions: {
			className: 'browser',
			editable: false
		}
	},

	initialize: function(){
		this.requireToRender('browser:history');
		this.parent.apply(this, arguments);
	},

	build: function(){
		this.parent.apply(this, arguments);
		this.history = new ART.History(
			$extend(this.options.historyOptions, {
				parentWidget: this
			})
		);
		$(this.history).inject(this.header);
		var styles = ART.Sheet.lookupStyle(this.getSelector());
		this.header.setStyles({
			'overflow': styles.headerOverflow
		});
		this.readyToRender('browser:history');
		this.history.resize();
	},

	redraw: function(){
		this.parent.apply(this, arguments);
		if (this.history) this.history.render();
	},

	resize: function(){
		this.parent.apply(this, arguments);
		if (this.history) this.history.resize();
	},

	show: function() {
		this.parent.apply(this, arguments);
		if (this.history) this.history.resize();
	}

});

ART.WindowTools.implement({

	getHistory: function() {
		return this.getWindow().history;
	}

});<commit_msg>since I switched to display:none for drag shading the sizing of the history widget broke because it can't measure offsets. adding event to resize this on unshade.<commit_after>ART.Sheet.defineStyle('window.browser', {
	'header-height': 60,
	'header-overflow': 'visible'
});

ART.Sheet.defineStyle('history.browser', {
	'top':30,
	'padding': '0 8px 0 10px'
});

ART.Sheet.defineStyle('history input', {
	'left': 66
});

ART.Sheet.defineStyle('history input.disabled', {
	'left': 66
});

ART.Browser = new Class({

	Extends: ART.Window,

	options: {
		className: 'browser',
		historyOptions: {
			className: 'browser',
			editable: false
		}
	},

	initialize: function(){
		this.requireToRender('browser:history');
		this.parent.apply(this, arguments);
	},

	build: function(){
		this.parent.apply(this, arguments);
		this.history = new ART.History(
			$extend(this.options.historyOptions, {
				parentWidget: this
			})
		);
		$(this.history).inject(this.header);
		var styles = ART.Sheet.lookupStyle(this.getSelector());
		this.header.setStyles({
			'overflow': styles.headerOverflow
		});
		this.readyToRender('browser:history');
		this.history.resize();
		this.addEvent('shade', function(dragging) {
			if (!dragging) this.history.resize();
		}.bind(this));
	},

	redraw: function(){
		this.parent.apply(this, arguments);
		if (this.history) this.history.render();
	},

	resize: function(){
		this.parent.apply(this, arguments);
		if (this.history) this.history.resize();
	},

	show: function() {
		this.parent.apply(this, arguments);
		if (this.history) this.history.resize();
	}

});

ART.WindowTools.implement({

	getHistory: function() {
		return this.getWindow().history;
	}

});<|endoftext|>