<commit_before>/*-*- coding: utf-8 -*- vim: set ts=4 sw=4 expandtab
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
##~ Copyright (C) 2002-2012 Bellite.io                            ##
##~                                                               ##
##~ This library is free software; you can redistribute it        ##
##~ and/or modify it under the terms of the MIT style License as  ##
##~ found in the LICENSE file included with this distribution.    ##
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##*/

"use strict";
function createMockBelliteServer(ns) {
    var self = {
        server: require('net').createServer(),
        token: ns.token || require('crypto').randomBytes(8).toString('hex'),
        shutdownTest: function() {
            self.shutdownTest = null;
            if (self.server)
                self.server.close();
            self.allConnections.forEach(function(conn){
                if (conn) conn.end() }) },
        allConnections: [] }

    var debugLog = ns.debugLog

    self.server.on('listening', function () {
        var addr = this.address()
        self.env = addr.address+':'+addr.port+'/'+self.token
        process.env.BELLITE_SERVER = self.env
        if (debugLog) debugLog('Serving BELLITE_SERVER="'+ process.env.BELLITE_SERVER +'"')
        ns.listening();
    })

    self.server.on('connection', function (conn) {
        self.allConnections.push(conn)
        conn.setEncoding("UTF-8");
        conn.setNoDelay(true);
        conn.setKeepAlive(true, 0);

        var api = {
            sendMessage: function(msg) {
                if (debugLog) debugLog('reply  ==> ', msg);
                return conn.write(msg+'\0') },
            shutdown: function() { return conn.end() },
            fireEvent: function(evtType, selfId, evt, ctx) {
                return this.send('event', {evtType: evtType, selfId: selfId||0, evt:evt, ctx:ctx}) },
            send: function(method, params, id) {
                var msg = {jsonrpc: "2.0", id:id, method:method, params:params}
                return this.sendMessage(JSON.stringify(msg)) },
            answer: function(result, id) {
                if (id===undefined) return false;
                var msg = {jsonrpc: "2.0", id:id, result:result}
                return this.sendMessage(JSON.stringify(msg)) },
            error: function(error, id) {
                if (id===undefined) return false;
                var msg = {jsonrpc: "2.0", id:id, error:error}
                return this.sendMessage(JSON.stringify(msg)) },
            checkAuth: function(token) {
                clearTimeout(authTimeout);
                return this.authorized = (token == self.token) }
            },
            tgt = ns.connect(api),
            authTimeout = setTimeout(api.shutdown, 250);

        var connBuf='';
        conn.on('data', function(data) {
            data = (connBuf+data).split('\0')
            connBuf = data.pop()
            while (data.length) {
                var msg = data.shift();
                if (debugLog) debugLog('invoke <== ', msg);
                try { msg = JSON.parse(msg) }
                catch (err) { tgt.parse_error(err, msg); continue }
                if (msg.method!==undefined)
                    tgt.invoke(msg)
                else tgt.response(msg)
            } })
        conn.on('close', function() { tgt.conn_close() })
        conn.on('error', function(err) { tgt.conn_error(err) })
    })

    self.server.on('close', function() {
        self.server = null; ns.server_close() })
    self.server.on('error', function(err) {
        ns.server_error(err) })

    self.server.listen(ns.port || 0, '127.0.0.1')
    return self;
}
exports.createMockBelliteServer = createMockBelliteServer;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function testBelliteJSONRPC(opt, doneCallback) {
    opt.log = opt.log || {};
    function log(key, args) {
        var log=opt.log[key];
        if (!log) opt.log[key] = log = []
        var ea = Array.prototype.slice.call(arguments, 1);
        if (ea.length<2) ea = ea[0]===undefined ? 0 : ea[0];
        log.push(ea)
        return this }

    var rpc = {
        connect: function(api) {
            log('connect')
            this.api = api;
            this.evtCtx = {}
            return this },
        conn_close: function() { log('conn_close') },
        conn_error: function(err) { log('conn_error', err) },
        parse_error: function(err,msg) { log('parse_error', err, msg) },
        response: function(msg) { log('response', msg) },
        invoke: function(msg) {
            var pre = this.api.authorized ? 'meth_' : 'meth0_';
            var meth = this[pre+msg.method] || this.meth_unknown;
            log('invoke', pre+msg.method, msg.params)
            return meth.call(this, msg.params, msg)},

        meth_unknown: function(args, msg) {
            log('meth_unknown', msg.method, args)
            this.api.answer(["unknown method ", null], msg.id) },
        meth_ping: function(args, msg) {
            log('meth_ping', args)
            this.api.answer([null, true, "pong"], msg.id) },
        meth_version: function(args, msg) {
            log('meth_version', args)
            this.api.answer([null, {"server":"bellite", "version":"1.4.3", "platform":"node/test"}], msg.id) },

        meth0_ping: function(args, msg) { this.meth_ping(args, msg) },
        meth0_version: function(args, msg) { this.meth_version(args, msg) },
        meth0_auth: function(args, msg) {
            log('meth_auth', args)
            if (this.api.checkAuth(args[0])) {
                log('authorize', true)
                this.api.answer([null, true, "authorized"], msg.id)
            } else {
                log('authorize', false)
                this.api.error({code:401, message:"Unauthorized"}, msg.id)
                this.api.shutdown()
            } },

        meth_bindEvent: function(args, msg) {
            log('meth_bindEvent', args)
            this.evtCtx[args[1]] = args[3]
            this.api.answer([null, true], msg.id) },
        meth_unbindEvent: function(args, msg) {
            log('meth_unbindEvent', args)
            this.api.answer([null, true], msg.id) },
        meth_perform: function(args, msg) {
            log('meth_perform', args)
            var self=this, cmd=this['cmd_'+args[1]] || this.cmd_mock
            cmd.call(this, args, function(res) {
                self.api.answer([null, res], msg.id) }) },

        cmd_mock: function(args, answer) {
            answer([null, {'a mock':'result'}]) },
        cmd_testEvent: function(args, answer) {
            log('cmd_testEvent', args)
            answer([null, true, 'firingTestEvent'])
            var resp = 'dyn_'+require('crypto').randomBytes(4).toString('hex')
            this['cmd_'+resp] = this.dynamic_response
            this.api.fireEvent('testEvent', 0, resp, this.evtCtx.testEvent) },
        dynamic_response: function(args, answer) {
            log('dynamic_response', args)
            answer([null, true, 'awesome'])
            this.api.fireEvent('testEvent', 0, null, this.evtCtx.testEvent) }
    };

    var test = createMockBelliteServer({
        port: opt.port, token: opt.token, debugLog: opt.debugLog,
        listening: function() {
            opt.execClient(spawnClient) },
        server_close: function() {},
        server_error: function(err) { log('server_error', err) },
        connect: function(api) {
            return Object.create(rpc).connect(api) }
    })

    function spawnClient(exec, args) {
        var cp = require('child_process')
        test.proc = cp.spawn(exec, args, {stdio:'inherit',cwd:__dirname})
        test.proc.on('exit', function(code, signal) {
            log('process_exit', code, signal)
            test.proc = false;
            done(code!==0 ? 'subprocess spawning error' : null) })
        return test.proc }

    function done(err) {
        if (done.timer)
            clearTimeout(done.timer)

        if (test.proc) {
            test.proc.kill()
            test.proc = null
        }
        if (test.shutdownTest) {
            test.shutdownTest()
            setTimeout(function() { doneCallback(err, opt.log, opt) }, 100)
        }}
    if (opt.timeout!==false)
        done.timer = setTimeout(function() {
            log('timeout'); done('timeout') }, opt.timeout || 2000)
}
exports.testBelliteJSONRPC = testBelliteJSONRPC;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function assetTestResults(err, log, opt) {
    var assert=require('assert');
    try {
        assert.equal(log.connect && log.connect.length, 1, "should connect exactly once")
        assert.equal(log.server_error, null, "should not experience server errors")
        assert.equal(log.conn_error, null, "should not experience connection errors")

        assert.equal(log.parse_error, null, "should not experience JSON parsing errors")
        assert.equal(log.response, null, "should not receive JSON-RPC 2.0 responses")

        assert.equal(log.meth_auth && log.meth_auth.length, 1, "should call auth exactly once")
        assert.deepEqual(log.authorize, [true], "should authorize successfully")

        assert.equal(log.meth_unknown, null, "should never call an unknown method")

        assert.deepEqual(log.meth_ping, [0], "should call ping once with no args")
        assert.deepEqual(log.meth_version, [0], "should call version once with no args")
        assert.equal(log.meth_perform && log.meth_perform.length, 3, "should call perform 3 times")
        assert.equal(log.meth_bindEvent && log.meth_bindEvent.length, 2, "should call bindEvent 3 times")
        assert.equal(log.meth_unbindEvent && log.meth_unbindEvent.length, 1, "should call unbindEvent 2 times")

        assert.deepEqual(log.cmd_testEvent, [[0, 'testEvent', null]], "should call testEvent")
        assert.equal(log.dynamic_response && log.dynamic_response.length, 1, "should call dynamic_response from event")

        assert.equal(err, null, "terminated with an error")

        console.log("All Bellite JSON-RPC protocol tests passed")
        process.exit(0) // success

    } catch(test_err) {
        console.log('\nBellite Mock Server Call Log:')
        console.log(log)
        console.log('\n')

        console.error(test_err.stack.split(/\n\s*/).slice(0,2).join('\n'))
        console.error(test_err)
        console.error()

        process.exit(1) // failure
    }
}
exports.assetTestResults = assetTestResults;

if (!module.parent) {
    // test the bellist JSON-RPC interactions
    testBelliteJSONRPC({
        debugLog: console.log,
        timeout: 2000,
        //timeout: false,
        //port: 3099,
        //token: 'bellite-demo-host',

        execClient: function(spawn) {
            spawn('python', [__dirname+'/_doBelliteTest.py'])
        }
    }, assetTestResults)
}
<commit_msg>Added optional cwd to spawnClient call<commit_after>/*-*- coding: utf-8 -*- vim: set ts=4 sw=4 expandtab
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
##~ Copyright (C) 2002-2012 Bellite.io                            ##
##~                                                               ##
##~ This library is free software; you can redistribute it        ##
##~ and/or modify it under the terms of the MIT style License as  ##
##~ found in the LICENSE file included with this distribution.    ##
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##*/

"use strict";
function createMockBelliteServer(ns) {
    var self = {
        server: require('net').createServer(),
        token: ns.token || require('crypto').randomBytes(8).toString('hex'),
        shutdownTest: function() {
            self.shutdownTest = null;
            if (self.server)
                self.server.close();
            self.allConnections.forEach(function(conn){
                if (conn) conn.end() }) },
        allConnections: [] }

    var debugLog = ns.debugLog

    self.server.on('listening', function () {
        var addr = this.address()
        self.env = addr.address+':'+addr.port+'/'+self.token
        process.env.BELLITE_SERVER = self.env
        if (debugLog) debugLog('Serving BELLITE_SERVER="'+ process.env.BELLITE_SERVER +'"')
        ns.listening();
    })

    self.server.on('connection', function (conn) {
        self.allConnections.push(conn)
        conn.setEncoding("UTF-8");
        conn.setNoDelay(true);
        conn.setKeepAlive(true, 0);

        var api = {
            sendMessage: function(msg) {
                if (debugLog) debugLog('reply  ==> ', msg);
                return conn.write(msg+'\0') },
            shutdown: function() { return conn.end() },
            fireEvent: function(evtType, selfId, evt, ctx) {
                return this.send('event', {evtType: evtType, selfId: selfId||0, evt:evt, ctx:ctx}) },
            send: function(method, params, id) {
                var msg = {jsonrpc: "2.0", id:id, method:method, params:params}
                return this.sendMessage(JSON.stringify(msg)) },
            answer: function(result, id) {
                if (id===undefined) return false;
                var msg = {jsonrpc: "2.0", id:id, result:result}
                return this.sendMessage(JSON.stringify(msg)) },
            error: function(error, id) {
                if (id===undefined) return false;
                var msg = {jsonrpc: "2.0", id:id, error:error}
                return this.sendMessage(JSON.stringify(msg)) },
            checkAuth: function(token) {
                clearTimeout(authTimeout);
                return this.authorized = (token == self.token) }
            },
            tgt = ns.connect(api),
            authTimeout = setTimeout(api.shutdown, 250);

        var connBuf='';
        conn.on('data', function(data) {
            data = (connBuf+data).split('\0')
            connBuf = data.pop()
            while (data.length) {
                var msg = data.shift();
                if (debugLog) debugLog('invoke <== ', msg);
                try { msg = JSON.parse(msg) }
                catch (err) { tgt.parse_error(err, msg); continue }
                if (msg.method!==undefined)
                    tgt.invoke(msg)
                else tgt.response(msg)
            } })
        conn.on('close', function() { tgt.conn_close() })
        conn.on('error', function(err) { tgt.conn_error(err) })
    })

    self.server.on('close', function() {
        self.server = null; ns.server_close() })
    self.server.on('error', function(err) {
        ns.server_error(err) })

    self.server.listen(ns.port || 0, '127.0.0.1')
    return self;
}
exports.createMockBelliteServer = createMockBelliteServer;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function testBelliteJSONRPC(opt, doneCallback) {
    opt.log = opt.log || {};
    function log(key, args) {
        var log=opt.log[key];
        if (!log) opt.log[key] = log = []
        var ea = Array.prototype.slice.call(arguments, 1);
        if (ea.length<2) ea = ea[0]===undefined ? 0 : ea[0];
        log.push(ea)
        return this }

    var rpc = {
        connect: function(api) {
            log('connect')
            this.api = api;
            this.evtCtx = {}
            return this },
        conn_close: function() { log('conn_close') },
        conn_error: function(err) { log('conn_error', err) },
        parse_error: function(err,msg) { log('parse_error', err, msg) },
        response: function(msg) { log('response', msg) },
        invoke: function(msg) {
            var pre = this.api.authorized ? 'meth_' : 'meth0_';
            var meth = this[pre+msg.method] || this.meth_unknown;
            log('invoke', pre+msg.method, msg.params)
            return meth.call(this, msg.params, msg)},

        meth_unknown: function(args, msg) {
            log('meth_unknown', msg.method, args)
            this.api.answer(["unknown method ", null], msg.id) },
        meth_ping: function(args, msg) {
            log('meth_ping', args)
            this.api.answer([null, true, "pong"], msg.id) },
        meth_version: function(args, msg) {
            log('meth_version', args)
            this.api.answer([null, {"server":"bellite", "version":"1.4.3", "platform":"node/test"}], msg.id) },

        meth0_ping: function(args, msg) { this.meth_ping(args, msg) },
        meth0_version: function(args, msg) { this.meth_version(args, msg) },
        meth0_auth: function(args, msg) {
            log('meth_auth', args)
            if (this.api.checkAuth(args[0])) {
                log('authorize', true)
                this.api.answer([null, true, "authorized"], msg.id)
            } else {
                log('authorize', false)
                this.api.error({code:401, message:"Unauthorized"}, msg.id)
                this.api.shutdown()
            } },

        meth_bindEvent: function(args, msg) {
            log('meth_bindEvent', args)
            this.evtCtx[args[1]] = args[3]
            this.api.answer([null, true], msg.id) },
        meth_unbindEvent: function(args, msg) {
            log('meth_unbindEvent', args)
            this.api.answer([null, true], msg.id) },
        meth_perform: function(args, msg) {
            log('meth_perform', args)
            var self=this, cmd=this['cmd_'+args[1]] || this.cmd_mock
            cmd.call(this, args, function(res) {
                self.api.answer([null, res], msg.id) }) },

        cmd_mock: function(args, answer) {
            answer([null, {'a mock':'result'}]) },
        cmd_testEvent: function(args, answer) {
            log('cmd_testEvent', args)
            answer([null, true, 'firingTestEvent'])
            var resp = 'dyn_'+require('crypto').randomBytes(4).toString('hex')
            this['cmd_'+resp] = this.dynamic_response
            this.api.fireEvent('testEvent', 0, resp, this.evtCtx.testEvent) },
        dynamic_response: function(args, answer) {
            log('dynamic_response', args)
            answer([null, true, 'awesome'])
            this.api.fireEvent('testEvent', 0, null, this.evtCtx.testEvent) }
    };

    var test = createMockBelliteServer({
        port: opt.port, token: opt.token, debugLog: opt.debugLog,
        listening: function() {
            opt.execClient(spawnClient) },
        server_close: function() {},
        server_error: function(err) { log('server_error', err) },
        connect: function(api) {
            return Object.create(rpc).connect(api) }
    })

    function spawnClient(exec, args, cwd) {
        var cp = require('child_process')
        test.proc = cp.spawn(exec, args, {stdio:'inherit',cwd:cwd||__dirname})
        test.proc.on('exit', function(code, signal) {
            log('process_exit', code, signal)
            test.proc = false;
            done(code!==0 ? 'subprocess spawning error' : null) })
        return test.proc }

    function done(err) {
        if (done.timer)
            clearTimeout(done.timer)

        if (test.proc) {
            test.proc.kill()
            test.proc = null
        }
        if (test.shutdownTest) {
            test.shutdownTest()
            setTimeout(function() { doneCallback(err, opt.log, opt) }, 100)
        }}
    if (opt.timeout!==false)
        done.timer = setTimeout(function() {
            log('timeout'); done('timeout') }, opt.timeout || 2000)
}
exports.testBelliteJSONRPC = testBelliteJSONRPC;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function assetTestResults(err, log, opt) {
    var assert=require('assert');
    try {
        assert.equal(log.connect && log.connect.length, 1, "should connect exactly once")
        assert.equal(log.server_error, null, "should not experience server errors")
        assert.equal(log.conn_error, null, "should not experience connection errors")

        assert.equal(log.parse_error, null, "should not experience JSON parsing errors")
        assert.equal(log.response, null, "should not receive JSON-RPC 2.0 responses")

        assert.equal(log.meth_auth && log.meth_auth.length, 1, "should call auth exactly once")
        assert.deepEqual(log.authorize, [true], "should authorize successfully")

        assert.equal(log.meth_unknown, null, "should never call an unknown method")

        assert.deepEqual(log.meth_ping, [0], "should call ping once with no args")
        assert.deepEqual(log.meth_version, [0], "should call version once with no args")
        assert.equal(log.meth_perform && log.meth_perform.length, 3, "should call perform 3 times")
        assert.equal(log.meth_bindEvent && log.meth_bindEvent.length, 2, "should call bindEvent 3 times")
        assert.equal(log.meth_unbindEvent && log.meth_unbindEvent.length, 1, "should call unbindEvent 2 times")

        assert.deepEqual(log.cmd_testEvent, [[0, 'testEvent', null]], "should call testEvent")
        assert.equal(log.dynamic_response && log.dynamic_response.length, 1, "should call dynamic_response from event")

        assert.equal(err, null, "terminated with an error")

        console.log("All Bellite JSON-RPC protocol tests passed")
        process.exit(0) // success

    } catch(test_err) {
        console.log('\nBellite Mock Server Call Log:')
        console.log(log)
        console.log('\n')

        console.error(test_err.stack.split(/\n\s*/).slice(0,2).join('\n'))
        console.error(test_err)
        console.error()

        process.exit(1) // failure
    }
}
exports.assetTestResults = assetTestResults;

if (!module.parent) {
    // test the bellist JSON-RPC interactions
    testBelliteJSONRPC({
        debugLog: console.log,
        timeout: 2000,
        //timeout: false,
        //port: 3099,
        //token: 'bellite-demo-host',

        execClient: function(spawn) {
            spawn('python', [__dirname+'/_doBelliteTest.py'])
        }
    }, assetTestResults)
}
<|endoftext|>


<commit_before>$(document).ready(function() {

  $('.welcome-login').on("click", function(event){
    event.preventDefault();
    $('#login_form').toggle();
  });

  $('.login-ajax').on("submit", function(event){
    event.preventDefault();
    var $target = $(event.target)

    $.ajax({
      type: $target.attr("method"),
      url: $target.attr("action"),
      data: $target.serialize(),
      success: function(response){
        $('#content').empty();
        $('#content').append(response);
        // $('.welcome-login').toggle();
        // $('.welcome-signup').toggle();
      }
    });
  });

   $('.welcome-signup').on("click", function(event){
    event.preventDefault();
    $('#signup_form').toggle();
  });

   $('.signup-ajax').on("submit", function(event){
    event.preventDefault();
    var $target = $(event.target)

    $.ajax({
      type: $target.attr("method"),
      url: $target.attr("action"),
      data: $target.serialize(),
      success: function(response){
        $('#content').empty();
        $('#content').append(response);
        // $('.welcome-login').toggle();
        // $('.welcome-signup').toggle();
      }
    });
  });

$('a img.heart').on("click", function(event){
    event.preventDefault();
    // console.log(event);
    var $target = $(event.target)
    // debugger

    $.ajax({
      type: $target.data("method"),
      url: $target.data("action"),
      data: $target.data(),
      success: function(response){
        console.log("in success")
        console.log(response)
        console.log("target",$target)
        console.log($('#' + $target.data('article_id')))
        $('#' + $target.data('article_id')).empty();
        $('#' + $target.data('article_id')).append(response);
        // $('body').empty();
        // $('body').append(response);
      }
    });
  });

$('a#show-articles-btn').on("click", function(event){
    event.preventDefault();
    var $target = $(event.currentTarget)
    // debugger
    $.ajax({
      type: "GET",
      url: $target.attr('href'),
      success: function(response){
        console.log(response)
        $('#content').append(response);
      }
    });
  });
});<commit_msg>update welcome page view<commit_after>$(document).ready(function() {

  $('.welcome-login').on("click", function(event){
    event.preventDefault();
    $('#signup_form').hide();
    $('#login_form').toggle();
  });

  $('.login-ajax').on("submit", function(event){
    event.preventDefault();
    var $target = $(event.target)

    $.ajax({
      type: $target.attr("method"),
      url: $target.attr("action"),
      data: $target.serialize(),
      success: function(response){
        $('#content').empty();
        $('#content').append(response);
        // $('.welcome-login').toggle();
        // $('.welcome-signup').toggle();
      }
    });
  });

   $('.welcome-signup').on("click", function(event){
    event.preventDefault();
    $('#login_form').hide();
    $('#signup_form').toggle();
  });

   $('.signup-ajax').on("submit", function(event){
    event.preventDefault();
    var $target = $(event.target)

    $.ajax({
      type: $target.attr("method"),
      url: $target.attr("action"),
      data: $target.serialize(),
      success: function(response){
        $('#content').empty();
        $('#content').append(response);
        // $('.welcome-login').toggle();
        // $('.welcome-signup').toggle();
      }
    });
  });

$('a img.heart').on("click", function(event){
    event.preventDefault();
    // console.log(event);
    var $target = $(event.target)
    // debugger

    $.ajax({
      type: $target.data("method"),
      url: $target.data("action"),
      data: $target.data(),
      success: function(response){
        console.log("in success")
        console.log(response)
        console.log("target",$target)
        console.log($('#' + $target.data('article_id')))
        $('#' + $target.data('article_id')).empty();
        $('#' + $target.data('article_id')).append(response);
        // $('body').empty();
        // $('body').append(response);
      }
    });
  });

$('a#show-articles-btn').on("click", function(event){
    event.preventDefault();
    var $target = $(event.currentTarget)
    // debugger
    $.ajax({
      type: "GET",
      url: $target.attr('href'),
      success: function(response){
        console.log(response)
        $('#content').append(response);
      }
    });
  });
});<|endoftext|>


<commit_before>const fs = require('fs');

fs.copyFile('./src/Calendar.less', 'dist/Calendar.less', (error) => {
  if (error) {
    throw error;
  }
  // eslint-disable-next-line no-console
  console.log('Calendar.less copied successfully.');
});

fs.copyFile('./src/Calendar.css', 'dist/Calendar.css', (error) => {
  if (error) {
    throw error;
  }
  // eslint-disable-next-line no-console
  console.log('Calendar.css copied successfully.');
});
<commit_msg>Simplify paths in copy-styles<commit_after>const fs = require('fs');

fs.copyFile('src/Calendar.less', 'dist/Calendar.less', (error) => {
  if (error) {
    throw error;
  }
  // eslint-disable-next-line no-console
  console.log('Calendar.less copied successfully.');
});

fs.copyFile('src/Calendar.css', 'dist/Calendar.css', (error) => {
  if (error) {
    throw error;
  }
  // eslint-disable-next-line no-console
  console.log('Calendar.css copied successfully.');
});
<|endoftext|>


<commit_before>'use strict';

var rp = window.require('request-promise')
var _  = require('lodash')

var SoundCloud = function(options) {
  this._endpoint   = 'http://api.soundcloud.com/'
  this._token      = undefined
  this._clientId   = undefined
}

SoundCloud.prototype.initialize = function(options) {

  if (!options.client_id)
    throw new Error('Could not initialize SoundCloud. Missing `client_id`.')

  if (!options.access_token)
    throw new Error('Could not initialize SoundCloud. Missing `access_token`.')

  this._endpoint  = this._endpoint || options.endpoint
  this._token     = options.access_token
  this._clientId  = options.client_id
}

SoundCloud.prototype.makeRequest = function(url, options) {
  var self = this
  options  = options || {}

  if (typeof url === 'object')
    options = url
  else if (typeof url === 'string' && url.indexOf('://') === -1)
    options.url = this._endpoint + url
  else if (typeof url === 'string' && url.indexOf('://') !== -1)
    options.url = url

  var defaults = {
    'method'        : 'GET',
    'json'          : true,
    'qs'            : _.defaults(options.qs || {}, {
      'client_id'   : self._clientId,
      'oauth_token' : self._token,
      'limit'       : 50
    })
  }

  options = _.defaults(options, defaults)

  return rp(options)
}

SoundCloud.prototype._mapTrack = function(track) {
  if (track.stream_url) // append client_id for audio stream access
    track.stream_url += '?client_id=' + this._clientId

  if (track.artwork_url)
    track.artwork_url = _artworkFormat(track.artwork_url, 'crop');

  if (track.user.avatar_url)
    track.user.avatar_url = _artworkFormat(track.user.avatar_url, 'crop');

  return track
}

SoundCloud.prototype.fetchVisual = function(trackId) {
  return rp({
    url  : 'https://visuals.soundcloud.com/visuals?urn=soundcloud:sounds:' + trackId,
    json : true,
    transform: function(body) {
      return body.visuals ? body.visuals[0].visual_url : null
    }
  })
}

SoundCloud.prototype.fetchWaveform = function(url) {
  return this.makeRequest(url)
    .then(function(resp) {
      return resp.samples
    })
}

SoundCloud.prototype.fetchLikes = function(options) {
  options = options || {}
  var self = this

  var next_href = options.next_href

  var url = next_href || 'me/favorites?linked_partitioning=1'

  return this.makeRequest(url)
    .then(function(resp) {
      next_href = resp.next_href
      return resp.collection
    })
    .bind(self)
    .map(self._mapTrack)
    .then(function(tracks) {
      return {
        tracks    : tracks,
        next_href : next_href
      }
    })
}

SoundCloud.prototype.fetchFeed = function(options) {
  options = options || {}
  var self = this

  var future_href = options.future_href
  var next_href = options.next_href

  var url = future_href || next_href || 'me/activities'
  var reqOpts = {}

  if (options.future_href)
    reqOpts = { qs : { limit : 200 } }

  return self.makeRequest(url, reqOpts)
    .then(function(resp) {
      next_href = resp.next_href
      future_href = resp.next_href
      return resp.collection
    })
    // filter out items with no origin (track-repost)
    .reduce(function(tracks, item) {
      if (item.origin) tracks.push(item)
      return tracks
    }, [])
    .map(function(item) {
      return item.origin
    })
    .map(function(item) {
      if (item.kind === 'playlist')
        return self.expandPlaylist(item)
      else if (item.kind === 'track')
        return self._mapTrack(item)
    })
    .then(function(tracks) {
      // SoundCloud activities can return multiple of the same track
      tracks = _.uniq(tracks, 'id')
      return {
        tracks      : tracks,
        next_href   : next_href,
        future_href : future_href
      }
    })
}

SoundCloud.prototype._fetchPlaylists = function(resp) {
  return resp.map(this._mapTrack)
  .map(function(playlist) {
    playlist.tracks = _.map(playlist.tracks, function(track) {
      return this._mapTrack(track)
    }.bind(this))
    return playlist
  })
}

SoundCloud.prototype.fetchPlaylists = function() {
  return this.makeRequest('me/playlists')
    .then()
    .bind(this)
    .then(funtion(playlists) {
      return this._fetchPlaylists(playlists)
    })
}

SoundCloud.prototype.fetchPlaylistLikes = function() {
  return this.makeRequest('e1/me/playlist_likes')
    .then()
    .bind(this)
    .map(function(resp) {
      return resp.playlist
    })
    .then(funtion(playlists) {
      return this._fetchPlaylists(playlists)
    })
}

SoundCloud.prototype.expandPlaylist = function(playlist) {
  if (!playlist.hasOwnProperty('tracks_uri') || playlist.kind !== 'playlist')
    return

  return this.makeRequest(playlist.tracks_uri)
    .then(function(tracks) {
      playlist.tracks = tracks
      return tracks
    })
    .bind(this)
    .map(this._mapTrack)
    .then(function() {
      return playlist
    })
}

SoundCloud.prototype.toggleLikeTrack = function(track) {
  var method = track.user_favorite ? 'DELETE' : 'PUT';
  return this.makeRequest('me/favorites/' + track.id, { method : method });
}

/**
 * Grab different resolution of artwork
 */
function _artworkFormat(url, size) {
  size = size || 't300x300';
  return url.replace('-large', '-' + size);
}

module.exports = new SoundCloud();
<commit_msg>Fix typo. Revert without function.<commit_after>'use strict';

var rp = window.require('request-promise')
var _  = require('lodash')

var SoundCloud = function(options) {
  this._endpoint   = 'http://api.soundcloud.com/'
  this._token      = undefined
  this._clientId   = undefined
}

SoundCloud.prototype.initialize = function(options) {

  if (!options.client_id)
    throw new Error('Could not initialize SoundCloud. Missing `client_id`.')

  if (!options.access_token)
    throw new Error('Could not initialize SoundCloud. Missing `access_token`.')

  this._endpoint  = this._endpoint || options.endpoint
  this._token     = options.access_token
  this._clientId  = options.client_id
}

SoundCloud.prototype.makeRequest = function(url, options) {
  var self = this
  options  = options || {}

  if (typeof url === 'object')
    options = url
  else if (typeof url === 'string' && url.indexOf('://') === -1)
    options.url = this._endpoint + url
  else if (typeof url === 'string' && url.indexOf('://') !== -1)
    options.url = url

  var defaults = {
    'method'        : 'GET',
    'json'          : true,
    'qs'            : _.defaults(options.qs || {}, {
      'client_id'   : self._clientId,
      'oauth_token' : self._token,
      'limit'       : 50
    })
  }

  options = _.defaults(options, defaults)

  return rp(options)
}

SoundCloud.prototype._mapTrack = function(track) {
  if (track.stream_url) // append client_id for audio stream access
    track.stream_url += '?client_id=' + this._clientId

  if (track.artwork_url)
    track.artwork_url = _artworkFormat(track.artwork_url, 'crop');

  if (track.user.avatar_url)
    track.user.avatar_url = _artworkFormat(track.user.avatar_url, 'crop');

  return track
}

SoundCloud.prototype.fetchVisual = function(trackId) {
  return rp({
    url  : 'https://visuals.soundcloud.com/visuals?urn=soundcloud:sounds:' + trackId,
    json : true,
    transform: function(body) {
      return body.visuals ? body.visuals[0].visual_url : null
    }
  })
}

SoundCloud.prototype.fetchWaveform = function(url) {
  return this.makeRequest(url)
    .then(function(resp) {
      return resp.samples
    })
}

SoundCloud.prototype.fetchLikes = function(options) {
  options = options || {}
  var self = this

  var next_href = options.next_href

  var url = next_href || 'me/favorites?linked_partitioning=1'

  return this.makeRequest(url)
    .then(function(resp) {
      next_href = resp.next_href
      return resp.collection
    })
    .bind(self)
    .map(self._mapTrack)
    .then(function(tracks) {
      return {
        tracks    : tracks,
        next_href : next_href
      }
    })
}

SoundCloud.prototype.fetchFeed = function(options) {
  options = options || {}
  var self = this

  var future_href = options.future_href
  var next_href = options.next_href

  var url = future_href || next_href || 'me/activities'
  var reqOpts = {}

  if (options.future_href)
    reqOpts = { qs : { limit : 200 } }

  return self.makeRequest(url, reqOpts)
    .then(function(resp) {
      next_href = resp.next_href
      future_href = resp.next_href
      return resp.collection
    })
    // filter out items with no origin (track-repost)
    .reduce(function(tracks, item) {
      if (item.origin) tracks.push(item)
      return tracks
    }, [])
    .map(function(item) {
      return item.origin
    })
    .map(function(item) {
      if (item.kind === 'playlist')
        return self.expandPlaylist(item)
      else if (item.kind === 'track')
        return self._mapTrack(item)
    })
    .then(function(tracks) {
      // SoundCloud activities can return multiple of the same track
      tracks = _.uniq(tracks, 'id')
      return {
        tracks      : tracks,
        next_href   : next_href,
        future_href : future_href
      }
    })
}

SoundCloud.prototype.fetchPlaylists = function() {
  return this.makeRequest('me/playlists')
    .then()
    .bind(this)
    .map(this._mapTrack)
    .map(function(playlist) {
      playlist.tracks = _.map(playlist.tracks, function(track) {
        return this._mapTrack(track)
      }.bind(this))
      return playlist
    })
}

SoundCloud.prototype.fetchPlaylistLikes = function() {
  return this.makeRequest('e1/me/playlist_likes')
    .then()
    .bind(this)
    .map(function(resp) {
      return resp.playlist
    })
    .map(this._mapTrack)
    .map(function(playlist) {
      playlist.tracks = _.map(playlist.tracks, function(track) {
        return this._mapTrack(track)
      }.bind(this))
      return playlist
    })
}

SoundCloud.prototype.expandPlaylist = function(playlist) {
  if (!playlist.hasOwnProperty('tracks_uri') || playlist.kind !== 'playlist')
    return

  return this.makeRequest(playlist.tracks_uri)
    .then(function(tracks) {
      playlist.tracks = tracks
      return tracks
    })
    .bind(this)
    .map(this._mapTrack)
    .then(function() {
      return playlist
    })
}

SoundCloud.prototype.toggleLikeTrack = function(track) {
  var method = track.user_favorite ? 'DELETE' : 'PUT';
  return this.makeRequest('me/favorites/' + track.id, { method : method });
}

/**
 * Grab different resolution of artwork
 */
function _artworkFormat(url, size) {
  size = size || 't300x300';
  return url.replace('-large', '-' + size);
}

module.exports = new SoundCloud();
<|endoftext|>


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

(function($, undefined) {
    if($ == undefined)
        throw "jQuery not loaded";

    $.gsUserName = null;
    $.gsToken = null;
    $.accession = null;
    $.gsTargetDir = null;

    function
    gsLoggedIn( gsUserName, gsToken )
    {
        $("#gs_auth_username").html(gsUserName);
        $("#gs_login_section").hide();
        $("#gs_upload_section").show();

        if ($.browser.msie) {
            $.gsToken = gsToken;
            checkGSTargetDirectory();
        } else {
            $.when(retrieveGSUserInformation()).then( function(json) {
                $.gsToken = json.token;
                checkGSTargetDirectory();
            });
        }
    }

    function
    gsLoggedOut()
    {
        $.gsToken = null;

        $("#gs_auth_status").html("");
        $("#gs_login_section").show();
        $("#gs_upload_section").hide();
    }

    function
    checkIfLoggedToGS( onLoggedInFunc, onLoggedOutFunc )
    {
        if ($.browser.msie) {
            var userName = $.cookie("gs-username");
            var token = $.cookie("gs-token");
            if (null != userName && null != token) {
                onLoggedInFunc(userName, token);
            } else {
                onLoggedOutFunc();
            }
        } else {
            $.ajax({
                url : "https://identity.genomespace.org/identityServer/usermanagement/utility/token/username"
                , xhrFields: { withCredentials: true }
                , success : onLoggedInFunc
                , error : onLoggedOutFunc
            });
        }
    }

    function
    checkGSMessage()
    {
        var message = $.cookie("gs-auth-message");
        if (null != message) {
            $("#gs_auth_message").html(message.replace(/^"?(.+[^"])"?$/g, "$1")).show();
            $.cookie("gs-auth-message", null, {path: contextPath});
        }
    }

    function
    retrieveGSUserInformation()
    {
        var dfr = $.Deferred();

        $.ajax({
            url : "https://identity.genomespace.org/identityServer/selfmanagement/user"
            , xhrFields: { withCredentials: true }
            , success : dfr.resolve
            , error: dfr.reject
            , dataType: "json"
        });

        return dfr.promise();
    }

    function
    checkGSTargetDirectory()
    {
        $.ajax({
            url : contextPath + "/gs/upload"
            , data: { action: "checkDirectory"
                , accession: $.accession
                , token: $.gsToken
            }
            , dataType: "json"
            , success : function(json) {
                if (null != json) {
                    if ("exists" == json.status ) {
                        $.gsTargetDir = json.target;
                        $("#gs_target_dir").html("/ArrayExpress/" + $.accession);
                        $("#gs_warning").show();
                    }
                }
            }
        });
    }

    function
    gsUploadFile(fileName)
    {
        var dfr = $.Deferred();

        $.ajax({
            url : contextPath + "/gs/upload"
            , data: { action: "uploadFile"
                , accession: $.accession
                , filename: fileName
                , target:  $.gsTargetDir
                , token: $.gsToken
            }
            , dataType: "json"
            , success : dfr.resolve
            , error: dfr.reject

        });

        return dfr.promise();
    }

    function
    gsCreateTargetDirectory()
    {
        var dfr = $.Deferred();

        $.ajax({
            url : contextPath + "/gs/upload"
            , data: { action: "createDirectory"
                , accession: $.accession
                , token: $.gsToken
            }
            , dataType: "json"
            , success : dfr.resolve
            , error: dfr.reject
        });

        return dfr.promise();
    }

    function
    uploadFile(counter)
    {
        var $check = $("#file_" + counter + "_check");
        if (0 != $check.length) {
            if ($check.prop("checked")) {
                var fileName = $("#file_" + counter + "_name").val();
                $.progressStatus.html("Sending " + fileName + " to GenomeSpace...");
                $check.prop("disabled", true);
                $("#file_" + counter + "_progress").addClass("in_progress");
                $.when(gsUploadFile(fileName)).then(function() {
                    $("#file_" + counter + "_progress").removeClass("in_progress").addClass("ok");
                    uploadFile(counter + 1);
                }, function() {
                    $("#file_" + counter + "_progress").removeClass("in_progress").addClass("failed");
                    $.progressStatus.html("There was an error uploading " + fileName + " to GenomeSpace.");
                    reEnableForm();
                })
            } else {
                uploadFile(counter + 1);
            }
        } else {
            if (counter > 1) {
                $.progressStatus.html("Upload completed. Please follow this link to open GenomeSpace UI.");
            } else {
                $.progressStatus.html("");
            }
            reEnableForm();
        }
    }

    function
    uploadFiles()
    {
        // first - disable submit button to prevent second event call
        var $this = $(this);
        $this.prop("disabled", true);
        $(".file_div > span").removeClass();

        if (null == $.gsTargetDir) {
            $.progressStatus.html("Creating target directory in GenomeSpace...");

            $.when(gsCreateTargetDirectory()).then(function(json) {
                $.gsTargetDir = json.target;
                uploadFile(1);
            }, function() {
                // directory creation went wrong?
                $.progressStatus.html("There was an error creating target directory in GenomeSpace.");
                $this.removeProp("disabled");
            });
        } else {
            uploadFile(1);
        }
    }

    function
    reEnableForm()
    {
        $("#gs_upload_submit").removeProp("disabled");
        $(".file_check").removeProp("disabled");
    }

    $(function() {
        $.accession = $("#ae_accession").val();
        $.progressStatus = $("#gs_progress_status");
        checkGSMessage();
        checkIfLoggedToGS(gsLoggedIn, gsLoggedOut);
        $("#gs_upload_submit").click(uploadFiles);
    });

})(window.jQuery);<commit_msg>- rewording of status<commit_after>/*
 * Copyright 2009-2012 European Molecular Biology Laboratory
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

(function($, undefined) {
    if($ == undefined)
        throw "jQuery not loaded";

    $.gsUserName = null;
    $.gsToken = null;
    $.accession = null;
    $.gsTargetDir = null;

    function
    gsLoggedIn( gsUserName, gsToken )
    {
        $("#gs_auth_username").html(gsUserName);
        $("#gs_login_section").hide();
        $("#gs_upload_section").show();

        if ($.browser.msie) {
            $.gsToken = gsToken;
            checkGSTargetDirectory();
        } else {
            $.when(retrieveGSUserInformation()).then( function(json) {
                $.gsToken = json.token;
                checkGSTargetDirectory();
            });
        }
    }

    function
    gsLoggedOut()
    {
        $.gsToken = null;

        $("#gs_auth_status").html("");
        $("#gs_login_section").show();
        $("#gs_upload_section").hide();
    }

    function
    checkIfLoggedToGS( onLoggedInFunc, onLoggedOutFunc )
    {
        if ($.browser.msie) {
            var userName = $.cookie("gs-username");
            var token = $.cookie("gs-token");
            if (null != userName && null != token) {
                onLoggedInFunc(userName, token);
            } else {
                onLoggedOutFunc();
            }
        } else {
            $.ajax({
                url : "https://identity.genomespace.org/identityServer/usermanagement/utility/token/username"
                , xhrFields: { withCredentials: true }
                , success : onLoggedInFunc
                , error : onLoggedOutFunc
            });
        }
    }

    function
    checkGSMessage()
    {
        var message = $.cookie("gs-auth-message");
        if (null != message) {
            $("#gs_auth_message").html(message.replace(/^"?(.+[^"])"?$/g, "$1")).show();
            $.cookie("gs-auth-message", null, {path: contextPath});
        }
    }

    function
    retrieveGSUserInformation()
    {
        var dfr = $.Deferred();

        $.ajax({
            url : "https://identity.genomespace.org/identityServer/selfmanagement/user"
            , xhrFields: { withCredentials: true }
            , success : dfr.resolve
            , error: dfr.reject
            , dataType: "json"
        });

        return dfr.promise();
    }

    function
    checkGSTargetDirectory()
    {
        $.ajax({
            url : contextPath + "/gs/upload"
            , data: { action: "checkDirectory"
                , accession: $.accession
                , token: $.gsToken
            }
            , dataType: "json"
            , success : function(json) {
                if (null != json) {
                    if ("exists" == json.status ) {
                        $.gsTargetDir = json.target;
                        $("#gs_target_dir").html("/ArrayExpress/" + $.accession);
                        $("#gs_warning").show();
                    }
                }
            }
        });
    }

    function
    gsUploadFile(fileName)
    {
        var dfr = $.Deferred();

        $.ajax({
            url : contextPath + "/gs/upload"
            , data: { action: "uploadFile"
                , accession: $.accession
                , filename: fileName
                , target:  $.gsTargetDir
                , token: $.gsToken
            }
            , dataType: "json"
            , success : dfr.resolve
            , error: dfr.reject

        });

        return dfr.promise();
    }

    function
    gsCreateTargetDirectory()
    {
        var dfr = $.Deferred();

        $.ajax({
            url : contextPath + "/gs/upload"
            , data: { action: "createDirectory"
                , accession: $.accession
                , token: $.gsToken
            }
            , dataType: "json"
            , success : dfr.resolve
            , error: dfr.reject
        });

        return dfr.promise();
    }

    function
    uploadFile(counter)
    {
        var $check = $("#file_" + counter + "_check");
        if (0 != $check.length) {
            if ($check.prop("checked")) {
                var fileName = $("#file_" + counter + "_name").val();
                $.progressStatus.html("Uploading " + fileName + " to GenomeSpace...");
                $check.prop("disabled", true);
                $("#file_" + counter + "_progress").addClass("in_progress");
                $.when(gsUploadFile(fileName)).then(function() {
                    $("#file_" + counter + "_progress").removeClass("in_progress").addClass("ok");
                    uploadFile(counter + 1);
                }, function() {
                    $("#file_" + counter + "_progress").removeClass("in_progress").addClass("failed");
                    $.progressStatus.html("There was an error uploading " + fileName + " to GenomeSpace.");
                    reEnableForm();
                })
            } else {
                uploadFile(counter + 1);
            }
        } else {
            if (counter > 1) {
                $.progressStatus.html("Upload completed. Please follow this link to open GenomeSpace UI.");
            } else {
                $.progressStatus.html("");
            }
            reEnableForm();
        }
    }

    function
    uploadFiles()
    {
        // first - disable submit button to prevent second event call
        var $this = $(this);
        $this.prop("disabled", true);
        $(".file_div > span").removeClass();

        if (null == $.gsTargetDir) {
            $.progressStatus.html("Creating target directory in GenomeSpace...");

            $.when(gsCreateTargetDirectory()).then(function(json) {
                $.gsTargetDir = json.target;
                uploadFile(1);
            }, function() {
                // directory creation went wrong?
                $.progressStatus.html("There was an error creating target directory in GenomeSpace.");
                $this.removeProp("disabled");
            });
        } else {
            uploadFile(1);
        }
    }

    function
    reEnableForm()
    {
        $("#gs_upload_submit").removeProp("disabled");
        $(".file_check").removeProp("disabled");
    }

    $(function() {
        $.accession = $("#ae_accession").val();
        $.progressStatus = $("#gs_progress_status");
        checkGSMessage();
        checkIfLoggedToGS(gsLoggedIn, gsLoggedOut);
        $("#gs_upload_submit").click(uploadFiles);
    });

})(window.jQuery);<|endoftext|>


<commit_before>/* global BreakString:true */

var updateRelativeAge, autoUpdatingRelativeAge, relativeAge, relativeAgeTiny,
    relativeAgeMedium, relativeAgeMediumSpan, longDate, longDateNoYear, toTitleCase,
    shortDate, shortDateNoYear, tinyDateYear, relativeAgeTinyShowsYear;

/*
* memoize.js
* by @philogb and @addyosmani
* with further optimizations by @mathias
* and @DmitryBaranovsk
* perf tests: http://bit.ly/q3zpG3
* Released under an MIT license.
*
* modified with cap by Sam
*/
var cappedMemoize = function ( fn, max ) {
    fn.maxMemoize = max;
    fn.memoizeLength = 0;

    return function () {
        var args = Array.prototype.slice.call(arguments),
            hash = "",
            i = args.length;
        var currentArg = null;
        while (i--) {
            currentArg = args[i];
            hash += (currentArg === new Object(currentArg)) ?
            JSON.stringify(currentArg) : currentArg;
            if(!fn.memoize) {
              fn.memoize = {};
            }
        }
        if (hash in fn.memoize) {
          return fn.memoize[hash];
        } else {
          fn.memoizeLength++;
          if(fn.memoizeLength > max) {
            fn.memoizeLength = 0;
            fn.memoize = {};
          }
          var result = fn.apply(this, args);
          fn.memoize[hash] = result;
          return result;
        }
    };
};

var breakUp = cappedMemoize(function(str, hint){
  return new BreakString(str).break(hint);
}, 100);

shortDate = function(date){
  return moment(date).format(I18n.t("dates.medium.date_year"));
};

shortDateNoYear = function(date) {
  return moment(date).format(I18n.t("dates.tiny.date_month"));
};

tinyDateYear = function(date) {
  return moment(date).format(I18n.t("dates.tiny.date_year"));
};

// http://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript
// TODO: locale support ?
toTitleCase = function toTitleCase(str) {
  return str.replace(/\w\S*/g, function(txt){
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });
};

longDate = function(dt) {
  if (!dt) return;
  return moment(dt).longDate();
};

// suppress year, if current year
longDateNoYear = function(dt) {
  if (!dt) return;

  if ((new Date()).getFullYear() !== dt.getFullYear()) {
    return moment(dt).format(I18n.t("dates.long_date_with_year"));
  } else {
    return moment(dt).format(I18n.t("dates.long_date_without_year"));
  }
};

updateRelativeAge = function(elems) {
  // jQuery .each
  elems.each(function(){
    var $this = $(this);
    $this.html(relativeAge(new Date($this.data('time')), {format: $this.data('format'), wrapInSpan: false}));
  });
};

autoUpdatingRelativeAge = function(date,options) {
  if (!date) return "";
  if (+date === +new Date(0)) return "";

  options = options || {};
  var format = options.format || "tiny";

  var append = "";

  if(format === 'medium') {
    append = " date";
    if(options.leaveAgo) {
      format = 'medium-with-ago';
    }
    options.wrapInSpan = false;
  }

  var relAge = relativeAge(date, options);

  if (format === 'tiny' && relativeAgeTinyShowsYear(relAge)) {
    append += " with-year";
  }

  if (options.title) {
    append += "' title='" + longDate(date);
  }

  return "" + relAge  + "";
};

relativeAgeTiny = function(date){
  var format = "tiny";
  var distance = Math.round((new Date() - date) / 1000);
  var distanceInMinutes = Math.round(distance / 60.0);

  var formatted;
  var t = function(key,opts){
    return I18n.t("dates." + format + "." + key, opts);
  };

  switch(true){

  case(distanceInMinutes < 1):
    formatted = t("less_than_x_minutes", {count: 1});
    break;
  case(distanceInMinutes >= 1 && distanceInMinutes <= 44):
    formatted = t("x_minutes", {count: distanceInMinutes});
    break;
  case(distanceInMinutes >= 45 && distanceInMinutes <= 89):
    formatted = t("about_x_hours", {count: 1});
    break;
  case(distanceInMinutes >= 90 && distanceInMinutes <= 1439):
    formatted = t("about_x_hours", {count: Math.round(distanceInMinutes / 60.0)});
    break;
  case(Discourse.SiteSettings.relative_date_duration === 0 && distanceInMinutes <= 525599):
    formatted = shortDateNoYear(date);
    break;
  case(distanceInMinutes >= 1440 && distanceInMinutes <= 2519):
    formatted = t("x_days", {count: 1});
    break;
  case(distanceInMinutes >= 2520 && distanceInMinutes <= ((Discourse.SiteSettings.relative_date_duration||14) * 1440)):
    formatted = t("x_days", {count: Math.round(distanceInMinutes / 1440.0)});
    break;
  default:
    if(date.getFullYear() === new Date().getFullYear()) {
      formatted = shortDateNoYear(date);
    } else {
      formatted = tinyDateYear(date);
    }
    break;
  }

  return formatted;
};

/*
 * Returns true if the given tiny date string includes the year.
 * Useful for checking if the string isn't so tiny.
 */
relativeAgeTinyShowsYear = function(relativeAgeString) {
  return relativeAgeString.match(/'[\d]{2}$/);
};

relativeAgeMediumSpan = function(distance, leaveAgo) {
  var formatted, distanceInMinutes;

  distanceInMinutes = Math.round(distance / 60.0);

  var t = function(key, opts){
    return I18n.t("dates.medium" + (leaveAgo?"_with_ago":"") + "." + key, opts);
  };

  switch(true){
  case(distanceInMinutes >= 1 && distanceInMinutes <= 56):
    formatted = t("x_minutes", {count: distanceInMinutes});
    break;
  case(distanceInMinutes >= 56 && distanceInMinutes <= 89):
    formatted = t("x_hours", {count: 1});
    break;
  case(distanceInMinutes >= 90 && distanceInMinutes <= 1379):
    formatted = t("x_hours", {count: Math.round(distanceInMinutes / 60.0)});
    break;
  case(distanceInMinutes >= 1380 && distanceInMinutes <= 2159):
    formatted = t("x_days", {count: 1});
    break;
  case(distanceInMinutes >= 2160):
    formatted = t("x_days", {count: Math.round((distanceInMinutes - 720.0) / 1440.0)});
    break;
  }
  return formatted || '&mdash';
};

relativeAgeMedium = function(date, options){
  var displayDate, fiveDaysAgo, oneMinuteAgo, fullReadable, leaveAgo;
  var wrapInSpan = options.wrapInSpan !== false;

  leaveAgo = options.leaveAgo;
  var distance = Math.round((new Date() - date) / 1000);

  if (!date) {
    return "—";
  }

  fullReadable = longDate(date);
  displayDate = "";
  fiveDaysAgo = 432000;
  oneMinuteAgo = 60;

  if (distance < oneMinuteAgo) {
    displayDate = I18n.t("now");
  } else if (distance > fiveDaysAgo) {
    if ((new Date()).getFullYear() !== date.getFullYear()) {
      displayDate = shortDate(date);
    } else {
      displayDate = shortDateNoYear(date);
    }
  } else {
    displayDate = relativeAgeMediumSpan(distance, leaveAgo);
  }
  if(wrapInSpan) {
    return "" + displayDate + "";
  } else {
    return displayDate;
  }
};

// mostly lifted from rails with a few amendments
relativeAge = function(date, options) {
  options = options || {};
  var format = options.format || "tiny";

  if(format === "tiny") {
    return relativeAgeTiny(date, options);
  } else if (format === "medium") {
    return relativeAgeMedium(date, options);
  } else if (format === 'medium-with-ago') {
    return relativeAgeMedium(date, _.extend(options, {format: 'medium', leaveAgo: true}));
  }

  return "UNKNOWN FORMAT";
};

var number = function(val) {
  val = parseInt(val, 10);
  if (isNaN(val)) val = 0;

  if (val > 999) {
    return (val / 1000).toFixed(1) + "K";
  }
  return val.toString();
};

Discourse.Formatter = {
  longDate: longDate,
  longDateNoYear: longDateNoYear,
  relativeAge: relativeAge,
  autoUpdatingRelativeAge: autoUpdatingRelativeAge,
  updateRelativeAge: updateRelativeAge,
  toTitleCase: toTitleCase,
  shortDate: shortDate,
  breakUp: breakUp,
  cappedMemoize: cappedMemoize,
  number: number
};
<commit_msg>Added 'M' to the number formatter<commit_after>/* global BreakString:true */

var updateRelativeAge, autoUpdatingRelativeAge, relativeAge, relativeAgeTiny,
    relativeAgeMedium, relativeAgeMediumSpan, longDate, longDateNoYear, toTitleCase,
    shortDate, shortDateNoYear, tinyDateYear, relativeAgeTinyShowsYear;

/*
* memoize.js
* by @philogb and @addyosmani
* with further optimizations by @mathias
* and @DmitryBaranovsk
* perf tests: http://bit.ly/q3zpG3
* Released under an MIT license.
*
* modified with cap by Sam
*/
var cappedMemoize = function ( fn, max ) {
    fn.maxMemoize = max;
    fn.memoizeLength = 0;

    return function () {
        var args = Array.prototype.slice.call(arguments),
            hash = "",
            i = args.length;
        var currentArg = null;
        while (i--) {
            currentArg = args[i];
            hash += (currentArg === new Object(currentArg)) ?
            JSON.stringify(currentArg) : currentArg;
            if(!fn.memoize) {
              fn.memoize = {};
            }
        }
        if (hash in fn.memoize) {
          return fn.memoize[hash];
        } else {
          fn.memoizeLength++;
          if(fn.memoizeLength > max) {
            fn.memoizeLength = 0;
            fn.memoize = {};
          }
          var result = fn.apply(this, args);
          fn.memoize[hash] = result;
          return result;
        }
    };
};

var breakUp = cappedMemoize(function(str, hint){
  return new BreakString(str).break(hint);
}, 100);

shortDate = function(date){
  return moment(date).format(I18n.t("dates.medium.date_year"));
};

shortDateNoYear = function(date) {
  return moment(date).format(I18n.t("dates.tiny.date_month"));
};

tinyDateYear = function(date) {
  return moment(date).format(I18n.t("dates.tiny.date_year"));
};

// http://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript
// TODO: locale support ?
toTitleCase = function toTitleCase(str) {
  return str.replace(/\w\S*/g, function(txt){
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });
};

longDate = function(dt) {
  if (!dt) return;
  return moment(dt).longDate();
};

// suppress year, if current year
longDateNoYear = function(dt) {
  if (!dt) return;

  if ((new Date()).getFullYear() !== dt.getFullYear()) {
    return moment(dt).format(I18n.t("dates.long_date_with_year"));
  } else {
    return moment(dt).format(I18n.t("dates.long_date_without_year"));
  }
};

updateRelativeAge = function(elems) {
  // jQuery .each
  elems.each(function(){
    var $this = $(this);
    $this.html(relativeAge(new Date($this.data('time')), {format: $this.data('format'), wrapInSpan: false}));
  });
};

autoUpdatingRelativeAge = function(date,options) {
  if (!date) return "";
  if (+date === +new Date(0)) return "";

  options = options || {};
  var format = options.format || "tiny";

  var append = "";

  if(format === 'medium') {
    append = " date";
    if(options.leaveAgo) {
      format = 'medium-with-ago';
    }
    options.wrapInSpan = false;
  }

  var relAge = relativeAge(date, options);

  if (format === 'tiny' && relativeAgeTinyShowsYear(relAge)) {
    append += " with-year";
  }

  if (options.title) {
    append += "' title='" + longDate(date);
  }

  return "" + relAge  + "";
};

relativeAgeTiny = function(date){
  var format = "tiny";
  var distance = Math.round((new Date() - date) / 1000);
  var distanceInMinutes = Math.round(distance / 60.0);

  var formatted;
  var t = function(key,opts){
    return I18n.t("dates." + format + "." + key, opts);
  };

  switch(true){

  case(distanceInMinutes < 1):
    formatted = t("less_than_x_minutes", {count: 1});
    break;
  case(distanceInMinutes >= 1 && distanceInMinutes <= 44):
    formatted = t("x_minutes", {count: distanceInMinutes});
    break;
  case(distanceInMinutes >= 45 && distanceInMinutes <= 89):
    formatted = t("about_x_hours", {count: 1});
    break;
  case(distanceInMinutes >= 90 && distanceInMinutes <= 1439):
    formatted = t("about_x_hours", {count: Math.round(distanceInMinutes / 60.0)});
    break;
  case(Discourse.SiteSettings.relative_date_duration === 0 && distanceInMinutes <= 525599):
    formatted = shortDateNoYear(date);
    break;
  case(distanceInMinutes >= 1440 && distanceInMinutes <= 2519):
    formatted = t("x_days", {count: 1});
    break;
  case(distanceInMinutes >= 2520 && distanceInMinutes <= ((Discourse.SiteSettings.relative_date_duration||14) * 1440)):
    formatted = t("x_days", {count: Math.round(distanceInMinutes / 1440.0)});
    break;
  default:
    if(date.getFullYear() === new Date().getFullYear()) {
      formatted = shortDateNoYear(date);
    } else {
      formatted = tinyDateYear(date);
    }
    break;
  }

  return formatted;
};

/*
 * Returns true if the given tiny date string includes the year.
 * Useful for checking if the string isn't so tiny.
 */
relativeAgeTinyShowsYear = function(relativeAgeString) {
  return relativeAgeString.match(/'[\d]{2}$/);
};

relativeAgeMediumSpan = function(distance, leaveAgo) {
  var formatted, distanceInMinutes;

  distanceInMinutes = Math.round(distance / 60.0);

  var t = function(key, opts){
    return I18n.t("dates.medium" + (leaveAgo?"_with_ago":"") + "." + key, opts);
  };

  switch(true){
  case(distanceInMinutes >= 1 && distanceInMinutes <= 56):
    formatted = t("x_minutes", {count: distanceInMinutes});
    break;
  case(distanceInMinutes >= 56 && distanceInMinutes <= 89):
    formatted = t("x_hours", {count: 1});
    break;
  case(distanceInMinutes >= 90 && distanceInMinutes <= 1379):
    formatted = t("x_hours", {count: Math.round(distanceInMinutes / 60.0)});
    break;
  case(distanceInMinutes >= 1380 && distanceInMinutes <= 2159):
    formatted = t("x_days", {count: 1});
    break;
  case(distanceInMinutes >= 2160):
    formatted = t("x_days", {count: Math.round((distanceInMinutes - 720.0) / 1440.0)});
    break;
  }
  return formatted || '&mdash';
};

relativeAgeMedium = function(date, options){
  var displayDate, fiveDaysAgo, oneMinuteAgo, fullReadable, leaveAgo;
  var wrapInSpan = options.wrapInSpan !== false;

  leaveAgo = options.leaveAgo;
  var distance = Math.round((new Date() - date) / 1000);

  if (!date) {
    return "—";
  }

  fullReadable = longDate(date);
  displayDate = "";
  fiveDaysAgo = 432000;
  oneMinuteAgo = 60;

  if (distance < oneMinuteAgo) {
    displayDate = I18n.t("now");
  } else if (distance > fiveDaysAgo) {
    if ((new Date()).getFullYear() !== date.getFullYear()) {
      displayDate = shortDate(date);
    } else {
      displayDate = shortDateNoYear(date);
    }
  } else {
    displayDate = relativeAgeMediumSpan(distance, leaveAgo);
  }
  if(wrapInSpan) {
    return "" + displayDate + "";
  } else {
    return displayDate;
  }
};

// mostly lifted from rails with a few amendments
relativeAge = function(date, options) {
  options = options || {};
  var format = options.format || "tiny";

  if(format === "tiny") {
    return relativeAgeTiny(date, options);
  } else if (format === "medium") {
    return relativeAgeMedium(date, options);
  } else if (format === 'medium-with-ago') {
    return relativeAgeMedium(date, _.extend(options, {format: 'medium', leaveAgo: true}));
  }

  return "UNKNOWN FORMAT";
};

var number = function(val) {
  val = parseInt(val, 10);
  if (isNaN(val)) val = 0;

  if (val > 999) {
    return (val / 1000).toFixed(1) + "K";
  }
  if (val > 999999) {
    return (val / 1000000).toFixed(1) + "M";
  }
  return val.toString();
};

Discourse.Formatter = {
  longDate: longDate,
  longDateNoYear: longDateNoYear,
  relativeAge: relativeAge,
  autoUpdatingRelativeAge: autoUpdatingRelativeAge,
  updateRelativeAge: updateRelativeAge,
  toTitleCase: toTitleCase,
  shortDate: shortDate,
  breakUp: breakUp,
  cappedMemoize: cappedMemoize,
  number: number
};
<|endoftext|>


<commit_before>var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var app     = express();

app.get('/scrape', function(req, res){

  //todo scrape

})

app.listen('8081')

exports = module.exports = app;
<commit_msg>Variable outline<commit_after>var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var app = express();

app.get('/scrape', function(req, res){

  url = 'http://www.imdb.com/list/ls052535080/?start=1&view=detail&sort=listorian:asc';

  request(url, function(error, response, html){

    if(!error) {

      var $= cheerio.load(html);
      var title, year, rating, rank, url;
      var json = { title : "", year : "", rating : "", rank : "", url : ""};

    }
  })

})

app.listen('8081')

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


<commit_before>var do_config = {};
var parse_config = {};
var target_config = {};

var seperator = (/^win/.test(process.platform)) ? "& " : "; ";
var dir_contents = (/^win/.test(process.platform)) ? "dir " : "ls -la ";

var file_opts = {
  encoding: "utf8"
};

var node_version = Number(process.version.match(/^v(\d+\.\d+)/)[1]);

switch (node_version) {
  case 0.8:
  case 0.9:
    var Iconv = require('iconv').Iconv;

    Buffer.prototype._$_toString = Buffer.prototype.toString;
    Buffer.prototype.toString = function(charset) {
      if (typeof charset == 'undefined' || charset == 'utf8' || charset == 'utf16le' || charset == 'ascii' || charset == 'ucs2' || charset == 'binary' || charset == 'base64' || charset == 'hex') {
        return this._$_toString.apply(this, arguments);
      }
      var iconv = new Iconv(charset.encoding, 'UTF-8');
      var buffer = iconv.convert(this);
      var args = arguments;
      args[0] = 'utf8';
      return buffer.toString.apply(buffer, args);
    }
    file_opts = 'utf8';
    break;

  default:

    break;
}

module.exports = {
  config: do_config,
  parse: parse_config,
  target: target_config,
  seperator: seperator,
  file_opts: file_opts,
  dir: dir_contents,
  channel: 'not-impressed'
}<commit_msg>give 0.9 an iconv break.<commit_after>var do_config = {};
var parse_config = {};
var target_config = {};

var seperator = (/^win/.test(process.platform)) ? "& " : "; ";
var dir_contents = (/^win/.test(process.platform)) ? "dir " : "ls -la ";

var file_opts = {
  encoding: "utf8"
};

var node_version = Number(process.version.match(/^v(\d+\.\d+)/)[1]);

switch (node_version) {
  case 0.8:
  // case 0.9:
    var Iconv = require('iconv').Iconv;

    Buffer.prototype._$_toString = Buffer.prototype.toString;
    Buffer.prototype.toString = function(charset) {
      if (typeof charset == 'undefined' || charset == 'utf8' || charset == 'utf16le' || charset == 'ascii' || charset == 'ucs2' || charset == 'binary' || charset == 'base64' || charset == 'hex') {
        return this._$_toString.apply(this, arguments);
      }
      var iconv = new Iconv(charset.encoding, 'UTF-8');
      var buffer = iconv.convert(this);
      var args = arguments;
      args[0] = 'utf8';
      return buffer.toString.apply(buffer, args);
    }
    file_opts = 'utf8';
    break;

  default:

    break;
}

module.exports = {
  config: do_config,
  parse: parse_config,
  target: target_config,
  seperator: seperator,
  file_opts: file_opts,
  dir: dir_contents,
  channel: 'not-impressed'
}<|endoftext|>


<commit_before>import { Router } from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import baseConfig from './webpack.config';
import loadConfig from './config';
import getIndexHtml from './index.html';
import getIframeHtml from './iframe.html';
import { getHeadHtml } from './utils';

export default function (configDir) {
  // Build the webpack configuration using the `baseConfig`
  // custom `.babelrc` file and `webpack.config.js` files
  const config = loadConfig('DEVELOPMENT', baseConfig, configDir);

  // remove the leading '/'
  let publicPath = config.output.publicPath;
  if (publicPath[0] === '/') {
    publicPath = publicPath.slice(1);
  }

  const compiler = webpack(config);
  const devMiddlewareOptions = {
    noInfo: true,
    publicPath: config.output.publicPath,
  };

  const router = new Router();
  router.use(webpackDevMiddleware(compiler, devMiddlewareOptions));
  router.use(webpackHotMiddleware(compiler));

  router.get('/', function (req, res) {
    res.send(getIndexHtml(publicPath));
  });

  const headHtml = getHeadHtml(configDir);
  router.get('/iframe.html', function (req, res) {
    res.send(getIframeHtml(headHtml, publicPath));
  });

  return router;
}
<commit_msg>Support watchOptions configuration. (#287)<commit_after>import { Router } from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import baseConfig from './webpack.config';
import loadConfig from './config';
import getIndexHtml from './index.html';
import getIframeHtml from './iframe.html';
import { getHeadHtml } from './utils';

export default function (configDir) {
  // Build the webpack configuration using the `baseConfig`
  // custom `.babelrc` file and `webpack.config.js` files
  const config = loadConfig('DEVELOPMENT', baseConfig, configDir);

  // remove the leading '/'
  let publicPath = config.output.publicPath;
  if (publicPath[0] === '/') {
    publicPath = publicPath.slice(1);
  }

  const compiler = webpack(config);
  const devMiddlewareOptions = {
    noInfo: true,
    publicPath: config.output.publicPath,
    watchOptions: config.watchOptions || {},
  };

  const router = new Router();
  router.use(webpackDevMiddleware(compiler, devMiddlewareOptions));
  router.use(webpackHotMiddleware(compiler));

  router.get('/', function (req, res) {
    res.send(getIndexHtml(publicPath));
  });

  const headHtml = getHeadHtml(configDir);
  router.get('/iframe.html', function (req, res) {
    res.send(getIframeHtml(headHtml, publicPath));
  });

  return router;
}
<|endoftext|>


<commit_before>var $input = $('
<input type="text" class="form-control" placeholder="Message">
');
$(document).on("click", ".js-msgGroup", function () {
    $(".js-msgGroup, .js-newMsg").addClass("hide"), $(".js-conversation").removeClass("hide"), $(".modal-title").html('Back'), $input.insertBefore(".js-modalBody")
}), $(function () {
    function o() {
        return $(window).width() - ($('[data-toggle="popover"]').offset().left + $('[data-toggle="popover"]').outerWidth())
    }

    $(window).on("resize", function () {
        var t = $('[data-toggle="popover"]').data("bs.popover");
        t && (t.options.viewport.padding = o())
    }), $('[data-toggle="popover"]').popover({
        template: '

',
        title: "",
        html: !0,
        trigger: "manual",
        placement: "bottom",
        viewport: {selector: "body", padding: o()},
        content: function () {
            var o = $(".app-navbar .navbar-nav:last-child").clone();
            return '
' + o.html() + "
"
        }
    }), $('[data-toggle="popover"]').on("click", function (o) {
        o.stopPropagation(), $('[data-toggle="popover"]').data("bs.popover").tip().hasClass("in") ? ($('[data-toggle="popover"]').popover("hide"), $(document).off("click.app.popover")) : ($('[data-toggle="popover"]').popover("show"), setTimeout(function () {
            $(document).one("click.app.popover", function () {
                $('[data-toggle="popover"]').popover("hide")
            })
        }, 1))
    })
}), $(document).on("click", ".js-gotoMsgs", function () {
    $input.remove(), $(".js-conversation").addClass("hide"), $(".js-msgGroup, .js-newMsg").removeClass("hide"), $(".modal-title").html("Messages")
}), $(document).on("click", "[data-action=growl]", function (o) {
    o.preventDefault(), $("#app-growl").append('
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
Click the x on the upper right to dismiss this little thing. Or click growl again to show more growls.

')
}), $(document).on("focus", '[data-action="grow"]', function () {
    $(window).width() > 1e3 && $(this).animate({width: 300})
}), $(document).on("blur", '[data-action="grow"]', function () {
    if ($(window).width() > 1e3) {
        $(this).animate({width: 180})
    }
}), $(function () {
    function o() {
        $(window).scrollTop() > $(window).height() ? $(".docs-top").fadeIn() : $(".docs-top").fadeOut()
    }

    $(".docs-top").length && (o(), $(window).on("scroll", o))
}), $(function () {
    function o() {
        i.width() > 768 ? e() : t()
    }

    function t() {
        i.off("resize.theme.nav"), i.off("scroll.theme.nav"), n.css({position: "", left: "", top: ""})
    }

    function e() {
        function o() {
            e.containerTop = $(".docs-content").offset().top - 40, e.containerRight = $(".docs-content").offset().left + $(".docs-content").width() + 45, t()
        }

        function t() {
            var o = i.scrollTop(), t = Math.max(o - e.containerTop, 0);
            return t ? void n.css({
                position: "fixed",
                left: e.containerRight,
                top: 40
            }) : ($(n.find("li")[1]).addClass("active"), n.css({position: "", left: "", top: ""}))
        }

        var e = {};
        o(), $(window).on("resize.theme.nav", o).on("scroll.theme.nav", t), $("body").scrollspy({
            target: "#markdown-toc",
            selector: "li > a"
        }), setTimeout(function () {
            $("body").scrollspy("refresh")
        }, 1e3)
    }

    var n = $("#markdown-toc"), i = $(window);
    n[0] && (o(), i.on("resize", o))
});

//script for handling image preview and ajax functionality
//for chops post

$('document').ready(function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    var files = [];
    $(function () {
        $("#file").change(function () {
            if (typeof(FileReader) !== "undefined") {
                var imagePreview = $("#imagePreview");
                imagePreview.html("");
                var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
                $($(this)[0].files).each(function () {
                    var file = $(this);
                    if (regex.test(file[0].name.toLowerCase())) {
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            var img = $("");
                            img.attr("style", "height:150px;width: 150px");
                            img.attr("src", e.target.result);
                            img.addClass("imagePreview");
                            imagePreview.append(img);
                            img.imageCrop({
                                overlayOpacity: 0.25,
                                displayPreview : true,
                                displaySize : true,

                                onSelect : updateForm
                            });
                        };
                        reader.readAsDataURL(file[0]);
                    } else {
                        alert(file[0].name + " is not a valid image file.");
                        imagePreview.html("");
                        return false;
                    }
                });
            }

            for (var i = 0; i < $(this).get(0).files.length; ++i) {
                files.push($(this).get(0).files[i].name);
            }
            $("input[name=file]").val(files);
        });
    });

    $(function () {
        $('[data-toggle="tooltip"]').tooltip()
    });

    $('.favourite').on('click', function(e){
        e.preventDefault();
        var chopId = $("input[name='chop_id']", this).val();

        $.ajax({
            type : 'post',
            url  : '/chops/favourite/'+chopId,
            data : {
                chopId: chopId
            },
            success: function(response){
                var span = $('#unpopular');
                if ( response.count > 0) {
                    $('#favourites-count-'+chopId).empty().append(response.count);

                    span.removeAttr('id');
                } else {
                    $('#favourites-count-'+chopId).empty().append('0');
                }

            },
            error: function(response){
               // console.log(response);
            }
        });

    });

});

// execute/clear BS loaders for docs
$(function(){
    if (window.BS&&window.BS.loader&&window.BS.loader.length) {
        while(BS.loader.length){(BS.loader.pop())()}
    }
});

$('#camera').click(function() {
    $( "#file" ).click();
});

// Toggle between follow and unfollow button on userModal
function toggleBetweenFollowAndUnfollow(element) {
    if($(element).text() == "Follow") {
        $(element).text('Unfollow').css("background-color", "#D9534F")
    } else if($(element).text() == "Unfollow") {
        $(element).text('Follow').css("background-color", "#3097D1")
    }
}

// Implement follow and Unfollow functionality
function followOrUnfollow(element) {
    $.ajax({
        type: 'get',
        url: '/follow',
        data: {'followee_id': $(element).prop('id')}
    }).done(function(response) {
        $('.followings-count-for-logged-in-user').empty();
        $('.followings-count-for-logged-in-user').append(response);
    });
}

// Retrieve followers or followees of a user
function getFollowersOrFollowees(routeUrl, element) {
    $.ajax({
        type: 'get',
        url: routeUrl,
        data: {'user_id': $(element).data().id}
    }).done(function(response) {
        $('#followingList').html(updateModal(response));
        var modalTag = $('#userModal');
        modalTag.find('.modal-title').text('Following');
        modalTag.modal('handleUpdate');
        modalTag.modal('show');
    });
}

// Update the userModal with ajax response for the collection of followers or followees
function updateModal(response) {
    var htmlResponse = '';
    var followStatuses = response['followStatuses'];
    var follows = response['follows'];
    var logged_in_user_id = response['logged_in_user_id'];
    var counter = 0;

    for(var follow in follows) {
        htmlResponse += '
' +
        '
' +
        '' +
        '' +
        '' +
        '
';

        if((typeof followStatuses !== 'undefined') && (followStatuses[counter] == "YES")) {
            if(follows[follow].id !== logged_in_user_id) {
                htmlResponse += '<button class="follow cg fm fx eg" style="background-color: #D9534F;color: #FFFFFF" id="' + follows[follow].id + '" onclick="toggleBetweenFollowAndUnfollow(this)">' +
                                'Unfollow' +
                                '</button>';
            }
        } else if((typeof followStatuses !== 'undefined') && (followStatuses[counter] == "NO")) {
            if(follows[follow].id !== logged_in_user_id) {
                htmlResponse += '<button class="follow cg fm fx eg" style="background-color: #3097D1;color: #FFFFFF" id="' + follows[follow].id + '" onclick="toggleBetweenFollowAndUnfollow(this)">' +
                                'Follow' +
                                '</button>';
            }
        } else {
            htmlResponse += '<button class="follow cg fm fx eg" style="background-color: #D9534F;color: #FFFFFF" id="' + follows[follow].id + '" onclick="toggleBetweenFollowAndUnfollow(this)">' +
                            'Unfollow' +
                            '</button>';
        }

        htmlResponse += '' + follows[follow].firstname + ' ' + follows[follow].lastname + '' + '
' + '@' + follows[follow].username.toLowerCase() + ' - ' + follows[follow].location + '

';

        counter++;
    }

    return htmlResponse;
}

// Retrieve all the users a particular user is following
$('#following').on('click', function() {
    getFollowersOrFollowees('/followees', this);
});

// Retrieve all the users following a particular user
$('#followers').on('click', function() {
    getFollowersOrFollowees('/followers', this);
});

// Handle follow and unfollow on userModal
$('#userModal').on('shown.bs.modal', function() {
    $('.follow').on('click',function() {
        followOrUnfollow(this);
    });
});

// Handle follow and unfollow on popover
$('.pop').on('shown.bs.popover', function() {
    $('.follow').on('click',function(e) {
        e.preventDefault();
        followOrUnfollow(this);
    });
});

// Handle the operation of follow/unfollow popover
$(document).ready(function() {
    $('.pop').popover({
        html: true,
        trigger: "hover",
        content: function () {
            return "";
        },
        placement: "auto left",
        delay: {"show": 300,"hide": 600},
        animation: "true",
        template: '

'
    }).on('show.bs.popover', function() {
        $.ajax({
            type: 'get',
            url: '/follow_status',
            data: {'followee_id': $(this).data().id},
            success: function(response){
                (response == "NO") ? $('div .popover').css("background-color", "#3097D1").css("color", "#FFFFFF") : $('div .popover').css("background-color", "#D9534F").css("color", "#FFFFFF");
                $('div .popover-content span').append((response == "NO") ? "Follow" : "Unfollow");
            }
        });
    });
});<commit_msg>Correct error in followers modal title<commit_after>var $input = $('
<input type="text" class="form-control" placeholder="Message">
');
$(document).on("click", ".js-msgGroup", function () {
    $(".js-msgGroup, .js-newMsg").addClass("hide"), $(".js-conversation").removeClass("hide"), $(".modal-title").html('Back'), $input.insertBefore(".js-modalBody")
}), $(function () {
    function o() {
        return $(window).width() - ($('[data-toggle="popover"]').offset().left + $('[data-toggle="popover"]').outerWidth())
    }

    $(window).on("resize", function () {
        var t = $('[data-toggle="popover"]').data("bs.popover");
        t && (t.options.viewport.padding = o())
    }), $('[data-toggle="popover"]').popover({
        template: '

',
        title: "",
        html: !0,
        trigger: "manual",
        placement: "bottom",
        viewport: {selector: "body", padding: o()},
        content: function () {
            var o = $(".app-navbar .navbar-nav:last-child").clone();
            return '
' + o.html() + "
"
        }
    }), $('[data-toggle="popover"]').on("click", function (o) {
        o.stopPropagation(), $('[data-toggle="popover"]').data("bs.popover").tip().hasClass("in") ? ($('[data-toggle="popover"]').popover("hide"), $(document).off("click.app.popover")) : ($('[data-toggle="popover"]').popover("show"), setTimeout(function () {
            $(document).one("click.app.popover", function () {
                $('[data-toggle="popover"]').popover("hide")
            })
        }, 1))
    })
}), $(document).on("click", ".js-gotoMsgs", function () {
    $input.remove(), $(".js-conversation").addClass("hide"), $(".js-msgGroup, .js-newMsg").removeClass("hide"), $(".modal-title").html("Messages")
}), $(document).on("click", "[data-action=growl]", function (o) {
    o.preventDefault(), $("#app-growl").append('
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
Click the x on the upper right to dismiss this little thing. Or click growl again to show more growls.

')
}), $(document).on("focus", '[data-action="grow"]', function () {
    $(window).width() > 1e3 && $(this).animate({width: 300})
}), $(document).on("blur", '[data-action="grow"]', function () {
    if ($(window).width() > 1e3) {
        $(this).animate({width: 180})
    }
}), $(function () {
    function o() {
        $(window).scrollTop() > $(window).height() ? $(".docs-top").fadeIn() : $(".docs-top").fadeOut()
    }

    $(".docs-top").length && (o(), $(window).on("scroll", o))
}), $(function () {
    function o() {
        i.width() > 768 ? e() : t()
    }

    function t() {
        i.off("resize.theme.nav"), i.off("scroll.theme.nav"), n.css({position: "", left: "", top: ""})
    }

    function e() {
        function o() {
            e.containerTop = $(".docs-content").offset().top - 40, e.containerRight = $(".docs-content").offset().left + $(".docs-content").width() + 45, t()
        }

        function t() {
            var o = i.scrollTop(), t = Math.max(o - e.containerTop, 0);
            return t ? void n.css({
                position: "fixed",
                left: e.containerRight,
                top: 40
            }) : ($(n.find("li")[1]).addClass("active"), n.css({position: "", left: "", top: ""}))
        }

        var e = {};
        o(), $(window).on("resize.theme.nav", o).on("scroll.theme.nav", t), $("body").scrollspy({
            target: "#markdown-toc",
            selector: "li > a"
        }), setTimeout(function () {
            $("body").scrollspy("refresh")
        }, 1e3)
    }

    var n = $("#markdown-toc"), i = $(window);
    n[0] && (o(), i.on("resize", o))
});

//script for handling image preview and ajax functionality
//for chops post

$('document').ready(function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    var files = [];
    $(function () {
        $("#file").change(function () {
            if (typeof(FileReader) !== "undefined") {
                var imagePreview = $("#imagePreview");
                imagePreview.html("");
                var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
                $($(this)[0].files).each(function () {
                    var file = $(this);
                    if (regex.test(file[0].name.toLowerCase())) {
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            var img = $("");
                            img.attr("style", "height:150px;width: 150px");
                            img.attr("src", e.target.result);
                            img.addClass("imagePreview");
                            imagePreview.append(img);
                            img.imageCrop({
                                overlayOpacity: 0.25,
                                displayPreview : true,
                                displaySize : true,

                                onSelect : updateForm
                            });
                        };
                        reader.readAsDataURL(file[0]);
                    } else {
                        alert(file[0].name + " is not a valid image file.");
                        imagePreview.html("");
                        return false;
                    }
                });
            }

            for (var i = 0; i < $(this).get(0).files.length; ++i) {
                files.push($(this).get(0).files[i].name);
            }
            $("input[name=file]").val(files);
        });
    });

    $(function () {
        $('[data-toggle="tooltip"]').tooltip()
    });

    $('.favourite').on('click', function(e){
        e.preventDefault();
        var chopId = $("input[name='chop_id']", this).val();

        $.ajax({
            type : 'post',
            url  : '/chops/favourite/'+chopId,
            data : {
                chopId: chopId
            },
            success: function(response){
                var span = $('#unpopular');
                if ( response.count > 0) {
                    $('#favourites-count-'+chopId).empty().append(response.count);

                    span.removeAttr('id');
                } else {
                    $('#favourites-count-'+chopId).empty().append('0');
                }

            },
            error: function(response){
               // console.log(response);
            }
        });

    });

});

// execute/clear BS loaders for docs
$(function(){
    if (window.BS&&window.BS.loader&&window.BS.loader.length) {
        while(BS.loader.length){(BS.loader.pop())()}
    }
});

$('#camera').click(function() {
    $( "#file" ).click();
});

// Toggle between follow and unfollow button on userModal
function toggleBetweenFollowAndUnfollow(element) {
    if($(element).text() == "Follow") {
        $(element).text('Unfollow').css("background-color", "#D9534F")
    } else if($(element).text() == "Unfollow") {
        $(element).text('Follow').css("background-color", "#3097D1")
    }
}

// Implement follow and Unfollow functionality
function followOrUnfollow(element) {
    $.ajax({
        type: 'get',
        url: '/follow',
        data: {'followee_id': $(element).prop('id')}
    }).done(function(response) {
        $('.followings-count-for-logged-in-user').empty();
        $('.followings-count-for-logged-in-user').append(response);
    });
}

// Retrieve followers or followees of a user
function getFollowersOrFollowees(routeUrl, element) {
    $.ajax({
        type: 'get',
        url: routeUrl,
        data: {'user_id': $(element).data().id}
    }).done(function(response) {
        $('#followingList').html(updateModal(response));
        var modalTag = $('#userModal');
        modalTag.find('.modal-title').text((routeUrl == "/followers") ? 'Followers' : 'Following');
        modalTag.modal('handleUpdate');
        modalTag.modal('show');
    });
}

// Update the userModal with ajax response for the collection of followers or followees
function updateModal(response) {
    var htmlResponse = '';
    var followStatuses = response['followStatuses'];
    var follows = response['follows'];
    var logged_in_user_id = response['logged_in_user_id'];
    var counter = 0;

    for(var follow in follows) {
        htmlResponse += '
' +
        '
' +
        '' +
        '' +
        '' +
        '
';

        if((typeof followStatuses !== 'undefined') && (followStatuses[counter] == "YES")) {
            if(follows[follow].id !== logged_in_user_id) {
                htmlResponse += '<button class="follow cg fm fx eg" style="background-color: #D9534F;color: #FFFFFF" id="' + follows[follow].id + '" onclick="toggleBetweenFollowAndUnfollow(this)">' +
                                'Unfollow' +
                                '</button>';
            }
        } else if((typeof followStatuses !== 'undefined') && (followStatuses[counter] == "NO")) {
            if(follows[follow].id !== logged_in_user_id) {
                htmlResponse += '<button class="follow cg fm fx eg" style="background-color: #3097D1;color: #FFFFFF" id="' + follows[follow].id + '" onclick="toggleBetweenFollowAndUnfollow(this)">' +
                                'Follow' +
                                '</button>';
            }
        } else {
            htmlResponse += '<button class="follow cg fm fx eg" style="background-color: #D9534F;color: #FFFFFF" id="' + follows[follow].id + '" onclick="toggleBetweenFollowAndUnfollow(this)">' +
                            'Unfollow' +
                            '</button>';
        }

        htmlResponse += '' + follows[follow].firstname + ' ' + follows[follow].lastname + '' + '
' + '@' + follows[follow].username.toLowerCase() + ' - ' + follows[follow].location + '

';

        counter++;
    }

    return htmlResponse;
}

// Retrieve all the users a particular user is following
$('#following').on('click', function() {
    getFollowersOrFollowees('/followees', this);
});

// Retrieve all the users following a particular user
$('#followers').on('click', function() {
    getFollowersOrFollowees('/followers', this);
});

// Handle follow and unfollow on userModal
$('#userModal').on('shown.bs.modal', function() {
    $('.follow').on('click',function() {
        followOrUnfollow(this);
    });
});

// Handle follow and unfollow on popover
$('.pop').on('shown.bs.popover', function() {
    $('.follow').on('click',function(e) {
        e.preventDefault();
        followOrUnfollow(this);
    });
});

// Handle the operation of follow/unfollow popover
$(document).ready(function() {
    $('.pop').popover({
        html: true,
        trigger: "hover",
        content: function () {
            return "";
        },
        placement: "auto left",
        delay: {"show": 300,"hide": 600},
        animation: "true",
        template: '

'
    }).on('show.bs.popover', function() {
        $.ajax({
            type: 'get',
            url: '/follow_status',
            data: {'followee_id': $(this).data().id},
            success: function(response){
                (response == "NO") ? $('div .popover').css("background-color", "#3097D1").css("color", "#FFFFFF") : $('div .popover').css("background-color", "#D9534F").css("color", "#FFFFFF");
                $('div .popover-content span').append((response == "NO") ? "Follow" : "Unfollow");
            }
        });
    });
});<|endoftext|>