<commit_before>/*
    update.js <https://github.com/davidfig/update>
    License: MIT license <https://github.com/davidfig/update/license>
    Author: David Figatner
    Copyright (c) 2016 YOPEY YOPEY LLC
*/

var list = [];
var FPS = 60;
var FPSActual;
var pause = false;
var pauseRegistrations = [];
var pauseElapsed = 0;

var startTime = 0;
var frameNumber = 0;
var lastUpdate = 0;
var lastFPS = '--';

var tolerance = 1;

var maxChange = 100;

var panels = {fps: null, meter: null, percent: null};
var percentageList = [];
var lastCount;

var DEBUG = false;

// this creates a rolling average using 500 entries to smooth the debug percentages
var rollingAverage = 500;

// initialize Update
// options: {}
//  debug {boolean} whether to turn on debug support (requires github.com/davidfig/debug)
function init(options)
{
    options = options || {};
    checkVisibility();
    FPSActual = 1000 / FPS;
    if (options.debug)
    {
        DEBUG = true;
        debugInit();
    }
}

// register functions to call after Update pauses or resumes
function registerPause(pause, resume)
{
    pauseRegistrations.push({ pause: pause, resume: resume});
}

function pauseGame()
{
    if (pause !== true)
    {
        pause = true;
        pauseElapsed = performance.now() - lastUpdate;
        updateOff = false;
        if (DEBUG)
        {
            debugPause();
        }
        for (var i = 0; i < pauseRegistrations.length; i++)
        {
            pauseRegistrations[i].pause();
        }
    }
}

function resumeGame()
{
    if (pause === true)
    {
        pause = false;
        lastUpdate = performance.now() - pauseElapsed;
        fpsReset();
        for (var i = 0; i < pauseRegistrations.length; i++)
        {
            pauseRegistrations[i].resume();
        }
        if (updateOff === true)
        {
            update();
        }
    }
}

function fpsReset()
{
    startTime = 0;
    frameNumber = 0;
    lastUpdate = 0;
    lastFPS = '--';
}

function updateOther(elapsed)
{
    var i = 0, _i = list.length;
    var total = 0, other = 0, updates = [], count = 0;
    while (i < _i)
    {
        var update = list[i++];
        if (update.pause)
        {
            continue;
        }
        if (update.duration !== 0)
        {
            update.elapsed += elapsed;
            if (update.elapsed < update.duration)
            {
                if (DEBUG && update.params.percent)
                {
                    var change = percentageList[update.params.percent];
                    change.amounts[change.current++] = 0;
                    if (change.current === rollingAverage)
                    {
                        change.current = 0;
                    }
                }
                continue;
            }
            else
            {
                update.elapsed = 0;
            }
        }
        var start, result;
        if (DEBUG && panels.percent)
        {
            start = performance.now();
            result = update.callback(elapsed, update.params);
            current = performance.now() - start;
            if (update.params.percent)
            {
                var change = percentageList[update.params.percent];
                change.amounts[change.current++] = current;
                if (change.current === rollingAverage)
                {
                    change.current = 0;
                }
            }
            else
            {
                other += current;
            }
            total += current;
        }
        else
        {
            result = update.callback(elapsed, update.params);
        }
        if (update.once || result)
        {
            i--;
            _i--;
            list.splice(i, 1);
        }
        count++;
    }
    if (DEBUG)
    {
        if (lastCount !== count)
        {
            debugOne(count + ' updates', {panel: panels.count});
            lastCount = count;
        }
        if (panels.percent)
        {
            debugPercent(other);
        }
    }
}

// Add a function to the update loop with a desired FPS
// params:
//   once: true or false -- call function only once
//   percent: track percentages in a davidfig/Debug panel
function addFPS(funct, fps, params)
{
    return add(funct, 1000 / fps, params);
}

// Add a function to the update loop ever time MS
// params:
//   once: true or false -- call function only once
//   percent: track percentages in a davidfig/Debug panel
function add(funct, time, params)
{
    time = time || 0;
    params = params || {};
    var update = {callback: funct, params: params, duration: time, elapsed: 0, once: params.once, pause: false};
    list.push(update);
    if (DEBUG && params.percent)
    {
        percentageList[params.percent] = {current: 0, amounts: []};
        var test = '';
        for (var key in percentageList)
        {
            test += key + ': --%
';
        }
        debugOne(test, {panel: panels.percent});
        Debug.resize();
    }
    return update;
}

// removes an update from the loop
// update is the object returned by Update.add() or Update.addFPS()
function remove(update)
{
    for (var i = 0, _i = list.length; i < _i; i++)
    {
        if (list[i] === update)
        {
            list.splice(i, 1);
            return;
        }
    }
}

// starts the update loop
function update()
{
    if (pause === true)
    {
        updateOff = true;
        return;
    }
    var current = performance.now();
    var elapsed;
    if (lastUpdate === 0)
    {
        elapsed = 0;
    }
    else
    {
        elapsed = current - lastUpdate;
        elapsed = elapsed > maxChange ? maxChange : elapsed;
    }
    if (FPS === 60 || elapsed === 0 || elapsed >= FPSActual)
    {
        if (list.length)
        {
            updateOther(elapsed);
        }
        lastUpdate = current;
        if (DEBUG)
        {
            debugUpdate(current);
        }
    }
    if (typeof requestAnimationFrame === 'function')
    {
        requestAnimationFrame(update);
    }
    else
    {
        setTimeout(update, FPSActual);
    }
}

//
// Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser.
// Also listens for window.onblur and window.onfocus.
// based on Phaser: https://github.com/photonstorm/phaser (MIT license)
function checkVisibility()
{
    var hiddenVar;
    if (document.webkitHidden !== undefined)
    {
        hiddenVar = 'webkitvisibilitychange';
    }
    else if (document.mozHidden !== undefined)
    {
        hiddenVar = 'mozvisibilitychange';
    }
    else if (document.msHidden !== undefined)
    {
        hiddenVar = 'msvisibilitychange';
    }
    else if (document.hidden !== undefined)
    {
        hiddenVar = 'visibilitychange';
    }
    else
    {
        hiddenVar = null;
    }

    //  Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus
    if (hiddenVar)
    {
        document.addEventListener(hiddenVar, visibilityChange, false);
    }

    window.onblur = visibilityChange;
    window.onfocus = visibilityChange;

    window.onpagehide = visibilityChange;
    window.onpageshow = visibilityChange;
}

// Callback for checkVisibility()
// based on Phaser: https://github.com/photonstorm/phaser (MIT license)
function visibilityChange(event)
{
    if (event.type === 'pagehide' || event.type === 'blur' || event.type === 'pageshow' || event.type === 'focus')
    {
        if (event.type === 'pagehide' || event.type === 'blur')
        {
            pauseGame();
        }
        else if (event.type === 'pageshow' || event.type === 'focus')
        {
            resumeGame(event);
        }
        return;
    }

    if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === "pause")
    {
        pauseGame(event);
    }
}

// add an FPS panel and meter
function debugInit()
{
    panels.fps = Debug.add('FPS', {text: '-- FPS'});
    panels.meter = Debug.addMeter('panel');
    panels.count = Debug.add('Updates', {text: '0 updates'});
    panels.percent = Debug.add('percentages', {style: {textAlign: 'right'}});
    percentageList['Other'] = {current: 0, amounts: []};
}

function debugPause()
{
    debugOne('-- FPS', {panel: panels.fps});
}

function debugUpdate(current)
{
    frameNumber++;
    var currentTime = performance.now() - startTime;

    // skip the first half second to get rid of garbage
    if (currentTime > 500)
    {
        if (startTime !== 0)
        {
            lastFPS = Math.floor(frameNumber / (currentTime / 1000));
            if (lastFPS >= 60 - tolerance && lastFPS <= 60 + tolerance)
            {
                lastFPS = 60;
            }
        }
        startTime = performance.now();
        frameNumber = 0;
    }
    debugOne(lastFPS + ' FPS', {panel: panels.fps});
    var time = performance.now() - current;

// TODO: 16.7 is hard coded for 60 FPS. Probably should figure out the real amount for the current FPS
    var expected = (16.7 - time) / 16.7;
    Debug.meter(expected, {panel: panels.meter});
}

function debugPercent(other)
{
    var change = percentageList['Other'];
    change.amounts[change.current++] = other;
    change.current %= rollingAverage;
    var updates = [], all = 0;
    for (var name in percentageList)
    {
        var change = percentageList[name];
        var total = 0;
        for (var i = 0; i < change.amounts.length; i++)
        {
            total += change.amounts[i];
        }
        total /= change.amounts.length;
        all += total;
        updates.push({name: name, total: total});
    }
    var result = '';
    for (var i = 1; i < updates.length; i++)
    {
        var update = updates[i];
        result += update.name + ': ' + Math.round(update.total / all * 100) + '%
';
    }
    var update = updates[0];
    result += update.name + ': ' + Math.round(update.total / all * 100) + '%
';
    debugOne(result, {panel: panels.percent});
}

// exports
var Update = {
    init: init,
    add: add,
    update: update,
    remove: remove,
    registerPause: registerPause,
    pauseGame: pauseGame,
    resumeGame: resumeGame,
    panels: panels
};

// add support for AMD (Asynchronous Module Definition) libraries such as require.js.
if (typeof define === 'function' && define.amd)
{
    define(function()
    {
        return {
            Update: Update
        };
    });
}

// add support for CommonJS libraries such as browserify.
if (typeof exports !== 'undefined')
{
    module.exports = Update;
}

// define globally in case AMD is not available or available but not used
if (typeof window !== 'undefined')
{
    window.Update = Update;
}<commit_msg>Adding more debug options in Debug.init<commit_after>/*
    update.js <https://github.com/davidfig/update>
    License: MIT license <https://github.com/davidfig/update/license>
    Author: David Figatner
    Copyright (c) 2016 YOPEY YOPEY LLC
*/

var list = [];
var FPS = 60;
var FPSActual;
var pause = false;
var pauseRegistrations = [];
var pauseElapsed = 0;

var startTime = 0;
var frameNumber = 0;
var lastUpdate = 0;
var lastFPS = '--';

var tolerance = 1;

var maxChange = 100;

var panels = {fps: null, meter: null, percent: null};
var percentageList = [];
var lastCount;

var DEBUG = false;
var COUNT = false;
var PERCENT = false;
var FPS = false;

// this is the number of entries to use in a rolling average to smooth the debug percentages
var rollingAverage = 500;

/**
 * must call Update.init before using Update
 * @param {boolean} debug - whether to turn on debug support (requires github.com/davidfig/debug)
 * @param {boolean=false|string} count - show debug counts (can supply side for panel, e.g., 'topleft')
 * @param {boolean=false|string} percent - show debug percentage
 * @param {boolean=false|string} FPS - show debug FPS
 */
function init(options)
{
    options = options || {};
    checkVisibility();
    FPSActual = 1000 / FPS;
    if (options.debug)
    {
        DEBUG = true;
        COUNT = options.count;
        PERCENT = options.percent;
        FPS = options.FPS;
        debugInit();
    }
}

// register functions to call after Update pauses or resumes
function registerPause(pause, resume)
{
    pauseRegistrations.push({ pause: pause, resume: resume});
}

function pauseGame()
{
    if (pause !== true)
    {
        pause = true;
        pauseElapsed = performance.now() - lastUpdate;
        updateOff = false;
        if (DEBUG)
        {
            debugPause();
        }
        for (var i = 0; i < pauseRegistrations.length; i++)
        {
            pauseRegistrations[i].pause();
        }
    }
}

function resumeGame()
{
    if (pause === true)
    {
        pause = false;
        lastUpdate = performance.now() - pauseElapsed;
        fpsReset();
        for (var i = 0; i < pauseRegistrations.length; i++)
        {
            pauseRegistrations[i].resume();
        }
        if (updateOff === true)
        {
            update();
        }
    }
}

function fpsReset()
{
    startTime = 0;
    frameNumber = 0;
    lastUpdate = 0;
    lastFPS = '--';
}

function updateOther(elapsed)
{
    var i = 0, _i = list.length;
    var total = 0, other = 0, updates = [], count = 0;
    while (i < _i)
    {
        var update = list[i++];
        if (update.pause)
        {
            continue;
        }
        if (update.duration !== 0)
        {
            update.elapsed += elapsed;
            if (update.elapsed < update.duration)
            {
                if (DEBUG && PERCENT && update.params.percent)
                {
                    var change = percentageList[update.params.percent];
                    change.amounts[change.current++] = 0;
                    if (change.current === rollingAverage)
                    {
                        change.current = 0;
                    }
                }
                continue;
            }
            else
            {
                update.elapsed = 0;
            }
        }
        var start, result;
        if (DEBUG && panels.percent)
        {
            start = performance.now();
            result = update.callback(elapsed, update.params);
            current = performance.now() - start;
            if (update.params.percent)
            {
                var change = percentageList[update.params.percent];
                change.amounts[change.current++] = current;
                if (change.current === rollingAverage)
                {
                    change.current = 0;
                }
            }
            else
            {
                other += current;
            }
            total += current;
        }
        else
        {
            result = update.callback(elapsed, update.params);
        }
        if (update.once || result)
        {
            i--;
            _i--;
            list.splice(i, 1);
        }
        count++;
    }
    if (DEBUG)
    {
        if (COUNT && lastCount !== count)
        {
            debugOne(count + ' updates', {panel: panels.count});
            lastCount = count;
        }
        if (PERCENT && panels.percent)
        {
            debugPercent(other);
        }
    }
}

// Add a function to the update loop with a desired FPS
// params:
//   once: true or false -- call function only once
//   percent: track percentages in a davidfig/Debug panel
function addFPS(funct, fps, params)
{
    return add(funct, 1000 / fps, params);
}

// Add a function to the update loop ever time MS
// params:
//   once: true or false -- call function only once
//   percent: track percentages in a davidfig/Debug panel
function add(funct, time, params)
{
    time = time || 0;
    params = params || {};
    var update = {callback: funct, params: params, duration: time, elapsed: 0, once: params.once, pause: false};
    list.push(update);
    if (DEBUG && PERCENT && params.percent)
    {
        percentageList[params.percent] = {current: 0, amounts: []};
        var test = '';
        for (var key in percentageList)
        {
            test += key + ': --%
';
        }
        debugOne(test, {panel: panels.percent});
        Debug.resize();
    }
    return update;
}

// removes an update from the loop
// update is the object returned by Update.add() or Update.addFPS()
function remove(update)
{
    for (var i = 0, _i = list.length; i < _i; i++)
    {
        if (list[i] === update)
        {
            list.splice(i, 1);
            return;
        }
    }
}

// starts the update loop
function update()
{
    if (pause === true)
    {
        updateOff = true;
        return;
    }
    var current = performance.now();
    var elapsed;
    if (lastUpdate === 0)
    {
        elapsed = 0;
    }
    else
    {
        elapsed = current - lastUpdate;
        elapsed = elapsed > maxChange ? maxChange : elapsed;
    }
    if (FPS === 60 || elapsed === 0 || elapsed >= FPSActual)
    {
        if (list.length)
        {
            updateOther(elapsed);
        }
        lastUpdate = current;
        if (DEBUG && FPS)
        {
            debugUpdate(current);
        }
    }
    if (typeof requestAnimationFrame === 'function')
    {
        requestAnimationFrame(update);
    }
    else
    {
        setTimeout(update, FPSActual);
    }
}

//
// Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser.
// Also listens for window.onblur and window.onfocus.
// based on Phaser: https://github.com/photonstorm/phaser (MIT license)
function checkVisibility()
{
    var hiddenVar;
    if (document.webkitHidden !== undefined)
    {
        hiddenVar = 'webkitvisibilitychange';
    }
    else if (document.mozHidden !== undefined)
    {
        hiddenVar = 'mozvisibilitychange';
    }
    else if (document.msHidden !== undefined)
    {
        hiddenVar = 'msvisibilitychange';
    }
    else if (document.hidden !== undefined)
    {
        hiddenVar = 'visibilitychange';
    }
    else
    {
        hiddenVar = null;
    }

    //  Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus
    if (hiddenVar)
    {
        document.addEventListener(hiddenVar, visibilityChange, false);
    }

    window.onblur = visibilityChange;
    window.onfocus = visibilityChange;

    window.onpagehide = visibilityChange;
    window.onpageshow = visibilityChange;
}

// Callback for checkVisibility()
// based on Phaser: https://github.com/photonstorm/phaser (MIT license)
function visibilityChange(event)
{
    if (event.type === 'pagehide' || event.type === 'blur' || event.type === 'pageshow' || event.type === 'focus')
    {
        if (event.type === 'pagehide' || event.type === 'blur')
        {
            pauseGame();
        }
        else if (event.type === 'pageshow' || event.type === 'focus')
        {
            resumeGame(event);
        }
        return;
    }

    if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === "pause")
    {
        pauseGame(event);
    }
}

// add an FPS panel and meter
function debugInit()
{
    panels.fps = Debug.add('FPS', {text: '-- FPS'});
    panels.meter = Debug.addMeter('panel');
    panels.count = Debug.add('Updates', {text: '0 updates'});
    panels.percent = Debug.add('percentages', {style: {textAlign: 'right'}});
    percentageList['Other'] = {current: 0, amounts: []};
}

function debugPause()
{
    debugOne('-- FPS', {panel: panels.fps});
}

function debugUpdate(current)
{
    frameNumber++;
    var currentTime = performance.now() - startTime;

    // skip the first half second to get rid of garbage
    if (currentTime > 500)
    {
        if (startTime !== 0)
        {
            lastFPS = Math.floor(frameNumber / (currentTime / 1000));
            if (lastFPS >= 60 - tolerance && lastFPS <= 60 + tolerance)
            {
                lastFPS = 60;
            }
        }
        startTime = performance.now();
        frameNumber = 0;
    }
    debugOne(lastFPS + ' FPS', {panel: panels.fps});
    var time = performance.now() - current;

// TODO: 16.7 is hard coded for 60 FPS. Probably should figure out the real amount for the current FPS
    var expected = (16.7 - time) / 16.7;
    Debug.meter(expected, {panel: panels.meter});
}

function debugPercent(other)
{
    var change = percentageList['Other'];
    change.amounts[change.current++] = other;
    change.current %= rollingAverage;
    var updates = [], all = 0;
    for (var name in percentageList)
    {
        var change = percentageList[name];
        var total = 0;
        for (var i = 0; i < change.amounts.length; i++)
        {
            total += change.amounts[i];
        }
        total /= change.amounts.length;
        all += total;
        updates.push({name: name, total: total});
    }
    var result = '';
    for (var i = 1; i < updates.length; i++)
    {
        var update = updates[i];
        result += update.name + ': ' + Math.round(update.total / all * 100) + '%
';
    }
    var update = updates[0];
    result += update.name + ': ' + Math.round(update.total / all * 100) + '%
';
    debugOne(result, {panel: panels.percent});
}

// exports
var Update = {
    init: init,
    add: add,
    update: update,
    remove: remove,
    registerPause: registerPause,
    pauseGame: pauseGame,
    resumeGame: resumeGame,
    panels: panels
};

// add support for AMD (Asynchronous Module Definition) libraries such as require.js.
if (typeof define === 'function' && define.amd)
{
    define(function()
    {
        return {
            Update: Update
        };
    });
}

// add support for CommonJS libraries such as browserify.
if (typeof exports !== 'undefined')
{
    module.exports = Update;
}

// define globally in case AMD is not available or available but not used
if (typeof window !== 'undefined')
{
    window.Update = Update;
}<|endoftext|>


<commit_before>module.exports = {
  browser: process.env.BROWSER || 'chromium',
  launch: {
    dumpio: true,
    headless: process.env.HEADLESS !== 'false',
  },
  server: {
    command: 'yarn dev:serve',
    port: 5000,
  },
};
<commit_msg>test: fix default browser value<commit_after>module.exports = () =>
  ({
    browser: process.env.BROWSER || 'chromium',
    launch: {
      dumpio: true,
      headless: process.env.HEADLESS !== 'false',
    },
    server: {
      command: 'yarn dev:serve',
      port: 5000,
    },
  }());
<|endoftext|>


<commit_before>/*
 * returns the root element, which is the highest element on the page we work with
 */
function getRootElement(entryInfo) {
  return $(document.getElementsByClassName(entryInfo.entryPoint)[0]).parents().eq(entryInfo.rootElementLevel)[0];
}

/*
 * returns an array of all events present on the page
 */
function getElements(root) {
  return root.getElementsByTagName('div');
}

function getNameOfLecture(object) {
    var name = object.childNodes[1].innerText;
    if (name.slice(name.length - 12) == " Beschreibung") {
      result = name.slice(0, (name.length - 12));
    } else {
      result = name;
    }
    return result;
}

function getSpeakerOfLecture(object) {
  return object.childNodes[3].innerText.slice(12).split(',').join('\\,');
}

function getDayOfWeek(object) {
  return object.childNodes[5].childNodes[3].childNodes[0].childNodes[3].innerText;
}

function getLocation(object) {
  return object.childNodes[5].childNodes[3].childNodes[0].childNodes[9].innerText.split(',').join('\\,');
}

function getTime(object) {
  return object.childNodes[5].childNodes[3].childNodes[0].childNodes[7].innerText;
}

function getDates(object) {
  return object.childNodes[5].childNodes[3].childNodes[0].childNodes[5].innerText;
}

function getTargetGroup(object) {
  return object.childNodes[5].childNodes[3].childNodes[0].childNodes[11].innerText;
}

function getLastUpdated(object) {
  return object.childNodes[5].childNodes[3].childNodes[0].childNodes[13].innerText.slice(13);
}

function getEventData(subject) {
  var data = {
    name: "",
    comment: "",
    location: "",
    begin: "",
    end: ""
  };

  data.name = getNameOfLecture(subject);
  data.comment = getSpeakerOfLecture(subject);
  data.location = getLocation(subject);

  var time = parseTime(getTime(subject), getDayOfWeek(subject));
  event.begin = time[0];
  event.end = time[1];

  return event;
}<commit_msg>fix getNameOfLecture to slice off whitespaces<commit_after>/*
 * returns the root element, which is the highest element on the page we work with
 */
function getRootElement(entryInfo) {
  return $(document.getElementsByClassName(entryInfo.entryPoint)[0]).parents().eq(entryInfo.rootElementLevel)[0];
}

/*
 * returns an array of all events present on the page
 */
function getElements(root) {
  return root.getElementsByTagName('div');
}

function getNameOfLecture(object) {
    var name = object.childNodes[1].innerText;
    if (name.slice(name.length - 12) == "Beschreibung") {
      result = name.slice(0, (name.length - 15));
    } else {
      result = name;
    }
    return result;
}

function getSpeakerOfLecture(object) {
  return object.childNodes[3].innerText.slice(12).split(',').join('\\,');
}

function getDayOfWeek(object) {
  return object.childNodes[5].childNodes[3].childNodes[0].childNodes[3].innerText;
}

function getLocation(object) {
  return object.childNodes[5].childNodes[3].childNodes[0].childNodes[9].innerText.split(',').join('\\,');
}

function getTime(object) {
  return object.childNodes[5].childNodes[3].childNodes[0].childNodes[7].innerText;
}

function getDates(object) {
  return object.childNodes[5].childNodes[3].childNodes[0].childNodes[5].innerText;
}

function getTargetGroup(object) {
  return object.childNodes[5].childNodes[3].childNodes[0].childNodes[11].innerText;
}

function getLastUpdated(object) {
  return object.childNodes[5].childNodes[3].childNodes[0].childNodes[13].innerText.slice(13);
}

function getEventData(subject) {
  var data = {
    name: "",
    comment: "",
    location: "",
    begin: "",
    end: ""
  };

  data.name = getNameOfLecture(subject);
  data.comment = getSpeakerOfLecture(subject);
  data.location = getLocation(subject);

  var time = parseTime(getTime(subject), getDayOfWeek(subject));
  event.begin = time[0];
  event.end = time[1];

  return event;
}<|endoftext|>


<commit_before>const express = require('express');
const pgp = require('pg-promise')();
const http = require('http');
const express_enforces_ssl = require('express-enforces-ssl');
const app = express();
const controller = require("./controller/controller.js");

app.use(express.static(__dirname));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

// Check for Prod to enforce SSL
if (process.env.NODE_ENV) {
	app.enable('trust proxy');
	app.use(express_enforces_ssl());
	console.log("SSL Enforced")
} else {
	console.log("SSL *not* Enforced")
}

controller.set(app);

http.createServer(app).listen(app.get('port'), function() {
	console.log('Express server listening on port ' + app.get('port'));
});

// app.listen(process.env.PORT || 3000);

// console.log("App running at http://localhost:" + (process.env.PORT ? process.env.PORT : 3000));<commit_msg>Fixed missing port declaration.<commit_after>const express = require('express');
const pgp = require('pg-promise')();
const http = require('http');
const express_enforces_ssl = require('express-enforces-ssl');
const app = express();
const controller = require("./controller/controller.js");

app.use(express.static(__dirname));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

// Check for Prod to enforce SSL
if (process.env.NODE_ENV) {
	app.enable('trust proxy');
	app.use(express_enforces_ssl());
	console.log("SSL Enforced")
} else {
	console.log("SSL *not* Enforced")
}

controller.set(app);

http.createServer(app).listen((process.env.PORT || 3000), function() {
	console.log('Express server listening on port ' + (process.env.PORT || 3000));
});

// app.listen(process.env.PORT || 3000);

// console.log("App running at http://localhost:" + (process.env.PORT ? process.env.PORT : 3000));<|endoftext|>


<commit_before>module.exports = {

  split: function(block, idx) {
    var original = {annotations: []},
        splitted = {annotations: []};

    original.content = block.content.substring(0, idx);
    splitted.content = block.content.substring(idx);

    block.annotations.forEach(function(a) {
      if (a.range[1] < idx)
        original.annotations.push(a)
      else if (a.range[0] >= idx)
        splitted.annotations.push({
          type: a.type,
          range: [a.range[0] - idx, a.range[1] - idx]
        });
      else {
        original.annotations.push({type: a.type, range: [a.range[0], idx]});
        splitted.annotations.push({type: a.type, range: [0, a.range[1] - idx]});
      }
    });

    return {original: original, splitted: splitted};
  },

  merge: function(a, b, insertSpace) {
    var needSuffix = insertSpace && a.content.length > 0,
        offset = needSuffix ? a.content.length + 1 : a.content.length,
        merged = {
          content: a.content + (needSuffix ? ' ' : '') + b.content,
          annotations: a.annotations ? a.annotations.slice(0) : []
        };

    if (b.annotations) {
      b.annotations.forEach(function(a) {
        merged.annotations.push({
          type: a.type,
          range: [a.range[0] + offset, a.range[1] + offset]
        });
      });
    }

    return merged;
  }
};
<commit_msg>improved block splitting<commit_after>module.exports = {

  split: function(block, idx) {
    var original = {annotations: []},
        splitted = {annotations: []};

    original.content = block.content.substring(0, idx);
    splitted.content = block.content.substring(idx);

    if (block.annotations) {
      block.annotations.forEach(function(a) {
        if (a.range[1] < idx) {
          original.annotations.push(a)
        } else if (a.range[0] >= idx) {
          splitted.annotations.push({
            type: a.type,
            range: [a.range[0] - idx, a.range[1] - idx]
          });
        } else {
          original.annotations.push({
            type: a.type,
            range: [a.range[0], idx]
          });
          if (a.range[1] - idx > 0)
            splitted.annotations.push({
              type: a.type,
              range: [0, a.range[1] - idx]
            });
        }
      });
    }

    return {original: original, splitted: splitted};
  },

  merge: function(a, b, insertSpace) {
    var needSuffix = insertSpace && a.content.length > 0,
        offset = needSuffix ? a.content.length + 1 : a.content.length,
        merged = {
          content: a.content + (needSuffix ? ' ' : '') + b.content,
          annotations: a.annotations ? a.annotations.slice(0) : []
        };

    if (b.annotations) {
      b.annotations.forEach(function(a) {
        merged.annotations.push({
          type: a.type,
          range: [a.range[0] + offset, a.range[1] + offset]
        });
      });
    }

    return merged;
  }
};
<|endoftext|>


<commit_before>function getLUT (pixelRepresentation, lutDataSet) {
  let numLUTEntries = lutDataSet.uint16('x00283002', 0);

  if (numLUTEntries === 0) {
    numLUTEntries = 65535;
  }
  let firstValueMapped = 0;

  if (pixelRepresentation === 0) {
    firstValueMapped = lutDataSet.uint16('x00283002', 1);
  } else {
    firstValueMapped = lutDataSet.int16('x00283002', 1);
  }
  const numBitsPerEntry = lutDataSet.uint16('x00283002', 2);
  // console.log('LUT(', numLUTEntries, ',', firstValueMapped, ',', numBitsPerEntry, ')');
  const lut = {
    id: '1',
    firstValueMapped,
    numBitsPerEntry,
    lut: []
  };

  // console.log("minValue=", minValue, "; maxValue=", maxValue);
  for (let i = 0; i < numLUTEntries; i++) {
    if (pixelRepresentation === 0) {
      lut.lut[i] = lutDataSet.uint16('x00283006', i);
    } else {
      lut.lut[i] = lutDataSet.int16('x00283006', i);
    }
  }

  return lut;
}

function getLUTs (pixelRepresentation, lutSequence) {
  if (!lutSequence || !lutSequence.items.length) {
    return;
  }
  const luts = [];

  for (let i = 0; i < lutSequence.items.length; i++) {
    const lutDataSet = lutSequence.items[i].dataSet;
    const lut = getLUT(pixelRepresentation, lutDataSet);

    if (lut) {
      luts.push(lut);
    }
  }

  return luts;
}

export default getLUTs;
<commit_msg>Fix for #269: Cannot read property 'length' of undefined at getLUTs.js<commit_after>function getLUT (pixelRepresentation, lutDataSet) {
  let numLUTEntries = lutDataSet.uint16('x00283002', 0);

  if (numLUTEntries === 0) {
    numLUTEntries = 65535;
  }
  let firstValueMapped = 0;

  if (pixelRepresentation === 0) {
    firstValueMapped = lutDataSet.uint16('x00283002', 1);
  } else {
    firstValueMapped = lutDataSet.int16('x00283002', 1);
  }
  const numBitsPerEntry = lutDataSet.uint16('x00283002', 2);
  // console.log('LUT(', numLUTEntries, ',', firstValueMapped, ',', numBitsPerEntry, ')');
  const lut = {
    id: '1',
    firstValueMapped,
    numBitsPerEntry,
    lut: []
  };

  // console.log("minValue=", minValue, "; maxValue=", maxValue);
  for (let i = 0; i < numLUTEntries; i++) {
    if (pixelRepresentation === 0) {
      lut.lut[i] = lutDataSet.uint16('x00283006', i);
    } else {
      lut.lut[i] = lutDataSet.int16('x00283006', i);
    }
  }

  return lut;
}

function getLUTs (pixelRepresentation, lutSequence) {
  if (!lutSequence || !lutSequence.items || !lutSequence.items.length) {
    return;
  }
  const luts = [];

  for (let i = 0; i < lutSequence.items.length; i++) {
    const lutDataSet = lutSequence.items[i].dataSet;
    const lut = getLUT(pixelRepresentation, lutDataSet);

    if (lut) {
      luts.push(lut);
    }
  }

  return luts;
}

export default getLUTs;
<|endoftext|>


<commit_before>var mocha = require('mocha')
var should = require('chai').should()

var extend = require('./')

// Types: number, string, array, object, date, function, boolean, 0, null, undefined
describe('types:', function () {

    // Boilerplate
    /*
    it('', function () {
        var a = {
            foo: ''
        }
        var b = {
            foo: ''
        }
        extend(a, b).should.eql({
            foo: ''
        })
    })
    */

    // Debug
    /*
    console.log('')
    console.log('a:', booleanObj)
    console.log('b:', numberObj)
    console.log('=:', extend(booleanObj, numberObj))
    */

    var numberObj,
        numberObj2,
        stringObj,
        stringObj2,
        arrayObj,
        arrayObj2,
        objectObj,
        objectObj2,
        dateObj,
        dateObj2,
        functionObj,
        functionObj2,
        booleanObj,
        booleanObj2,
        zeroObj,
        zeroObj2,
        nullObj,
        nullObj2,
        undefinedObj,
        undefinedObj2

    beforeEach(function () {

        numberObj = {
            foo: 1
        }
        numberObj2 = {
            foo: 2
        }

        stringObj = {
            foo: 'bar'
        }
        stringObj2 = {
            foo: 'baz'
        }

        arrayObj = {
            foo: [1, 'b', 3]
        }
        arrayObj2 = {
            foo: [5, 'f', 7]
        }

        objectObj = {
            foo: {
                bar: 'baz'
            }
        }
        objectObj2 = {
            foo: {
                bar: 'bam'
            }
        }

        dateObj = {
            foo: new Date(2013, 4, 4)
        }
        dateObj2 = {
            foo: new Date(2013, 4, 5)
        }

        functionObj = {
            foo: function () { return true }
        }
        functionObj2 = {
            foo: function () { return false }
        }

        booleanObj = {
            foo: true
        }
        booleanObj2 = {
            foo: false
        }

        zeroObj = {
            foo: 0
        }
        zeroObj2 = {
            foo: 0
        }

        nullObj = {
            foo: null
        }
        nullObj2 = {
            foo: null
        }

        undefinedObj = {
            foo: undefined
        }
        undefinedObj2 = {
            foo: undefined
        }

    })

    // Number with number
    it('should extend number with number', function () {
        extend(numberObj, numberObj2).should.eql(numberObj2)
    })

    // Number with string
    it('should extend number with string', function () {
        extend(numberObj, stringObj).should.eql(stringObj)
    })

    // Number with array
    it('should extend number with array', function () {
        extend(numberObj, arrayObj).should.eql(arrayObj)
    })

    // Number with object
    it('should extend number with object', function () {
        extend(numberObj, objectObj).should.eql(objectObj)
    })

    // Number with date
    it('should extend number with date', function () {
        extend(numberObj, dateObj).should.eql(dateObj)
    })

    // Number with function
    it('should extend number with function', function () {
        extend(numberObj, functionObj).should.eql(functionObj)
    })

    // Number with boolean
    it('should extend number with boolean', function () {
        extend(numberObj, booleanObj).should.eql(booleanObj)
    })

    // Number with 0
    it('should extend number with 0', function () {
        extend(numberObj, zeroObj).should.eql(zeroObj)
    })

    // Number with null
    it('should extend number with null', function () {
        extend(numberObj, nullObj).should.eql(nullObj)
    })

    // Number with undefined
    it('should extend number with undefined', function () {
        extend(numberObj, undefinedObj).should.eql(undefinedObj)
    })

    // String with number
    it('should extend string with number', function () {
        extend(stringObj, numberObj).should.eql(numberObj)
    })

    // String with string
    it('should extend string with string', function () {
        extend(stringObj, stringObj2).should.eql(stringObj2)
    })

    // String with array
    it('should extend string with array', function () {
        extend(stringObj, arrayObj).should.eql(arrayObj)
    })

    // String with object
    it('should extend string with object', function () {
        extend(stringObj, objectObj).should.eql(objectObj)
    })

    // String with date
    it('should extend string with date', function () {
        extend(stringObj, dateObj).should.eql(dateObj)
    })

    // String with function
    it('should extend string with function', function () {
        extend(stringObj, functionObj).should.eql(functionObj)
    })

    // String with boolean
    it('should extend string with boolean', function () {
        extend(stringObj, booleanObj).should.eql(booleanObj)
    })

    // String with 0
    it('should extend string with 0', function () {
        extend(stringObj, zeroObj).should.eql(zeroObj)
    })

    // String with null
    it('should extend string with null', function () {
        extend(stringObj, nullObj).should.eql(nullObj)
    })

    // String with undefined
    it('should extend string with undefined', function () {
        extend(stringObj, undefinedObj).should.eql(undefinedObj)
    })

    // Array with number
    it('should extend array with number', function () {
        extend(arrayObj, numberObj).should.eql(numberObj)
    })

    // Array with string
    it('should extend array with string', function () {
        extend(arrayObj, stringObj).should.eql(stringObj)
    })

    // Array with array
    it('should extend array with array', function () {
        extend(arrayObj, arrayObj2).should.eql(arrayObj2)
    })

    // Array with object
    it('should extend array with object', function () {
        extend(arrayObj, objectObj).should.eql(objectObj)
    })

    // Array with date
    it('should extend array with date', function () {
        extend(arrayObj, dateObj).should.eql(dateObj)
    })

    // Array with function
    it('should extend array with function', function () {
        extend(arrayObj, functionObj).should.eql(functionObj)
    })

    // Array with boolean
    it('should extend array with boolean', function () {
        extend(arrayObj, booleanObj).should.eql(booleanObj)
    })

    // Array with 0
    it('should extend array with 0', function () {
        extend(arrayObj, zeroObj).should.eql(zeroObj)
    })

    // Array with null
    it('should extend array with null', function () {
        extend(arrayObj, nullObj).should.eql(nullObj)
    })

    // Array with undefined
    it('should extend array with undefined', function () {
        extend(arrayObj, undefinedObj).should.eql(undefinedObj)
    })

    // Object with number
    it('should extend object with number', function () {
        extend(objectObj, numberObj).should.eql(numberObj)
    })

    // Object with string
    it('should extend object with string', function () {
        extend(objectObj, stringObj).should.eql(stringObj)
    })

    // Object with array
    it('should extend object with array', function () {
        extend(objectObj, arrayObj).should.eql(arrayObj)
    })

    // Object with object
    it('should extend object with object', function () {
        extend(objectObj, objectObj2).should.eql(objectObj2)
    })

    // Object with date
    it('should extend object with date', function () {
        extend(objectObj, dateObj).should.eql(dateObj)
    })

    // Object with function
    it('should extend object with function', function () {
        extend(objectObj, functionObj).should.eql(functionObj)
    })

    // Object with boolean
    it('should extend object with boolean', function () {
        extend(objectObj, booleanObj).should.eql(booleanObj)
    })

    // Object with 0
    it('should extend object with 0', function () {
        extend(objectObj, zeroObj).should.eql(zeroObj)
    })

    // Object with null
    it('should extend object with null', function () {
        extend(objectObj, nullObj).should.eql(nullObj)
    })

    // Object with undefined
    it('should extend object with undefined', function () {
        extend(objectObj, undefinedObj).should.eql(undefinedObj)
    })

    // Function with number
    it('should extend function with number', function () {
        extend(functionObj, numberObj).should.eql(numberObj)
    })

    // Function with string
    it('should extend function with string', function () {
        extend(functionObj, stringObj).should.eql(stringObj)
    })

    // Function with array
    it('should extend function with array', function () {
        extend(functionObj, arrayObj).should.eql(arrayObj)
    })

    // Function with object
    it('should extend function with object', function () {
        extend(functionObj, objectObj).should.eql(objectObj)
    })

    // Function with date
    it('should extend function with date', function () {
        extend(functionObj, dateObj).should.eql(dateObj)
    })

    // Function with function
    it('should extend function with function', function () {
        extend(functionObj, functionObj2).should.eql(functionObj2)
    })

    // Function with boolean
    it('should extend function with boolean', function () {
        extend(functionObj, booleanObj).should.eql(booleanObj)
    })

    // Function with 0
    it('should extend function with 0', function () {
        extend(functionObj, zeroObj).should.eql(zeroObj)
    })

    // Function with null
    it('should extend function with null', function () {
        extend(functionObj, nullObj).should.eql(nullObj)
    })

    // Function with undefined
    it('should extend function with undefined', function () {
        extend(functionObj, undefinedObj).should.eql(undefinedObj)
    })

    // Boolean with number
    it('should extend boolean with number', function () {
        extend(booleanObj, numberObj).should.eql(numberObj)
    })

    // Boolean with string
    it('should extend boolean with string', function () {
        extend(booleanObj, stringObj).should.eql(stringObj)
    })

    // Boolean with array
    it('should extend boolean with array', function () {
        extend(booleanObj, arrayObj).should.eql(arrayObj)
    })

    // Boolean with object
    it('should extend boolean with object', function () {
        extend(booleanObj, objectObj).should.eql(objectObj)
    })

    // Boolean with date
    it('should extend boolean with date', function () {
        extend(booleanObj, dateObj).should.eql(dateObj)
    })

    // Boolean with function
    it('should extend boolean with function', function () {
        extend(booleanObj, functionObj).should.eql(functionObj)
    })

    // Boolean with boolean
    it('should extend boolean with boolean', function () {
        extend(booleanObj, booleanObj2).should.eql(booleanObj2)
    })

    // Boolean with 0
    it('should extend boolean with 0', function () {
        extend(booleanObj, zeroObj).should.eql(zeroObj)
    })

    // Boolean with null
    it('should extend boolean with null', function () {
        extend(booleanObj, nullObj).should.eql(nullObj)
    })

    // Boolean with undefined
    it('should extend boolean with undefined', function () {
        extend(booleanObj, undefinedObj).should.eql(undefinedObj)
    })

    // 0 with number
    it('should extend 0 with number', function () {
        extend(zeroObj, numberObj).should.eql(numberObj)
    })

    // 0 with string
    it('should extend 0 with string', function () {
        extend(zeroObj, stringObj).should.eql(stringObj)
    })

    // 0 with array
    it('should extend 0 with array', function () {
        extend(zeroObj, arrayObj).should.eql(arrayObj)
    })

    // 0 with object
    it('should extend 0 with object', function () {
        extend(zeroObj, objectObj).should.eql(objectObj)
    })

    // 0 with date
    it('should extend 0 with date', function () {
        extend(zeroObj, dateObj).should.eql(dateObj)
    })

    // 0 with function
    it('should extend 0 with function', function () {
        extend(zeroObj, functionObj).should.eql(functionObj)
    })

    // 0 with boolean
    it('should extend 0 with boolean', function () {
        extend(zeroObj, booleanObj).should.eql(booleanObj)
    })

    // 0 with 0
    it('should extend 0 with 0', function () {
        extend(zeroObj, zeroObj2).should.eql(zeroObj2)
    })

    // 0 with null
    it('should extend 0 with null', function () {
        extend(zeroObj, nullObj).should.eql(nullObj)
    })

    // 0 with undefined
    it('should extend 0 with undefined', function () {
        extend(zeroObj, undefinedObj).should.eql(undefinedObj)
    })

    // null with number
    it('should extend null with number', function () {
        extend(nullObj, numberObj).should.eql(numberObj)
    })

    // null with string
    it('should extend null with string', function () {
        extend(nullObj, stringObj).should.eql(stringObj)
    })

    // null with array
    it('should extend null with array', function () {
        extend(nullObj, arrayObj).should.eql(arrayObj)
    })

    // null with object
    it('should extend null with object', function () {
        extend(nullObj, objectObj).should.eql(objectObj)
    })

    // null with date
    it('should extend null with date', function () {
        extend(nullObj, dateObj).should.eql(dateObj)
    })

    // null with function
    it('should extend null with function', function () {
        extend(nullObj, functionObj).should.eql(functionObj)
    })

    // null with boolean
    it('should extend null with boolean', function () {
        extend(nullObj, booleanObj).should.eql(booleanObj)
    })

    // null with 0
    it('should extend null with 0', function () {
        extend(nullObj, zeroObj).should.eql(zeroObj)
    })

    // null with null
    it('should extend null with null', function () {
        extend(nullObj, nullObj2).should.eql(nullObj2)
    })

    // null with undefined
    it('should extend null with undefined', function () {
        extend(nullObj, undefinedObj).should.eql(undefinedObj)
    })

    // undefined with number
    it('should extend undefined with number', function () {
        extend(undefinedObj, numberObj).should.eql(numberObj)
    })

    // undefined with string
    it('should extend undefined with string', function () {
        extend(undefinedObj, stringObj).should.eql(stringObj)
    })

    // undefined with array
    it('should extend undefined with array', function () {
        extend(undefinedObj, arrayObj).should.eql(arrayObj)
    })

    // undefined with object
    it('should extend undefined with object', function () {
        extend(undefinedObj, objectObj).should.eql(objectObj)
    })

    // undefined with date
    it('should extend undefined with date', function () {
        extend(undefinedObj, dateObj).should.eql(dateObj)
    })

    // undefined with function
    it('should extend undefined with function', function () {
        extend(undefinedObj, functionObj).should.eql(functionObj)
    })

    // undefined with boolean
    it('should extend undefined with boolean', function () {
        extend(undefinedObj, booleanObj).should.eql(booleanObj)
    })

    // undefined with 0
    it('should extend undefined with 0', function () {
        extend(undefinedObj, zeroObj).should.eql(zeroObj)
    })

    // undefined with null
    it('should extend undefined with null', function () {
        extend(undefinedObj, nullObj).should.eql(nullObj)
    })

    // undefined with undefined
    it('should extend undefined with undefined', function () {
        extend(undefinedObj, undefinedObj2).should.eql(undefinedObj2)
    })

})

describe('complex:', function () {

    // Arrays
    it('should extend arrays', function () {
        var a = {
            foo: ['a, b, c'],
            bar: 'bla',
            baz: function () {}
        }
        var b = {
            foo: 'new',
            bar: [1, 2, 3],
            baz: ['alpha', 'beta']
        }
        extend(a, b).should.eql({
            foo: 'new',
            bar: [1, 2, 3],
            baz: ['alpha', 'beta']
        })
    })

    // Functions
    it('should extend functions', function () {
        // We use two dummy functions to reference in our objects. Otherwise our objects will
        // never be equal since the functions (although looking the same) will never point to
        // the same memory.
        var dummyA = function () {
            return false
        }
        var dummyB = function () {
            return true
        }
        var a = {
            baz: dummyA()
        }
        var b = {
            baz: dummyB()
        }

        extend(a, b).should.eql({
            baz: dummyB()
        })
    })

})

describe('deep', function () {

    var dummyFunction = function () {
        return true
    }

    var a = {
        app: 'My App',
        connections: {
            default: 'mysql',
            mysql: {
                driver: 'mysql',
                host: 'localhost',
                database: 'myapp.dev'
            }
        },
        init: {
            setup: null
        }
    }

    var b = {
        environment: 'production',
        connections: {
            default: 'mongodb',
            mysql: {
                database: 'myapp.prod'
            },
            mongodb: {
                host: 'http://mongo.example.org',
                database: 'myapp'
            }
        },
        init: {
            setup: dummyFunction()
        }
    }

    var expected = {
        app: 'My App',
        environment: 'production',
        connections: {
            default: 'mongodb',
            mysql: {
                driver: 'mysql',
                host: 'localhost',
                database: 'myapp.prod'
            },
            mongodb: {
                host: 'http://mongo.example.org',
                database: 'myapp'
            }
        },
        init: {
            setup: dummyFunction()
        }
    }

    it('should not deep extend objects', function () {
        extend(a, b).should.not.eql(expected)
    })

})

describe('grand finale', function () {

    var dummyFunction = function () {
        return true
    }

    var a = {
        myVersion: 1,
        myDate: new Date(2013, 4, 10),
        myArray: ['foo', 'bar'],
        deep: {
            myArray: ['a', 2, 'b', { sub: 'test' }],
            object: {
                foo: 'test',
                bar: {
                    subsub: 'go',
                    subsubArr: ['a', 'b', 'c']
                }
            }
        },
        myFunction: function () {
            return true
        }
    }

    var b = {
        myFoo: 'b',
        myVersion: '1',
        deep: {
            object: {
                bar: {
                    subsubArr: ['d']
                }
            },
            strg: 'String here...',
            subsub: {
                val: 'go'
            }
        },
        myFunction: dummyFunction
    }

    var expected = {
        myFoo: 'b',
        myVersion: '1',
        myDate: new Date(2013, 4, 10),
        myArray: ['foo', 'bar'],
        deep: {
            myArray: ['a', 2, 'b', { sub: 'test' }],
            object: {
                foo: 'test',
                bar: {
                    subsub: 'go',
                    subsubArr: ['d']
                }
            },
            strg: 'String here...',
            subsub: {
                val: 'go'
            }
        },
        myFunction: dummyFunction

    }

    // Grand finale.
    it('should not pass the grand finale', function () {
        extend(a, b).should.not.eql(expected)
    })

})<commit_msg>update test.js<commit_after>var test = require('ttr')

var extend = require('./')

function defs () {
  return {
    num1: {foo: 1},
    num2: {foo: 2},
    str1: {foo: 'bar'},
    str2: {foo: 'baz'},
    arr1: {foo: [1, 'b', 3]},
    arr2: {foo: [5, 'f', 7]},
    obj1: {foo: {bar: 'baz'}},
    obj2: {foo: {bar: 'bam'}},
    dat1: {foo: new Date(2015, 10, 27)},
    dat2: {foo: new Date(2015, 10, 31)},
    fnc1: {foo: function () {return true}},
    fnc2: {foo: function () {return false}},
    boo1: {foo: true},
    boo2: {foo: false},
    zer1: {foo: 0},
    zer2: {foo: 0},
    nul1: {foo: null},
    nul2: {foo: null},
    udf1: {foo: undefined},
    udf2: {foo: undefined}
  }
}

// Extending Number
test('extend number with number', function (t) {
  var o = defs()
  t.same(extend(o.num1, o.num2), o.num2)
})

test('extend number with string', function (t) {
  var o = defs()
  t.same(extend(o.num1, o.str1), o.str1)
})

test('extend number with array', function (t) {
  var o = defs()
  t.same(extend(o.num1, o.arr1), o.arr1)
})

test('extend number with object', function (t) {
  var o = defs()
  t.same(extend(o.num1, o.obj1), o.obj1)
})

test('extend number with date', function (t) {
  var o = defs()
  t.same(extend(o.num1, o.dat1), o.dat1)
})

test('extend number with function', function (t) {
  var o = defs()
  t.same(extend(o.num1, o.fnc1), o.fnc1)
})

test('extend number with boolean', function (t) {
  var o = defs()
  t.same(extend(o.num1, o.boo1), o.boo1)
})

test('extend number with 0', function (t) {
  var o = defs()
  t.same(extend(o.num1, o.zer1), o.zer1)
})

test('extend number with null', function (t) {
  var o = defs()
  t.same(extend(o.num1, o.nul1), o.nul1)
})

test('extend number with undefined', function (t) {
  var o = defs()
  t.same(extend(o.num1, o.udf1), o.udf1)
})

// Extending String
test('extend string with number', function (t) {
  var o = defs()
  t.same(extend(o.str1, o.num1), o.num1)
})

test('extend string with string', function (t) {
  var o = defs()
  t.same(extend(o.str1, o.str1), o.str1)
})

test('extend string with array', function (t) {
  var o = defs()
  t.same(extend(o.str1, o.arr1), o.arr1)
})

test('extend string with object', function (t) {
  var o = defs()
  t.same(extend(o.str1, o.obj1), o.obj1)
})

test('extend string with date', function (t) {
  var o = defs()
  t.same(extend(o.str1, o.dat1), o.dat1)
})

test('extend string with function', function (t) {
  var o = defs()
  t.same(extend(o.str1, o.fnc1), o.fnc1)
})

test('extend string with boolean', function (t) {
  var o = defs()
  t.same(extend(o.str1, o.boo1), o.boo1)
})

test('extend string with 0', function (t) {
  var o = defs()
  t.same(extend(o.str1, o.zer1), o.zer1)
})

test('extend string with null', function (t) {
  var o = defs()
  t.same(extend(o.str1, o.nul1), o.nul1)
})

test('extend string with undefined', function (t) {
  var o = defs()
  t.same(extend(o.str1, o.udf1), o.udf1)
})

test.result()
<|endoftext|>


<commit_before>var Backbone = require('backbone');
var _ = require('underscore');
var OrganizationModel = require('./organization-model');
var UserGroups = require('./user-groups-collection');
var CustomBaselayersCollection = require('./custom-baselayers-collection');

/**
 *  User model
 *
 */

var UserModel = Backbone.Model.extend({
  urlRoot: function () {
    var baseUrl = this._configModel.get('base_url');
    return baseUrl + '/api/v1/users';
  },

  defaults: {
    avatar_url: 'http://cartodb.s3.amazonaws.com/static/public_dashboard_default_avatar.png',
    username: '',
    email: ''
  },

  initialize: function (attrs, opts) {
    if (!opts.configModel) throw new Error('configModel is required');
    this._configModel = opts.configModel;
    attrs = attrs || {};

    if (!_.isEmpty(this.get('organization'))) {
      this._organizationModel = new OrganizationModel(
        this.get('organization'),
        {
          configModel: this._configModel,
          currentUserId: this.id
        }
      );
    }

    if (this.get('layers')) {
      this.layers = new CustomBaselayersCollection(this.get('layers'), {
        configModel: this._configModel,
        currentUserId: this.id
      });
    }

    this.groups = new UserGroups(attrs.groups, {
      organization: this._organizationModel
    });
  },

  isBuilder: function () {
    return this.get('viewer') === false;
  },

  canCreateDatasets: function () {
    if (!this.get('remaining_byte_quota') || this.get('remaining_byte_quota') <= 0) {
      return false;
    }
    return true;
  },

  canCreateTwitterDataset: function () {
    return !((this.get('twitter').quota - this.get('twitter').monthly_use) <= 0 && this.get('twitter').hard_limit);
  },

  canStartTrial: function () {
    return !this.isInsideOrg() && this.get('account_type') === 'FREE' && this.get('table_count') > 0;
  },

  isActionEnabled: function (action) {
    return this.get('actions') && this.get('actions')[action];
  },

  canCreatePrivateDatasets: function () {
    var actions = this.get('actions');
    return actions && actions.private_tables;
  },

  isInsideOrg: function () {
    if (this._organizationModel) {
      return !!this._organizationModel.id || this.isOrgAdmin();
    }
    return false;
  },

  isOrgAdmin: function () {
    if (this._organizationModel) {
      return this._organizationModel.getOwnerId() === this.get('id');
    }
    return false;
  },

  featureEnabled: function (name) {
    var featureFlags = this.get('feature_flags');
    if (!featureFlags || featureFlags.length === 0 || !name) {
      return false;
    }
    return _.contains(featureFlags, name);
  },

  upgradeContactEmail: function () {
    if (this.isInsideOrg()) {
      if (this.isOrgAdmin()) {
        return 'enterprise-support@carto.com';
      } else {
        return this._organizationModel.getOwnerEmail();
      }
    } else {
      return 'support@carto.com';
    }
  },

  nameOrUsername: function () {
    return this.get('name') || this.get('username');
  },

  getMaxConcurrentImports: function () {
    return (this.get('limits') && this.get('limits').concurrent_imports) || 1;
  },

  getSchemaName: function () {
    return this.isInsideOrg() ? this.get('username') : 'public';
  },

  getOrganizationModel: function () {
    if (this.isInsideOrg()) {
      return this._organizationModel;
    }
    return false;
  },

  renderData: function (currentUser) {
    var name = this.get('username');
    if (currentUser && currentUser.id === this.id) {
      name = _t('user.you');
    }
    return {
      username: name,
      avatar_url: this.get('avatar_url')
    };
  },

  clone: function () {
    var attrs = _.clone(this.attributes);
    delete attrs.id;
    return new UserModel(attrs, {
      configModel: this._configModel
    });
  },

  getOrganization: function () {
    return this._organizationModel;
  }
});

module.exports = UserModel;
<commit_msg>Don't use another getOrganization methodlib/assets/javascripts/cartodb3/data/user-model.js<commit_after>var Backbone = require('backbone');
var _ = require('underscore');
var OrganizationModel = require('./organization-model');
var UserGroups = require('./user-groups-collection');
var CustomBaselayersCollection = require('./custom-baselayers-collection');

/**
 *  User model
 *
 */

var UserModel = Backbone.Model.extend({
  urlRoot: function () {
    var baseUrl = this._configModel.get('base_url');
    return baseUrl + '/api/v1/users';
  },

  defaults: {
    avatar_url: 'http://cartodb.s3.amazonaws.com/static/public_dashboard_default_avatar.png',
    username: '',
    email: ''
  },

  initialize: function (attrs, opts) {
    if (!opts.configModel) throw new Error('configModel is required');
    this._configModel = opts.configModel;
    attrs = attrs || {};

    if (!_.isEmpty(this.get('organization'))) {
      this._organizationModel = new OrganizationModel(
        this.get('organization'),
        {
          configModel: this._configModel,
          currentUserId: this.id
        }
      );
    }

    if (this.get('layers')) {
      this.layers = new CustomBaselayersCollection(this.get('layers'), {
        configModel: this._configModel,
        currentUserId: this.id
      });
    }

    this.groups = new UserGroups(attrs.groups, {
      organization: this._organizationModel
    });
  },

  isBuilder: function () {
    return this.get('viewer') === false;
  },

  canCreateDatasets: function () {
    if (!this.get('remaining_byte_quota') || this.get('remaining_byte_quota') <= 0) {
      return false;
    }
    return true;
  },

  canCreateTwitterDataset: function () {
    return !((this.get('twitter').quota - this.get('twitter').monthly_use) <= 0 && this.get('twitter').hard_limit);
  },

  canStartTrial: function () {
    return !this.isInsideOrg() && this.get('account_type') === 'FREE' && this.get('table_count') > 0;
  },

  isActionEnabled: function (action) {
    return this.get('actions') && this.get('actions')[action];
  },

  canCreatePrivateDatasets: function () {
    var actions = this.get('actions');
    return actions && actions.private_tables;
  },

  isInsideOrg: function () {
    if (this._organizationModel) {
      return !!this._organizationModel.id || this.isOrgAdmin();
    }
    return false;
  },

  isOrgAdmin: function () {
    if (this._organizationModel) {
      return this._organizationModel.getOwnerId() === this.get('id');
    }
    return false;
  },

  featureEnabled: function (name) {
    var featureFlags = this.get('feature_flags');
    if (!featureFlags || featureFlags.length === 0 || !name) {
      return false;
    }
    return _.contains(featureFlags, name);
  },

  upgradeContactEmail: function () {
    if (this.isInsideOrg()) {
      if (this.isOrgAdmin()) {
        return 'enterprise-support@carto.com';
      } else {
        return this._organizationModel.getOwnerEmail();
      }
    } else {
      return 'support@carto.com';
    }
  },

  nameOrUsername: function () {
    return this.get('name') || this.get('username');
  },

  getMaxConcurrentImports: function () {
    return (this.get('limits') && this.get('limits').concurrent_imports) || 1;
  },

  getSchemaName: function () {
    return this.isInsideOrg() ? this.get('username') : 'public';
  },

  renderData: function (currentUser) {
    var name = this.get('username');
    if (currentUser && currentUser.id === this.id) {
      name = _t('user.you');
    }
    return {
      username: name,
      avatar_url: this.get('avatar_url')
    };
  },

  clone: function () {
    var attrs = _.clone(this.attributes);
    delete attrs.id;
    return new UserModel(attrs, {
      configModel: this._configModel
    });
  },

  getOrganization: function () {
    return this._organizationModel;
  }
});

module.exports = UserModel;
<|endoftext|>


<commit_before>var Class = require('../../utils/Class');
var BaseSoundManager = require('../BaseSoundManager');
var WebAudioSound = require('./WebAudioSound');
var SoundValueEvent = require('../SoundValueEvent');
//  Phaser.Loader.WebAudioSoundManager
var WebAudioSoundManager = new Class({
    Extends: BaseSoundManager,
    initialize: function WebAudioSoundManager(game) {
        /**
         * Flag indicating if Web Audio implementation is webkit or standards based.
         * There are certain cases where they have to be handled differently.
         *
         * https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext
         *
         * @private
         * @property {boolean} webkit
         */
        this.webkit = !!window['webkitAudioContext'] && !window['AudioContext'];
        /**
         * The AudioContext being used for playback.
         *
         * @private
         * @property {AudioContext} context
         */
        this.context = this.createAudioContext(game);
        /**
         * [description]
         *
         * @private
         * @property {GainNode} masterMuteNode
         */
        this.masterMuteNode = (this.context.createGain || this.context.createGainNode).call(this.context);
        /**
         * [description]
         *
         * @private
         * @property {GainNode} masterVolumeNode
         */
        this.masterVolumeNode = (this.context.createGain || this.context.createGainNode).call(this.context);
        this.masterMuteNode.connect(this.masterVolumeNode);
        this.masterVolumeNode.connect(this.context.destination);
        /**
         * Destination node for connecting individual sounds to.
         *
         * @private
         * @property {AudioNode} destination
         */
        this.destination = this.masterMuteNode;
        this.unlock();
        BaseSoundManager.call(this, game);
    },
    /**
     * @private
     * @param game
     * @returns {AudioContext}
     */
    createAudioContext: function (game) {
        var audioConfig = game.config.audio;
        if (audioConfig && audioConfig.context) {
            return audioConfig.context;
        }
        return new (window['AudioContext'] || window['webkitAudioContext'])();
    },
    add: function (key, config) {
        var sound = new WebAudioSound(this, key, config);
        this.sounds.push(sound);
        return sound;
    },
    /**
     * @private
     */
    unlock: function () {
        var _this = this;
        if (this.context.state === 'suspended' && 'ontouchstart' in window) {
            var unlock_1 = function () {
                _this.context.resume().then(function () {
                    document.body.removeEventListener('touchstart', unlock_1);
                    document.body.removeEventListener('touchend', unlock_1);
                });
            };
            document.body.addEventListener('touchstart', unlock_1, false);
            document.body.addEventListener('touchend', unlock_1, false);
        }
    },
    onBlur: function () {
        this.context.suspend();
    },
    onFocus: function () {
        this.context.resume();
    }
});
/**
 * Global mute setting.
 * @property {boolean} mute
 */
Object.defineProperty(WebAudioSoundManager.prototype, 'mute', {
    get: function () {
        return this.masterMuteNode.gain.value === 0;
    },
    set: function (value) {
        this.masterMuteNode.gain.setValueAtTime(value ? 0 : 1, 0);
        this.events.dispatch(new SoundValueEvent(this, 'SOUND_MUTE', value));
    }
});
/**
 * Global volume setting.
 * @property {number} volume
 */
Object.defineProperty(WebAudioSoundManager.prototype, 'volume', {
    get: function () {
        return this.masterVolumeNode.gain.value;
    },
    set: function (value) {
        this.masterVolumeNode.gain.setValueAtTime(value, 0);
        this.events.dispatch(new SoundValueEvent(this, 'SOUND_VOLUME', value));
    }
});
module.exports = WebAudioSoundManager;
<commit_msg>Reverting compatibility changes as they are handled by a polyfill<commit_after>var Class = require('../../utils/Class');
var BaseSoundManager = require('../BaseSoundManager');
var WebAudioSound = require('./WebAudioSound');
var SoundValueEvent = require('../SoundValueEvent');
//  Phaser.Loader.WebAudioSoundManager
var WebAudioSoundManager = new Class({
    Extends: BaseSoundManager,
    initialize: function WebAudioSoundManager(game) {
        /**
         * Flag indicating if Web Audio implementation is webkit or standards based.
         * There are certain cases where they have to be handled differently.
         *
         * https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext
         *
         * @private
         * @property {boolean} webkit
         */
        this.webkit = !!window['webkitAudioContext'] && !window['AudioContext'];
        /**
         * The AudioContext being used for playback.
         *
         * @private
         * @property {AudioContext} context
         */
        this.context = this.createAudioContext(game);
        /**
         * [description]
         *
         * @private
         * @property {GainNode} masterMuteNode
         */
        this.masterMuteNode = this.context.createGain();
        /**
         * [description]
         *
         * @private
         * @property {GainNode} masterVolumeNode
         */
        this.masterVolumeNode = this.context.createGain();
        this.masterMuteNode.connect(this.masterVolumeNode);
        this.masterVolumeNode.connect(this.context.destination);
        /**
         * Destination node for connecting individual sounds to.
         *
         * @private
         * @property {AudioNode} destination
         */
        this.destination = this.masterMuteNode;
        this.unlock();
        BaseSoundManager.call(this, game);
    },
    /**
     * @private
     * @param game
     * @returns {AudioContext}
     */
    createAudioContext: function (game) {
        var audioConfig = game.config.audio;
        if (audioConfig && audioConfig.context) {
            return audioConfig.context;
        }
        return new (window['AudioContext'] || window['webkitAudioContext'])();
    },
    add: function (key, config) {
        var sound = new WebAudioSound(this, key, config);
        this.sounds.push(sound);
        return sound;
    },
    /**
     * @private
     */
    unlock: function () {
        var _this = this;
        if (this.context.state === 'suspended' && 'ontouchstart' in window) {
            var unlock_1 = function () {
                _this.context.resume().then(function () {
                    document.body.removeEventListener('touchstart', unlock_1);
                    document.body.removeEventListener('touchend', unlock_1);
                });
            };
            document.body.addEventListener('touchstart', unlock_1, false);
            document.body.addEventListener('touchend', unlock_1, false);
        }
    },
    onBlur: function () {
        this.context.suspend();
    },
    onFocus: function () {
        this.context.resume();
    }
});
/**
 * Global mute setting.
 * @property {boolean} mute
 */
Object.defineProperty(WebAudioSoundManager.prototype, 'mute', {
    get: function () {
        return this.masterMuteNode.gain.value === 0;
    },
    set: function (value) {
        this.masterMuteNode.gain.setValueAtTime(value ? 0 : 1, 0);
        this.events.dispatch(new SoundValueEvent(this, 'SOUND_MUTE', value));
    }
});
/**
 * Global volume setting.
 * @property {number} volume
 */
Object.defineProperty(WebAudioSoundManager.prototype, 'volume', {
    get: function () {
        return this.masterVolumeNode.gain.value;
    },
    set: function (value) {
        this.masterVolumeNode.gain.setValueAtTime(value, 0);
        this.events.dispatch(new SoundValueEvent(this, 'SOUND_VOLUME', value));
    }
});
module.exports = WebAudioSoundManager;
<|endoftext|>


<commit_before>/**
 * Created by deepaksisodiya on 29/09/15.
 */

var should = require('should');
var request = require('supertest');
var mongoose = require('mongoose');

describe('testing API', function () {

    before(function (done) {
        mongoose.connect('mongodb://localhost:27017/Mocha');
        done();
    });

    var _id;

    it('user should be saved into the database', function (done) {
        var user = {
            "name" : "piyush",
            "mobile" : "7879544770"
        };
        request('http://localhost:3001')
            .post('/users')
            .send(user)
            .end(function (err, res) {
                _id = res.body._id;
                res.body.name.should.equal('piyush');
                res.body.mobile.should.equal('7879544770');
                done();
            });
    });

    it('user should be update into the database', function (done) {
        var user = {
            "name" : "deepak"
        };
        request('http://localhost:3001')
            .put('/users/' + _id)
            .send(user)
            .end(function(err, res) {
                res.body.name.should.equal('deepak');
                done();
            });
    });

});<commit_msg>delete user API testing<commit_after>/**
 * Created by deepaksisodiya on 29/09/15.
 */

var should = require('should');
var request = require('supertest');
var mongoose = require('mongoose');

describe('testing API', function () {

    before(function (done) {
        mongoose.connect('mongodb://localhost:27017/Mocha');
        done();
    });

    var _id;

    it('user should be save into the database', function (done) {
        var user = {
            "name" : "piyush",
            "mobile" : "7879544770"
        };
        request('http://localhost:3001')
            .post('/users')
            .send(user)
            .end(function (err, res) {
                _id = res.body._id;
                res.body.name.should.equal('piyush');
                res.body.mobile.should.equal('7879544770');
                done();
            });
    });

    it('user should be update into the database', function (done) {
        var user = {
            "name" : "deepak"
        };
        request('http://localhost:3001')
            .put('/users/' + _id)
            .send(user)
            .end(function(err, res) {
                res.body.name.should.equal('deepak');
                done();
            });
    });

    it('user should be delete from the database', function (done) {
        request('http://localhost:3001')
            .delete('/users/' + _id)
            .send()
            .end(function(err, res) {
                res.body.status.should.equal('user deleted successfully');
                done();
            });
    });

});<|endoftext|>


<commit_before>/**
 Jasmine Reporter that outputs test results to the browser console.
 Useful for running in a headless environment such as PhantomJs, ZombieJs etc.

 Usage:
 // From your html file that loads jasmine:
 jasmine.getEnv().addReporter(new jasmine.ConsoleReporter());
 jasmine.getEnv().execute();
*/

(function(jasmine, console) {
  if (!jasmine) {
    throw "jasmine library isn't loaded!";
  }

  var ANSI = {}
  ANSI.color_map = {
      "green" : 32,
      "red"   : 31
  }

  ANSI.colorize_text = function(text, color) {
    var color_code = this.color_map[color];
    return "\033[" + color_code + "m" + text + "\033[0m";
  }

  var ConsoleReporter = function() {
    if (!console || !console.log) { throw "console isn't present!"; }
    this.status = this.statuses.stopped;
  };

  var proto = ConsoleReporter.prototype;
  proto.statuses = {
    stopped : "stopped",
    running : "running",
    fail    : "fail",
    success : "success"
  };

  proto.reportRunnerStarting = function(runner) {
    this.status = this.statuses.running;
    this.start_time = (new Date()).getTime();
    this.executed_specs = 0;
    this.passed_specs = 0;
    this.log("Starting...");
  };

  proto.reportRunnerResults = function(runner) {
    var failed = this.executed_specs - this.passed_specs;
    var spec_str = this.executed_specs + (this.executed_specs === 1 ? " spec, " : " specs, ");
    var fail_str = failed + (failed === 1 ? " failure in " : " failures in ");
    var color = (failed > 0)? "red" : "green";
    var dur = (new Date()).getTime() - this.start_time;

    this.log("");
    this.log("Finished");
    this.log("-----------------");
    this.log(spec_str + fail_str + (dur/1000) + "s.", color);

    this.status = (failed > 0)? this.statuses.fail : this.statuses.success;

    /* Print something that signals that testing is over so that headless browsers
       like PhantomJs know when to terminate. */
    this.log("");
    this.log("ConsoleReporter finished");
  };

  proto.reportSpecStarting = function(spec) {
    this.executed_specs++;
  };

  proto.reportSpecResults = function(spec) {
    if (spec.results().skipped) {
      return;
    }
    if (spec.results().passed()) {
      this.passed_specs++;
      return;
    }

    var resultText = spec.suite.description + " : " + spec.description;
    this.log(resultText, "red");

    var items = spec.results().getItems()
    for (var i = 0; i < items.length; i++) {
      var trace = items[i].trace.stack || items[i].trace;
      this.log(trace, "red");
    }
  };

  proto.reportSuiteResults = function(suite) {
    if (!suite.parentSuite) { return; }
    var results = suite.results();
    if (results.totalCount === 0) {
      return;
    }
    var failed = results.totalCount - results.passedCount;
    var color = (failed > 0)? "red" : "green";
    this.log(suite.description + ": " + results.passedCount + " of " + results.totalCount + " passed.", color);
  };

  proto.log = function(str, color) {
    var text = (color != undefined)? ANSI.colorize_text(str, color) : str;
    console.log(text)
  };

  jasmine.ConsoleReporter = ConsoleReporter;
})(jasmine, console);

<commit_msg>tweak output from console reporter to be more helpful identifying errors<commit_after>/**
 Jasmine Reporter that outputs test results to the browser console.
 Useful for running in a headless environment such as PhantomJs, ZombieJs etc.

 Usage:
 // From your html file that loads jasmine:
 jasmine.getEnv().addReporter(new jasmine.ConsoleReporter());
 jasmine.getEnv().execute();
*/

(function(jasmine, console) {
  if (!jasmine) {
    throw "jasmine library isn't loaded!";
  }

  var ANSI = {}
  ANSI.color_map = {
      "green" : 32,
      "red"   : 31
  }

  ANSI.colorize_text = function(text, color) {
    var color_code = this.color_map[color];
    return "\033[" + color_code + "m" + text + "\033[0m";
  }

  var ConsoleReporter = function() {
    if (!console || !console.log) { throw "console isn't present!"; }
    this.status = this.statuses.stopped;
  };

  var proto = ConsoleReporter.prototype;
  proto.statuses = {
    stopped : "stopped",
    running : "running",
    fail    : "fail",
    success : "success"
  };

  proto.reportRunnerStarting = function(runner) {
    this.status = this.statuses.running;
    this.start_time = (new Date()).getTime();
    this.executed_specs = 0;
    this.passed_specs = 0;
    this.log("Starting...");
  };

  proto.reportRunnerResults = function(runner) {
    var failed = this.executed_specs - this.passed_specs;
    var spec_str = this.executed_specs + (this.executed_specs === 1 ? " spec, " : " specs, ");
    var fail_str = failed + (failed === 1 ? " failure in " : " failures in ");
    var color = (failed > 0)? "red" : "green";
    var dur = (new Date()).getTime() - this.start_time;

    this.log("");
    this.log("Finished");
    this.log("-----------------");
    this.log(spec_str + fail_str + (dur/1000) + "s.", color);

    this.status = (failed > 0)? this.statuses.fail : this.statuses.success;

    /* Print something that signals that testing is over so that headless browsers
       like PhantomJs know when to terminate. */
    this.log("");
    this.log("ConsoleReporter finished");
  };

  proto.reportSpecStarting = function(spec) {
    this.executed_specs++;
  };

  proto.reportSpecResults = function(spec) {
    if (spec.results().skipped) {
      return;
    }
    if (spec.results().passed()) {
      this.passed_specs++;
      return;
    }

    var resultText = spec.suite.description + " : " + spec.description;
    this.log(resultText, "red");

    var items = spec.results().getItems()
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      var output = '  ' + item.message;
      this.log(output, "red");
    }
  };

  proto.reportSuiteResults = function(suite) {
    if (!suite.parentSuite) { return; }
    var results = suite.results();
    if (results.totalCount === 0) {
      return;
    }
    var failed = results.totalCount - results.passedCount;
    var color = (failed > 0)? "red" : "green";
    this.log(suite.description + ": " + results.passedCount + " of " + results.totalCount + " passed.", color);
  };

  proto.log = function(str, color) {
    var text = (color != undefined)? ANSI.colorize_text(str, color) : str;
    console.log(text)
  };

  jasmine.ConsoleReporter = ConsoleReporter;
})(jasmine, console);
<|endoftext|>


<commit_before>var assert = require( "assert" );
var zlib = require( "zlib" );
var s = require( "./index" );
var type;

it( "guesses json", function () {

    type = s.guess( new Buffer( JSON.stringify({ "hello": "world" }) ) )
    assert.equal( type, "json" );

    type = s.guess( "   " + JSON.stringify({ "hello": "world" }) + "  " )
    assert.equal( type, "json" );

    type = s.guess( JSON.stringify([ 1, 2, 3 ]) )
    assert.equal( type, "json" );

    type = s.guess( "     " + JSON.stringify([ 1, 2, 3 ]) + "   " );
    assert.equal( type, "json" );

})

it( "guesses csv", function () {
    type = s.guess( new Buffer( "hello,world,foo,bar" ) );
    assert.equal( type, "csv" );
})

it( "guesses tsv", function () {
    type = s.guess( new Buffer( "hello\tworld\tfoo\tbar" ) );
    assert.equal( type, "tsv" );
})

it( "guesses query strings", function () {
    type = s.guess( new Buffer( "?hello=world&foo=bar" ) );
    assert.equal( type, "querystring" );

    type = s.guess( "hello=world&foo=bar" );
    assert.equal( type, "querystring" );
})

it( "guesses tar", function () {
    type = s.guess( "one000644 000765 000024 00000000024 12703723146 012542" );
    assert.equal( type, "tar" );
})

it( "guesses gzip", function () {
    type = s.guess( zlib.gzipSync( "hello world" ) );
    assert.equal( type, "gzip" );
})

it( "no type for empty sample", function () {
    type = s.guess( "" );
    assert.equal( typeof type, "undefined" );
})
<commit_msg>Test actual tar file instead of an invalid tar string<commit_after>var assert = require( "assert" );
var zlib = require( "zlib" );
var s = require( "./index" );
var type;

it( "guesses json", function () {

    type = s.guess( new Buffer( JSON.stringify({ "hello": "world" }) ) )
    assert.equal( type, "json" );

    type = s.guess( "   " + JSON.stringify({ "hello": "world" }) + "  " )
    assert.equal( type, "json" );

    type = s.guess( JSON.stringify([ 1, 2, 3 ]) )
    assert.equal( type, "json" );

    type = s.guess( "     " + JSON.stringify([ 1, 2, 3 ]) + "   " );
    assert.equal( type, "json" );

})

it( "guesses csv", function () {
    type = s.guess( new Buffer( "hello,world,foo,bar" ) );
    assert.equal( type, "csv" );
})

it( "guesses tsv", function () {
    type = s.guess( new Buffer( "hello\tworld\tfoo\tbar" ) );
    assert.equal( type, "tsv" );
})

it( "guesses query strings", function () {
    type = s.guess( new Buffer( "?hello=world&foo=bar" ) );
    assert.equal( type, "querystring" );

    type = s.guess( "hello=world&foo=bar" );
    assert.equal( type, "querystring" );
})

it( "guesses tar", function () {
    var tarball = require( "fs" ).readFileSync( "./test.tar" );
    type = s.guess( tarball );
    assert.equal( type, "tar" );
})

it( "guesses gzip", function () {
    type = s.guess( zlib.gzipSync( "hello world" ) );
    assert.equal( type, "gzip" );
})

it( "no type for empty sample", function () {
    type = s.guess( "" );
    assert.equal( typeof type, "undefined" );
})
<|endoftext|>