<commit_before>// http://www.jblotus.com/2011/05/24/keeping-your-handlebars-js-templates-organized/
function getTemplateAjax(path, callback) {
    var source;
    var template;

    $.ajax({
      url: path,
        success: function(data) {
          source    = data;
          template  = Handlebars.compile(source);

          //execute the callback if passed
          if (callback) callback(template);
        }
    });
}

// http://stackoverflow.com/questions/979975
function getQueryParams(qs) {
    qs = qs.split('+').join(' ');

    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }

    return params;
}

$.fn.scrollView = function () {
    return this.each(function () {
        $('html, body').animate({
            scrollTop: $(this).offset().top
        }, 1000);
    });
}

function loadYAML(name, f) {
    var client = new XMLHttpRequest();
    client.open('GET', 'data/' + name + '.yaml');
    client.onreadystatechange = function() {
        if (client.readyState == 4) {
            var yaml = jsyaml.load(client.responseText);
            if (yaml) {
                f(yaml);
            }
        }
    }
    client.send();
}

function prettifyFinishedEntryInPlace(entry) {
    function dateString(d) {
        // Get a string representation of a date object d.
        return d.getUTCFullYear().toString() + "/" +
            (d.getUTCMonth() + 1).toString() + "/" +
            (d.getUTCDate()).toString();
    }

    var hash = CryptoJS.SHA256(entry.author + entry.title);

    entry['hash'] = hash.toString(CryptoJS.enc.Hex);
    entry.finished = dateString(entry.finished);

    // Convert markdown to HTML in the notes and quotes.
    if ('quotes' in entry) {
        var l = entry.quotes;
        var jLen = l.length;
        for (var j = 0; j < jLen; j++) {
            l[j].content = marked(l[j].content);
        }
    }
    if ('notes' in entry) {
        var l = entry.notes;
        var jLen = l.length;
        for (var j = 0; j < jLen; j++) {
            l[j] = marked(l[j]);
        }
    }
}

function loadLists() {
    if (!isPermalink) {
        getTemplateAjax('templates/to-read.hbars.html', function(tmpl) {
            loadYAML("to-read", function(yaml) {
                yaml.sort(function(a,b) {
                    return a.author.localeCompare(b.author);
                });
                $("#to-read").html(tmpl(yaml));
                $("#to-read-count").append(yaml.length);
            });
        });
    }

    getTemplateAjax('templates/finished.hbars.html', function(tmpl) {
        loadYAML("finished", function(yamlUnfiltered) {
            isComplete = function(book) {
                return book.finished instanceof Date;
            }
            yaml = yamlUnfiltered.filter(isComplete);
            $("#finished-count").append(yaml.length);

            var iLen = yaml.length;
            for (var i = 0; i < iLen; i++) {
                prettifyFinishedEntryInPlace(yaml[i])
                if (isPermalink && yaml[i].hash == params.book) {
                    yaml = [yaml[i]];
                    break;
                }
            }

            if (isPermalink) {
                if (yaml.length != 1 || yaml[0].hash != params.book) {
                    alert("Error: Unable to find book.");
                }
            } else {
                yaml.sort(function(a,b) {
                    if (a.finished > b.finished) return -1;
                    if (a.finished < b.finished) return 1;
                    return 0;
                });

                getTemplateAjax('templates/timeline-body.hbars.html',
                                function(timeline_body_tmpl) {
                                    loadTimeline(yaml,timeline_body_tmpl);
                                });
            }

            $("#finished").html(tmpl(yaml));
            finished_yaml = yaml;

            if (isPermalink) {
                $(".intro").hide();
                $("#rHead").hide();
                $("#cHead").hide();
                $("h2").hide();
                $("#finished").prepend('
'); // TODO: Add this to CSS.
                $(".permalink").hide();
                $("li").hide();
            }
        });
    });

    if (!isPermalink) {
        getTemplateAjax('templates/compilations.hbars.html', function(tmpl) {
            loadYAML("compilations", function(yaml) {
                yaml.sort(function(a,b) {
                    return a.title.localeCompare(b.title);
                });
                $("#compilations").html(tmpl(yaml));
            });
        });
    }
}

function showModal(title,yaml,idx,subfield) {
    var message = null;
    if (subfield == "quotes" && quotes_body_tmpl) {
        message = quotes_body_tmpl(yaml[idx]);
    } else if (subfield == "notes" && notes_body_tmpl) {
        message = notes_body_tmpl(yaml[idx]);
    }

    if (message) {
        bootbox.dialog({
            message: message,
            title: title,
            onEscape: function() {}
        });
        // MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
    }
}

// Close the modal dialog if the background of the document is clicked.
// Reference: https://github.com/makeusabrew/bootbox/issues/210
$(document).on('click', '.bootbox', function(){
    var classname = event.target.className;
    if(classname && !$('.' + classname).parents('.modal-dialog').length)
        bootbox.hideAll();
});

function loadTimeline(finished_yaml, timeline_body_tmpl) {
    var books = []
    $.each(finished_yaml, function(idx, book) {
        book['idx'] = idx;
        books.push({
            "startDate": book.finished.replace(/\//g,","),
            "headline": book.author + ": " + book.title,
            "text": timeline_body_tmpl(book)
        });
    });
    var timelineData = { "timeline": {
        "type": "default",
        "date": books
    }};
    createStoryJS({
        width: "100%",
        height: "400",
        source: timelineData,
        embed_id: 'finished-timeline',
        start_at_end: true
    });
}

function registerHandlebarsHelpers() {
    Handlebars.registerHelper('for', function(from, to, block) {
        var accum = '';
        for(var i = from; i < to; ++i) {
            accum += block.fn(i);
        }
        return accum;
    });

    Handlebars.registerHelper('escape', function(variable) {
        return variable.replace(/(['"])/g, '\\$1');
    });

    // http://stackoverflow.com/questions/12331077
    Handlebars.registerHelper('breaklines', function(text) {
      text = Handlebars.Utils.escapeExpression(text);
      text = text.replace(/(\r\n|\n|\r)/gm, '
');
      return new Handlebars.SafeString(text);
    });
}
<commit_msg>Sort by date, not date string.<commit_after>// http://www.jblotus.com/2011/05/24/keeping-your-handlebars-js-templates-organized/
function getTemplateAjax(path, callback) {
    var source;
    var template;

    $.ajax({
      url: path,
        success: function(data) {
          source    = data;
          template  = Handlebars.compile(source);

          //execute the callback if passed
          if (callback) callback(template);
        }
    });
}

// http://stackoverflow.com/questions/979975
function getQueryParams(qs) {
    qs = qs.split('+').join(' ');

    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }

    return params;
}

$.fn.scrollView = function () {
    return this.each(function () {
        $('html, body').animate({
            scrollTop: $(this).offset().top
        }, 1000);
    });
}

function loadYAML(name, f) {
    var client = new XMLHttpRequest();
    client.open('GET', 'data/' + name + '.yaml');
    client.onreadystatechange = function() {
        if (client.readyState == 4) {
            var yaml = jsyaml.load(client.responseText);
            if (yaml) {
                f(yaml);
            }
        }
    }
    client.send();
}

function prettifyFinishedEntryInPlace(entry) {
    function dateString(d) {
        // Get a string representation of a date object d.
        return d.getUTCFullYear().toString() + "/" +
            (d.getUTCMonth() + 1).toString() + "/" +
            (d.getUTCDate()).toString();
    }

    var hash = CryptoJS.SHA256(entry.author + entry.title);

    entry['hash'] = hash.toString(CryptoJS.enc.Hex);
    entry.finished = dateString(entry.finished);

    // Convert markdown to HTML in the notes and quotes.
    if ('quotes' in entry) {
        var l = entry.quotes;
        var jLen = l.length;
        for (var j = 0; j < jLen; j++) {
            l[j].content = marked(l[j].content);
        }
    }
    if ('notes' in entry) {
        var l = entry.notes;
        var jLen = l.length;
        for (var j = 0; j < jLen; j++) {
            l[j] = marked(l[j]);
        }
    }
}

function loadLists() {
    if (!isPermalink) {
        getTemplateAjax('templates/to-read.hbars.html', function(tmpl) {
            loadYAML("to-read", function(yaml) {
                yaml.sort(function(a,b) {
                    return a.author.localeCompare(b.author);
                });
                $("#to-read").html(tmpl(yaml));
                $("#to-read-count").append(yaml.length);
            });
        });
    }

    getTemplateAjax('templates/finished.hbars.html', function(tmpl) {
        loadYAML("finished", function(yamlUnfiltered) {
            isComplete = function(book) {
                return book.finished instanceof Date;
            }
            yaml = yamlUnfiltered.filter(isComplete);
            $("#finished-count").append(yaml.length);

            // Must be done before `prettifyFinishedEntryInPlace`.
            // Otherwise, the dates are sorted as strings.
            if (!isPermalink) {
                yaml.sort(function(a,b) {
                    if (a.finished > b.finished) return -1;
                    if (a.finished < b.finished) return 1;
                    return 0;
                });
            }

            var iLen = yaml.length;
            for (var i = 0; i < iLen; i++) {
                prettifyFinishedEntryInPlace(yaml[i])
                if (isPermalink && yaml[i].hash == params.book) {
                    yaml = [yaml[i]];
                    break;
                }
            }

            if (isPermalink) {
                if (yaml.length != 1 || yaml[0].hash != params.book) {
                    alert("Error: Unable to find book.");
                }
            } else {
                getTemplateAjax('templates/timeline-body.hbars.html',
                                function(timeline_body_tmpl) {
                                    loadTimeline(yaml,timeline_body_tmpl);
                                });
            }

            $("#finished").html(tmpl(yaml));
            finished_yaml = yaml;

            if (isPermalink) {
                $(".intro").hide();
                $("#rHead").hide();
                $("#cHead").hide();
                $("h2").hide();
                $("#finished").prepend('
'); // TODO: Add this to CSS.
                $(".permalink").hide();
                $("li").hide();
            }
        });
    });

    if (!isPermalink) {
        getTemplateAjax('templates/compilations.hbars.html', function(tmpl) {
            loadYAML("compilations", function(yaml) {
                yaml.sort(function(a,b) {
                    return a.title.localeCompare(b.title);
                });
                $("#compilations").html(tmpl(yaml));
            });
        });
    }
}

function showModal(title,yaml,idx,subfield) {
    var message = null;
    if (subfield == "quotes" && quotes_body_tmpl) {
        message = quotes_body_tmpl(yaml[idx]);
    } else if (subfield == "notes" && notes_body_tmpl) {
        message = notes_body_tmpl(yaml[idx]);
    }

    if (message) {
        bootbox.dialog({
            message: message,
            title: title,
            onEscape: function() {}
        });
        // MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
    }
}

// Close the modal dialog if the background of the document is clicked.
// Reference: https://github.com/makeusabrew/bootbox/issues/210
$(document).on('click', '.bootbox', function(){
    var classname = event.target.className;
    if(classname && !$('.' + classname).parents('.modal-dialog').length)
        bootbox.hideAll();
});

function loadTimeline(finished_yaml, timeline_body_tmpl) {
    var books = []
    $.each(finished_yaml, function(idx, book) {
        book['idx'] = idx;
        books.push({
            "startDate": book.finished.replace(/\//g,","),
            "headline": book.author + ": " + book.title,
            "text": timeline_body_tmpl(book)
        });
    });
    var timelineData = { "timeline": {
        "type": "default",
        "date": books
    }};
    createStoryJS({
        width: "100%",
        height: "400",
        source: timelineData,
        embed_id: 'finished-timeline',
        start_at_end: true
    });
}

function registerHandlebarsHelpers() {
    Handlebars.registerHelper('for', function(from, to, block) {
        var accum = '';
        for(var i = from; i < to; ++i) {
            accum += block.fn(i);
        }
        return accum;
    });

    Handlebars.registerHelper('escape', function(variable) {
        return variable.replace(/(['"])/g, '\\$1');
    });

    // http://stackoverflow.com/questions/12331077
    Handlebars.registerHelper('breaklines', function(text) {
      text = Handlebars.Utils.escapeExpression(text);
      text = text.replace(/(\r\n|\n|\r)/gm, '
');
      return new Handlebars.SafeString(text);
    });
}
<|endoftext|>


<commit_before>'use strict'

// Load env for local development
if (['staging', 'production'].indexOf(process.env.NODE_ENV) === -1) {
  require('dotenv').config({path: `${process.cwd()}/.env`})
}

const bodyParser = require('body-parser')
const express = require('express')
const config = require('./config')
const msn = require('./messenger')

const cm = config.messenger
const app = express()

const fbids = msn.fbids
const mUtils = msn.utils

const jsonParser = bodyParser.json()
const jsonParserWithSignature = bodyParser.json({
  verify: msn.verifyRequestSignature
})

app.get('/webhook', (req, res) => {
  if (req.query['hub.mode'] === 'subscribe' &&
      req.query['hub.verify_token'] === cm.validationToken) {
    console.log('Validating webhook')
    res.status(200).send(req.query['hub.challenge'])
  } else {
    console.error('Failed validation. Make sure the validation tokens match.')
    res.sendStatus(403)
  }
})

app.post('/webhook', jsonParserWithSignature, (req, res) => {
  const data = req.body

  // Make sure this is a page subscription
  if (data.object === 'page') {
    // Iterate over each entry
    // There may be multiple if batched
    data.entry.forEach((pageEntry) => {
      const pageID = pageEntry.id
      const timeOfEvent = pageEntry.time

      // Iterate over each messaging event
      pageEntry.messaging.forEach((messagingEvent) => {
        if (messagingEvent.optin) {
          msn.receivedAuthentication(messagingEvent)
        } else if (messagingEvent.message) {
          msn.receivedMessage(messagingEvent)
        } else if (messagingEvent.delivery) {
          msn.receivedDeliveryConfirmation(messagingEvent)
        } else if (messagingEvent.postback) {
          msn.receivedPostback(messagingEvent)
        } else {
          console.log('Webhook received unknown messagingEvent: ', messagingEvent)
        }
      })
    })

    // Must send back a 200, within 20 seconds, for successfully received the callback.
    // Otherwise, the request will time out.
    res.sendStatus(200)
  }
})

app.post('/bot/v1.0/messages', jsonParser, (req, res) => {
  // Sent to fb messenger
  const message = req.body
  const senderId = message.to.id
  const text = message.text

  fbids[senderId] = message

  console.log(JSON.stringify(message))

  msn.sendTextMessage(senderId, text)

  res.sendStatus(200)
})

app.listen(config.app.port, () => {
  console.log(`${config.app.name} is running on port ${config.app.port}.`)
})

module.exports = app
<commit_msg>Check if text param exists<commit_after>'use strict'

// Load env for local development
if (['staging', 'production'].indexOf(process.env.NODE_ENV) === -1) {
  require('dotenv').config({path: `${process.cwd()}/.env`})
}

const bodyParser = require('body-parser')
const express = require('express')
const config = require('./config')
const msn = require('./messenger')

const cm = config.messenger
const app = express()

const fbids = msn.fbids
const mUtils = msn.utils

const jsonParser = bodyParser.json()
const jsonParserWithSignature = bodyParser.json({
  verify: msn.verifyRequestSignature
})

app.get('/webhook', (req, res) => {
  if (req.query['hub.mode'] === 'subscribe' &&
      req.query['hub.verify_token'] === cm.validationToken) {
    console.log('Validating webhook')
    res.status(200).send(req.query['hub.challenge'])
  } else {
    console.error('Failed validation. Make sure the validation tokens match.')
    res.sendStatus(403)
  }
})

app.post('/webhook', jsonParserWithSignature, (req, res) => {
  const data = req.body

  // Make sure this is a page subscription
  if (data.object === 'page') {
    // Iterate over each entry
    // There may be multiple if batched
    data.entry.forEach((pageEntry) => {
      const pageID = pageEntry.id
      const timeOfEvent = pageEntry.time

      // Iterate over each messaging event
      pageEntry.messaging.forEach((messagingEvent) => {
        if (messagingEvent.optin) {
          msn.receivedAuthentication(messagingEvent)
        } else if (messagingEvent.message) {
          msn.receivedMessage(messagingEvent)
        } else if (messagingEvent.delivery) {
          msn.receivedDeliveryConfirmation(messagingEvent)
        } else if (messagingEvent.postback) {
          msn.receivedPostback(messagingEvent)
        } else {
          console.log('Webhook received unknown messagingEvent: ', messagingEvent)
        }
      })
    })

    // Must send back a 200, within 20 seconds, for successfully received the callback.
    // Otherwise, the request will time out.
    res.sendStatus(200)
  }
})

app.post('/bot/v1.0/messages', jsonParser, (req, res) => {
  // Sent to fb messenger
  const message = req.body
  const senderId = message.to.id
  const text = message.text

  if (text) {
    fbids[senderId] = message

    console.log(JSON.stringify(message))

    msn.sendTextMessage(senderId, text)
  }

  res.sendStatus(200)
})

app.listen(config.app.port, () => {
  console.log(`${config.app.name} is running on port ${config.app.port}.`)
})

module.exports = app
<|endoftext|>


<commit_before>import {bindable, inject, customElement} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';

@customElement('google-map')
@inject(Element, EventAggregator)
export class GoogleMaps {
    constructor(element, ea) {
        this.element = element;
        this.ea = ea;
    }

    attached() {
        var classRef = this;

        this.element.addEventListener('dragstart', evt => {
            evt.preventDefault();
        });

        this.ea.subscrube('google.maps.ready', () => {
            this.map = new google.maps.Map(this.element);
            this.map.markers = {};
            this.map.shapes = {};
        });

        window.myGoogleMapsCallback = function() {
            classRef.ea.publish('google.maps.ready');
        };
    }

    getCurrentPosition() {
        return new Promise((resolve, reject) => {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(position => resolve(position), evt => reject(evt));
            } else {
                reject('Browser Geolocation not supported or found.')
            }
        });
    }

    loadApiScript() {
        if (window.google === undefined || window.google.maps === undefined) {
            let scriptEl = document.createElement('script');
            scriptEl.src = 'https://maps.googleapis.com/maps/api/js&callback=myGoogleMapsCallback';
            document.body.appendChild(scriptEl);
        }
    }

    error() {
        console.log.apply(console, arguments);
    }
}
<commit_msg>Fixing up a typo and adding in ability to load Google API script (if not already loaded).<commit_after>import {bindable, inject, customElement} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';

@customElement('google-map')
@inject(Element, EventAggregator)
export class GoogleMaps {
    constructor(element, ea) {
        this.element = element;
        this.ea = ea;

        this.apikey = '';
    }

    attached() {
        var classRef = this;

        console.log('Attached');

        this.element.addEventListener('dragstart', evt => {
            evt.preventDefault();
        });

        this.ea.subscribe('google.maps.ready', () => {
            this.map = new google.maps.Map(this.element);
            this.map.markers = {};
            this.map.shapes = {};
        });

        window.myGoogleMapsCallback = function() {
            classRef.ea.publish('google.maps.ready');
        };

        this.loadApiScript();
    }

    getCurrentPosition() {
        return new Promise((resolve, reject) => {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(position => resolve(position), evt => reject(evt));
            } else {
                reject('Browser Geolocation not supported or found.')
            }
        });
    }

    loadApiScript() {
        if (window.google === undefined || window.google.maps === undefined) {
            let scriptEl = document.createElement('script');
            scriptEl.src = `https://maps.googleapis.com/maps/api/js?key=${this.apikey}&callback=myGoogleMapsCallback`;
            document.body.appendChild(scriptEl);
        }
    }

    error() {
        console.log.apply(console, arguments);
    }
}
<|endoftext|>


<commit_before>/** dependencies */
var path = require('path');
var Promise = require('promise');
var express = require('express');
var bodyParser = require("body-parser");
var fs = require('fs');

/** create app and register middleware */
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

/** run wemo and load config */
var bridge = require('./bridge');
var config = JSON.parse(fs.readFileSync('config.json', 'utf8'));

bridge.init(config);

app.get('/api/devices', function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.send(bridge.getDevices());
});

app.get('/api/device/:id/toggle', function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var id = req.param("id");
    bridge.toggle(id)
        .then(function(result) {
            res.send(result);
        }, function(err) {
            res.send({ error: err });
        });
});
app.get('/api/device/:id/brightness/:value', function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var id = req.param("id");
    var value = req.param("value");

    bridge.setValue(id, 'brightness', value)
        .then(function(result) {
            res.send(result);
        }, function(err) {
            res.send({ error: err });
        });
});

app.get('/api/rules/', function(req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.send(bridge.getRules());
});
app.post('/api/rule/:id/update', function(req, res) {
    res.setHeader('Content-Type', 'application/json');
    var id = req.param("id");
    var rule = bridge.updateRule(req.body, id);
    storeConfig()
        .then(function(result) {
            console.log(result);
        }, function(err) {
            console.log(err);
        });
    res.send(rule);
});

app.get('/api/rule/:name/:action', function (req, res) {
    var name = req.param("name");
    var action = req.param("action");
    bridge.controlRule(name, action)
        .then(function(rule) {
            res.send(rule);
        }, function(err) {
            res.status(404).send(err);
        });
});

app.use('/', express.static('examples'));

function storeConfig() {
    return new Promise(function(resolve, reject) {
        var rules = bridge.getRules();
        config.rules = rules;
        var configString = JSON.stringify(config, null, 4);

        fs.writeFile("./config.json", configString, function(err) {
            if(err) {
                reject("Unable to write config: " + err);
            } else {
                resolve("Config written");
            }
        });
    });
}

var port = 8080;
if(config.host) {
    port = config.host.port;
}

app.listen(port, function (err) {
  if (err) {
    return console.error(err);
  }
  console.log('Listening on http://localhost:' + port);
});
<commit_msg>Backend serves correct frontend<commit_after>/** dependencies */
var path = require('path');
var Promise = require('promise');
var express = require('express');
var bodyParser = require("body-parser");
var fs = require('fs');

/** create app and register middleware */
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

/** run wemo and load config */
var bridge = require('./bridge');
var config = JSON.parse(fs.readFileSync('config.json', 'utf8'));

bridge.init(config);

app.get('/api/devices', function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.send(bridge.getDevices());
});

app.get('/api/device/:id/toggle', function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var id = req.param("id");
    bridge.toggle(id)
        .then(function(result) {
            res.send(result);
        }, function(err) {
            res.send({ error: err });
        });
});
app.get('/api/device/:id/brightness/:value', function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var id = req.param("id");
    var value = req.param("value");

    bridge.setValue(id, 'brightness', value)
        .then(function(result) {
            res.send(result);
        }, function(err) {
            res.send({ error: err });
        });
});

app.get('/api/rules/', function(req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.send(bridge.getRules());
});
app.post('/api/rule/:id/update', function(req, res) {
    res.setHeader('Content-Type', 'application/json');
    var id = req.param("id");
    var rule = bridge.updateRule(req.body, id);
    storeConfig()
        .then(function(result) {
            console.log(result);
        }, function(err) {
            console.log(err);
        });
    res.send(rule);
});

app.get('/api/rule/:name/:action', function (req, res) {
    var name = req.param("name");
    var action = req.param("action");
    bridge.controlRule(name, action)
        .then(function(rule) {
            res.send(rule);
        }, function(err) {
            res.status(404).send(err);
        });
});

app.use('/', express.static('frontend'));

function storeConfig() {
    return new Promise(function(resolve, reject) {
        var rules = bridge.getRules();
        config.rules = rules;
        var configString = JSON.stringify(config, null, 4);

        fs.writeFile("./config.json", configString, function(err) {
            if(err) {
                reject("Unable to write config: " + err);
            } else {
                resolve("Config written");
            }
        });
    });
}

var port = 8080;
if(config.host) {
    port = config.host.port;
}

app.listen(port, function (err) {
  if (err) {
    return console.error(err);
  }
  console.log('Listening on http://localhost:' + port);
});
<|endoftext|>


<commit_before>game.PlayScreen = me.ScreenObject.extend({
	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		me.audio.playTrack('c4');
		// reset the score
		game.data.score = 0;

		me.levelDirector.loadLevel("level01")

		// this tells it what to look at as far as maps
		// in melon js we use a naming convention which means the first letter is lower case and the first letter of the next word is upper case.

        this.resetPlayer(0, 420);

        var gameTimerManager = me.pool.pull("GameTimerManager", 0, 0, {});
        me.game.world.addChild(gameTimerManager, 0);

        var heroDeathManager = me.pool.pull("HeroDeathManager", 0, 0, {});
        me.game.world.addChild(heroDeathManager, 0);

        var experienceManager = me.pool.pull("ExperienceManager", 0, 0, {});
        me.game.world.addChild(experienceManager, 0);

        var spendGold = me.pool.pull("SpendGold", 0, 0, {});
        me.game.world.addChild(spendGold, 0);

        game.data.minimap = me.pool.pull("minimap", 10, 10, {});
        me.game.world.addChild(game.data.minimap, 30);

        me.input.bindKey(me.input.KEY.B, "buy");
        me.input.bindKey(me.input.KEY.Z, "skill1");
        me.input.bindKey(me.input.KEY.X, "skill2"),
        me.input.bindKey(me.input.KEY.C, "skill3"),
        me.input.bindKey(me.input.KEY.RIGHT, "right");
        me.input.bindKey(me.input.KEY.LEFT, "left");
        me.input.bindKey(me.input.KEY.UP, "jump", true);
        me.input.bindKey(me.input.KEY.DOWN, "attack");
        //this is where we will be adding our player
        //we will do that by adding our instances of the player
        // the z variable is the distance of the player to the front of the screen
        // if you have a low number, you can possibly becovered by the layers we are using in tiled

		// add our HUD to the game world
		this.HUD = new game.HUD.Container();
		me.game.world.addChild(this.HUD);
	},

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function() {
		me.audio.stopTrack();
		// remove the HUD from the game world
		me.game.world.removeChild(this.HUD);
	},

	resetPlayer: function(x, y){

	    game.data.player = me.pool.pull("player", x, y, {});
        me.game.world.addChild(game.data.player, 5);
	}

});

<commit_msg>Video i5 commented<commit_after>game.PlayScreen = me.ScreenObject.extend({
	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		me.audio.playTrack('c4');
		// reset the score
		game.data.score = 0;

		me.levelDirector.loadLevel("level01")

		// this tells it what to look at as far as maps
		// in melon js we use a naming convention which means the first letter is lower case and the first letter of the next word is upper case.

        this.resetPlayer(0, 420);

        var gameTimerManager = me.pool.pull("GameTimerManager", 0, 0, {});
        me.game.world.addChild(gameTimerManager, 0);

        var heroDeathManager = me.pool.pull("HeroDeathManager", 0, 0, {});
        me.game.world.addChild(heroDeathManager, 0);

        var experienceManager = me.pool.pull("ExperienceManager", 0, 0, {});
        me.game.world.addChild(experienceManager, 0);

        var spendGold = me.pool.pull("SpendGold", 0, 0, {});
        me.game.world.addChild(spendGold, 0);

        game.data.minimap = me.pool.pull("minimap", 10, 10, {});
        me.game.world.addChild(game.data.minimap, 30);

        me.input.bindKey(me.input.KEY.B, "buy");
        me.input.bindKey(me.input.KEY.Z, "skill1");
        me.input.bindKey(me.input.KEY.X, "skill2"),
        me.input.bindKey(me.input.KEY.C, "skill3"),
        me.input.bindKey(me.input.KEY.RIGHT, "right");
        me.input.bindKey(me.input.KEY.LEFT, "left");
        me.input.bindKey(me.input.KEY.UP, "jump", true);
        me.input.bindKey(me.input.KEY.DOWN, "attack");
        //this is where we will be adding our player
        //we will do that by adding our instances of the player
        // the z variable is the distance of the player to the front of the screen
        // if you have a low number, you can possibly becovered by the layers we are using in tiled

		// add our HUD to the game world
		this.HUD = new game.HUD.Container();
		me.game.world.addChild(this.HUD);
	},

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function() {
		me.audio.stopTrack();
		// remove the HUD from the game world
		me.game.world.removeChild(this.HUD);
	},

	resetPlayer: function(x, y){

	    game.data.player = me.pool.pull("player", x, y, {});
        me.game.world.addChild(game.data.player, 5);
	}

});

// we have linked our minimap image to our resources

// next we are putting the minimaps info into game.js

// our minimap is now in our pool

// we are adding a high z level for the mini map also
<|endoftext|>


<commit_before>var requirejs = require('requirejs');

//Config for libraries accessible and require js
var app_config = requirejs('./config');
app_config.baseUrl = 'app/';
app_config.nodeRequire = require;
requirejs.config(app_config);

//Command line args
var argv = require('optimist').argv;
var environment = process.env.NODE_ENV || argv.env || 'development';

//GLOBALS:

//- setting server $ stuff
var backbone = require('backbone');
    XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

var $ = global.$ = backbone.$ = global.jQuery = require('jquery');
$.support.cors = true;

$.ajaxSettings.xhr = function () {
    return new XMLHttpRequest();
};

//- the rest
global.isServer = true;
global.isClient = false;

global._ = require('underscore');
global.config = requirejs('environment_config').configure(environment, argv);
global.logger = requirejs('logger');

//App stuff

if(environment.match(/^development/)){
  environment = 'development';
}

var http = require('http'),
    path = require('path');

var rootDir = path.join(__dirname, '..');
var app = requirejs('appBuilder').getApp(environment, rootDir, argv.REQUIRE_BASE_URL);

var server = http.createServer(app).listen(app.get('port'), function(){
  global.logger.info("Express server listening on port " + app.get('port'));
});

exports = module.exports = server;

exports.use = function () {
	app.use.apply(app, arguments);
};
<commit_msg>Lint app/server.js<commit_after>var requirejs = require('requirejs');

//Config for libraries accessible and require js
var app_config = requirejs('./config');
app_config.baseUrl = 'app/';
app_config.nodeRequire = require;
requirejs.config(app_config);

//Command line args
var argv = require('optimist').argv;
var environment = process.env.NODE_ENV || argv.env || 'development';

//GLOBALS:

//- setting server $ stuff
var backbone = require('backbone'),
    XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

var $ = global.$ = backbone.$ = global.jQuery = require('jquery');
$.support.cors = true;

$.ajaxSettings.xhr = function () {
  return new XMLHttpRequest();
};

//- the rest
global.isServer = true;
global.isClient = false;

global._ = require('underscore');
global.config = requirejs('environment_config').configure(environment, argv);
global.logger = requirejs('logger');

//App stuff

if(environment.match(/^development/)){
  environment = 'development';
}

var http = require('http'),
    path = require('path');

var rootDir = path.join(__dirname, '..');
var app = requirejs('appBuilder').getApp(environment, rootDir, argv.REQUIRE_BASE_URL);

var server = http.createServer(app).listen(app.get('port'), function(){
  global.logger.info("Express server listening on port " + app.get('port'));
});

exports = module.exports = server;

exports.use = function () {
  app.use.apply(app, arguments);
};
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; <commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; c<|endoftext|>


<commit_before>// Copyright 2016 Google Inc. All rights reserved.
//
// 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(internal) {

  function parsePositionValue(str) {
    var params = internal.parsing.consumeRepeated(
        internal.parsing.consumeLengthValue,
        null, // separator not required due to use of consumeTrimmed.
        str);
    if (!params || params[0].length != 2) {
      return;
    }
    console.log(params);
    var lengths = params[0];
    return [new CSSPositionValue(lengths[0], lengths[1]), params[1]];
  }

  internal.parsing.parsePositionValue = parsePositionValue;
})(typedOM.internal);
<commit_msg>Remove console.log<commit_after>// Copyright 2016 Google Inc. All rights reserved.
//
// 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(internal) {

  function parsePositionValue(str) {
    var params = internal.parsing.consumeRepeated(
        internal.parsing.consumeLengthValue,
        null, // separator not required due to use of consumeTrimmed.
        str);
    if (!params || params[0].length != 2) {
      return;
    }
    var lengths = params[0];
    return [new CSSPositionValue(lengths[0], lengths[1]), params[1]];
  }

  internal.parsing.parsePositionValue = parsePositionValue;
})(typedOM.internal);
<|endoftext|>


<commit_before>var Raspi = require("raspi-io");
var five = require("johnny-five");
var pitft = require("pitft");
var sleep = require('sleep');

var fb = pitft("/dev/fb1"); // Returns a framebuffer in direct mode.  See the clock.js example for double buffering mode

var xMax = fb.size().width;
console.log(xMax);
var yMax = fb.size().height;
console.log(yMax);

// Clear the screen buffer
fb.clear();
fb.color(1, 1, 1); // Set the color to whit
fb.font("fantasy", 12); // Use the "fantasy" font with size 12

fb.text(0,20,"Latitude:",false);
fb.text(0,40,"Longitude:",false);
fb.text(0,60,"Speed:",false);
fb.text(0,80,"Course:",false);
fb.text(0,100,"Longitude:",false);
fb.text(0,120,"Balance:",false);
fb.text(0,140,"Volume:",false);
fb.text(0,160,"Stroke Rate:",false);
fb.text(0,180,"/500:",false);
fb.text(0,200,"Race Mode: 5000m",false);
fb.text(0,220,"Estimated Finish time:",false);

sleep.sleep(5);
/*
sleep.sleep(5)

fb.clear();
fb.text(0,20,"Latitude: ya",false);
fb.text(0,40,"Longitude: boy",false);
fb.text(0,60,"Speed: the ",false);
fb.text(0,80,"Course: lazy ",false);
fb.text(0,100,"Longitude: brown",false);
fb.text(0,120,"Balance: cow",false);
fb.text(0,140,"Volume: jumped",false);
fb.text(0,160,"Stroke Rate: over",false);
fb.text(0,180,"/500: your ",false);
fb.text(0,200,"Race Mode: 5000m mom",false);
fb.text(0,220,"Estimated Finish time: lol",false);
*/
//fb.font("fantasy", 12); // Use the "fantasy" font with size 12
//fb.text(0, 20, "HI", false); // Draw the text non-centered, rotated _a_ degrees
//sleep.sleep(5);

console.log("Starting Board");

var board = new five.Board({
  io: new Raspi()
});

board.on("ready", function() {
  var imu = new five.IMU({
    controller: "MPU6050"
  });

  var gps = new five.GPS({
    breakout: "ADAFRUIT_ULTIMATE_GPS",
    pins: ['P1-8', 'P1-10']
  });

  /*
  var volumecontrol = new five.i2c({
    controller: "i2c"
  });

  var strokeRate = new five.Board({
    controller: "arduino"
  });
  */

  gps.on("change", function() {
    console.log("GPS Data");
    console.log("  Speed   : ", gps.speed);
    console.log("  Course  : ", gps.course);
    console.log("  latitude   : ", gps.latitude);
    console.log("  longitude  : ", gps.longitude);
    console.log("  altitude   : ", gps.altitude);
    console.log("MPU6050 Roll Data");
    console.log("  pitch   : ", imu.gyro.pitch);
    //console.log("Volume");
    //console.log("  Volume   : ",volumecontrol.currentVolume);
    //console.log("Stroke Rate");
    //console.log("  Stroke Rate   : ",strokeRate.currentStrokeRate);
    console.log("--------------------------------------");

  });
});
<commit_msg>with access<commit_after>var Raspi = require("raspi-io");
var five = require("johnny-five");
var pitft = require("pitft");
var sleep = require('sleep');

var fb = pitft("/dev/fb1"); // Returns a framebuffer in direct mode.  See the clock.js example for double buffering mode

var xMax = fb.size().width;
console.log(xMax);
var yMax = fb.size().height;
console.log(yMax);

// Clear the screen buffer
fb.clear();
fb.color(1, 1, 1); // Set the color to whit
fb.font("fantasy", 12); // Use the "fantasy" font with size 12

fb.text(0,20,"Latitude:",false);
fb.text(0,40,"Longitude:",false);
fb.text(0,60,"Speed:",false);
fb.text(0,80,"Course:",false);
fb.text(0,100,"Longitude:",false);
fb.text(0,120,"Balance:",false);
fb.text(0,140,"Volume:",false);
fb.text(0,160,"Stroke Rate:",false);
fb.text(0,180,"/500:",false);
fb.text(0,200,"Race Mode: 5000m",false);
fb.text(0,220,"Estimated Finish time:",false);

sleep.sleep(5);
/*
sleep.sleep(5)

fb.clear();
fb.text(0,20,"Latitude: ya",false);
fb.text(0,40,"Longitude: boy",false);
fb.text(0,60,"Speed: the ",false);
fb.text(0,80,"Course: lazy ",false);
fb.text(0,100,"Longitude: brown",false);
fb.text(0,120,"Balance: cow",false);
fb.text(0,140,"Volume: jumped",false);
fb.text(0,160,"Stroke Rate: over",false);
fb.text(0,180,"/500: your ",false);
fb.text(0,200,"Race Mode: 5000m mom",false);
fb.text(0,220,"Estimated Finish time: lol",false);
*/
//fb.font("fantasy", 12); // Use the "fantasy" font with size 12
//fb.text(0, 20, "HI", false); // Draw the text non-centered, rotated _a_ degrees
//sleep.sleep(5);

console.log("Starting Board");

var board = new five.Board({
  io: new Raspi()
});

board.on("ready", function() {
  var imu = new five.IMU({
    controller: "MPU6050"
  });

  var gps = new five.GPS({
    breakout: "ADAFRUIT_ULTIMATE_GPS",
    pins: ['P1-8', 'P1-10']
  });

  /*
  var volumecontrol = new five.i2c({
    controller: "i2c"
  });

  var strokeRate = new five.Board({
    controller: "arduino"
  });
  */

  gps.on("change", function() {
    console.log("GPS Data");
    console.log("  Speed   : ", gps.speed);
    console.log("  Course  : ", gps.course);
    console.log("  latitude   : ", gps.latitude);
    console.log("  longitude  : ", gps.longitude);
    console.log("  altitude   : ", gps.altitude);
    console.log("MPU6050 Roll Data");
    console.log("  pitch   : ", imu.gyro.pitch);
    console.log("MPU6050 Starting Acceleration");
    console.log("  x   : ", imu.accelerometer.x);
    console.log("  y   : ", imu.accelerometer.y);
    console.log("  z   : ", imu.accelerometer.z);
    //console.log("Volume");
    //console.log("  Volume   : ",volumecontrol.currentVolume);
    //console.log("Stroke Rate");
    //console.log("  Stroke Rate   : ",strokeRate.currentStrokeRate);
    console.log("--------------------------------------");

  });
});
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mea<commit_msg>Commit all the required changes<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean<|endoftext|>


<commit_before>import _ from 'lodash'
import { BadRequest } from 'feathers-errors'
import { getItems } from 'feathers-hooks-common'
import { populateObject } from './hooks.query'
import makeDebug from 'debug'

const debug = makeDebug('kalisio:kCore:tags:hooks')

export function isTagEqual (tag1, tag2) {
  let equal = (tag1.value === tag2.value && tag1.scope === tag2.scope)
  // when context is provided use it as well
  if (tag1.context && tag2.context) {
    equal = equal && (tag1.context.toString() === tag2.context.toString())
  }
  return equal
}

export function populateTagResource (hook) {
  if (hook.type !== 'before') {
    throw new Error(`The 'populateTagResource' hook should only be used as a 'before' hook.`)
  }

  // Avoid populating any target resource when resource parameters are not present
  return populateObject({ serviceField: 'resourcesService', idField: 'resource', throwOnNotFound: false })(hook)
}

export async function updateTags (hook) {
  let item = getItems(hook)
  if (!item.tags) {
    debug('No tags to update for object ', item)
    return Promise.resolve(hook)
  }
  // Tag service is contextual, look for context on initiator service
  const context = hook.service.context
  // Retrieve previous version of the item
  let previousTags = _.get(hook.params, 'previousItem.tags')
  if (previousTags) {
    // Find common tags
    const commonTags = _.intersectionWith(item.tags, previousTags, isTagEqual)
    // Clear removed tags
    const removedTags = _.differenceWith(previousTags, commonTags, isTagEqual)
    debug('Removing tags for object ', item, removedTags)
    const removePromises = removedTags.map(tag => {
      // When a contextual service is used we might not provide the context in tag, extract from service instead
      const tagService = hook.app.getService('tags', tag.context || context)
      if (!tagService) return Promise.reject(new Error('No valid context found to retrieve tag service for ', tag))
      else return tagService.remove(null, { query: tag })
    })
    // And add new ones
    const addedTags = _.differenceWith(item.tags, commonTags, isTagEqual)
    debug('Adding tags for object ', item, addedTags)
    const addedPromises = addedTags.map(tag => {
      // When a contextual service is used we might not provide the context in tag, extract from service instead
      const tagService = hook.app.getService('tags', tag.context || context)
      if (!tagService) return Promise.reject(new Error('No valid context found to retrieve tag service for ', tag))
      else return tagService.create(tag)
    })
    let [ oldTags, newTags ] = await Promise.all([
      Promise.all(removePromises),
      Promise.all(addedPromises)
    ])
    debug('Tags removed/added', oldTags, newTags)
    // Update tags to include information added when they are created (eg _id)
    // and add also context because tags might come from different ones on the same target object
    newTags = newTags.map(tag => {
      if (tag.context) return tag
      else return Object.assign({ context: (typeof context === 'object' ? context._id : context) }, tag)
    })
    item.tags = commonTags.concat(newTags)
  } else {
    if (hook.method !== 'remove') {
      // Add new tags
      debug('Adding tags for object ', item)
      const addPromises = item.tags.map(tag => {
        // When a contextual service is used we might not provide the context in tag, extract from service instead
        const tagService = hook.app.getService('tags', tag.context || context)
        if (!tagService) return Promise.reject(new Error('No valid context found to retrieve tag service for ', tag))
        else return tagService.create(tag)
      })
      // Update tags to include information added when they are created (eg _id)
      let newTags = await Promise.all(addPromises)
      // and add also context because tags might come from different ones on the same target object
      newTags = newTags.map(tag => {
        if (tag.context) return tag
        else return Object.assign({ context: (typeof context === 'object' ? context._id : context) }, tag)
      })
      item.tags = newTags
    } else {
      debug('Removing tags for object ', item)
      const removePromises = item.tags.map(tag => {
        // When a contextual service is used we might not provide the context in tag, extract from service instead
        const tagService = hook.app.getService('tags', tag.context || context)
        if (!tagService) return Promise.reject(new Error('No valid context found to retrieve tag service for ', tag))
        else return tagService.remove(null, { query: tag })
      })
      await Promise.all(removePromises)
    }
  }
  // Avoid transferring some internal data
  // item.tags = item.tags.map(tag => _.omit(tag, ['count']))

  return hook
}

export function addTagIfNew (hook) {
  if (hook.type !== 'before') {
    throw new Error(`The 'addTagIfNew' hook should only be used as a 'before' hook.`)
  }
  const tagService = hook.service
  const value = _.get(hook, 'data.value')
  const scope = _.get(hook, 'data.scope')
  if (!value || !scope) {
    throw new BadRequest('Scope and value should be provided to create a tag')
  }

  return tagService.find({ query: { value, scope } })
  .then(result => {
    // If it already exist avoid creating it in DB,
    // simply update counter and return it
    if (result.total > 0) {
      let tag = result.data[0]
      hook.result = tag
      tag.count += 1
      debug('Increasing tag ' + tag.value + ' count (' + tag.count + ') with scope ' + tag.scope)
      return tagService.patch(tag._id.toString(), { count: tag.count })
    } else {
      // Otherwise initialize tag counter
      hook.data.count = 1
      return Promise.resolve(hook)
    }
  })
  .then(() => {
    return hook
  })
}

export function removeTagIfUnused (hook) {
  if (hook.type !== 'before') {
    throw new Error(`The 'removeTagIfUnused' hook should only be used as a 'before' hook.`)
  }

  const tagService = hook.service
  const value = _.get(hook.params, 'query.value')
  const scope = _.get(hook.params, 'query.scope')
  if (!value || !scope) {
    throw new BadRequest('Scope and value should be provided to remove a tag')
  }

  return tagService.find({ query: { value, scope } })
  .then(result => {
    // If it already exist decrease counter and erase it if not used anymore
    if (result.total > 0) {
      let tag = result.data[0]
      hook.result = tag
      tag.count -= 1
      if (tag.count <= 0) {
        debug('Removing unused tag ' + tag.value + ' with scope ' + tag.scope)
        return tagService.remove(tag._id.toString())
      } else {
        debug('Decreasing tag ' + tag.value + ' count (' + tag.count + ') with scope ' + tag.scope)
        return tagService.patch(tag._id.toString(), { count: tag.count })
      }
    } else {
      // Should not be possible, this will skip DB call
      hook.result = null
      return Promise.resolve(hook)
    }
  })
  .then(() => {
    return hook
  })
}

export function tagResource (hook) {
  if (hook.type !== 'after') {
    throw new Error(`The 'tagResource' hook should only be used as a 'after' hook.`)
  }
  const tag = hook.result
  const params = hook.params
  const query = params.query
  const context = hook.service.context
  const resourcesService = params.resourcesService
  let resource = params.resource
  // If not already tagged
  if (!_.find(resource.tags, resourceTag => isTagEqual(resourceTag, tag))) {
    // Initialize on first tag
    if (!resource.tags) {
      resource.tags = []
    }
    // Add context because tags might come from different ones on the same target object
    if (context) {
      tag.context = (typeof context === 'object' ? context._id : context)
    }
    resource.tags.push(tag)
    return resourcesService.patch(resource._id.toString(), {
      tags: resource.tags
    }, {
      user: hook.params.user,
      // Forward query so that any update param could be processed as usual on resource
      // Delete own parameters from query otherwise it will be used to filter items
      query: _.omit(query, ['resource', 'resourcesService'])
    })
    .then(subject => {
      debug('Tag ' + tag.value + ' set on resource ' + resource._id.toString() + ' with scope ' + tag.scope)
      return hook
    })
  } else {
    return Promise.resolve(hook)
  }
}

export function untagResource (hook) {
  if (hook.type !== 'after') {
    throw new Error(`The 'untagResource' hook should only be used as a 'after' hook.`)
  }

  const tag = hook.result
  const params = hook.params
  const query = params.query
  const resourcesService = params.resourcesService
  let resource = params.resource
  // If already tagged
  const tagIndex = _.findIndex(resource.tags, resourceTag => isTagEqual(resourceTag, tag))
  if (tagIndex >= 0) {
    _.pullAt(resource.tags, tagIndex)
    return resourcesService.patch(resource._id.toString(), {
      tags: resource.tags
    }, {
      user: params.user,
      // Forward query so that any update param could be processed as usual on resource
      // Delete own parameters from query otherwise it will be used to filter items
      query: _.omit(query, ['resource', 'resourcesService'])
    })
    .then(subject => {
      debug('Tag ' + tag.value + ' unset on resource ' + resource._id.toString() + ' with scope ' + tag.scope)
      return hook
    })
  } else {
    return Promise.resolve(hook)
  }
}
<commit_msg>Fixed tag tests<commit_after>import _ from 'lodash'
import { BadRequest } from 'feathers-errors'
import { getItems } from 'feathers-hooks-common'
import { populateObject } from './hooks.query'
import makeDebug from 'debug'

const debug = makeDebug('kalisio:kCore:tags:hooks')

export function isTagEqual (tag1, tag2) {
  let equal = (tag1.value === tag2.value && tag1.scope === tag2.scope)
  // when context is provided use it as well
  if (tag1.context && tag2.context) {
    equal = equal && (tag1.context.toString() === tag2.context.toString())
  }
  return equal
}

export function populateTagResource (hook) {
  if (hook.type !== 'before') {
    throw new Error(`The 'populateTagResource' hook should only be used as a 'before' hook.`)
  }

  // Avoid populating any target resource when resource parameters are not present
  return populateObject({ serviceField: 'resourcesService', idField: 'resource', throwOnNotFound: false })(hook)
}

export async function updateTags (hook) {
  let item = getItems(hook)
  if (!item.tags) {
    debug('No tags to update for object ', item)
    return Promise.resolve(hook)
  }
  // Tag service is contextual, look for context on initiator service
  const context = hook.service.context
  // Retrieve previous version of the item
  let previousTags = _.get(hook.params, 'previousItem.tags')
  if (previousTags) {
    // Find common tags
    const commonTags = _.intersectionWith(item.tags, previousTags, isTagEqual)
    // Clear removed tags
    const removedTags = _.differenceWith(previousTags, commonTags, isTagEqual)
    debug('Removing tags for object ', item, removedTags)
    const removePromises = removedTags.map(tag => {
      // When a contextual service is used we might not provide the context in tag, extract from service instead
      const tagService = hook.app.getService('tags', tag.context || context)
      if (!tagService) return Promise.reject(new Error('No valid context found to retrieve tag service for ', tag))
      else return tagService.remove(null, { query: tag })
    })
    // And add new ones
    const addedTags = _.differenceWith(item.tags, commonTags, isTagEqual)
    debug('Adding tags for object ', item, addedTags)
    const addedPromises = addedTags.map(tag => {
      // When a contextual service is used we might not provide the context in tag, extract from service instead
      const tagService = hook.app.getService('tags', tag.context || context)
      if (!tagService) return Promise.reject(new Error('No valid context found to retrieve tag service for ', tag))
      else return tagService.create(tag)
    })
    let [ oldTags, newTags ] = await Promise.all([
      Promise.all(removePromises),
      Promise.all(addedPromises)
    ])
    debug('Tags removed/added', oldTags, newTags)
    // Update tags to include information added when they are created (eg _id)
    // and add also context because tags might come from different ones on the same target object
    newTags = newTags.map(tag => {
      if (tag.context) return tag
      else return Object.assign({ context: (typeof context === 'object' ? context._id : context) }, tag)
    })
    item.tags = commonTags.concat(newTags)
  } else {
    if (hook.method !== 'remove') {
      // Add new tags
      debug('Adding tags for object ', item)
      const addPromises = item.tags.map(tag => {
        // When a contextual service is used we might not provide the context in tag, extract from service instead
        const tagService = hook.app.getService('tags', tag.context || context)
        if (!tagService) return Promise.reject(new Error('No valid context found to retrieve tag service for ', tag))
        else return tagService.create(tag)
      })
      // Update tags to include information added when they are created (eg _id)
      let newTags = await Promise.all(addPromises)
      // and add also context because tags might come from different ones on the same target object
      newTags = newTags.map(tag => {
        if (tag.context) return tag
        else return Object.assign({ context: (typeof context === 'object' ? context._id : context) }, tag)
      })
      item.tags = newTags
    } else {
      debug('Removing tags for object ', item)
      const removePromises = item.tags.map(tag => {
        // When a contextual service is used we might not provide the context in tag, extract from service instead
        const tagService = hook.app.getService('tags', tag.context || context)
        if (!tagService) return Promise.reject(new Error('No valid context found to retrieve tag service for ', tag))
        else return tagService.remove(null, { query: tag })
      })
      await Promise.all(removePromises)
    }
  }
  // Avoid transferring some internal data
  // item.tags = item.tags.map(tag => _.omit(tag, ['count']))

  return hook
}

export function addTagIfNew (hook) {
  if (hook.type !== 'before') {
    throw new Error(`The 'addTagIfNew' hook should only be used as a 'before' hook.`)
  }
  const tagService = hook.service
  const value = _.get(hook, 'data.value')
  const scope = _.get(hook, 'data.scope')
  if (!value || !scope) {
    throw new BadRequest('Scope and value should be provided to create a tag')
  }

  return tagService.find({ query: { value, scope } })
  .then(result => {
    // If it already exist avoid creating it in DB,
    // simply update counter and return it
    if (result.total > 0) {
      let tag = result.data[0]
      hook.result = tag
      tag.count += 1
      debug('Increasing tag ' + tag.value + ' count (' + tag.count + ') with scope ' + tag.scope)
      return tagService.patch(tag._id.toString(), { count: tag.count })
    } else {
      // Otherwise initialize tag counter
      hook.data.count = 1
      return Promise.resolve(hook)
    }
  })
  .then(() => {
    return hook
  })
}

export function removeTagIfUnused (hook) {
  if (hook.type !== 'before') {
    throw new Error(`The 'removeTagIfUnused' hook should only be used as a 'before' hook.`)
  }

  const tagService = hook.service
  const value = _.get(hook.params, 'query.value')
  const scope = _.get(hook.params, 'query.scope')
  if (!value || !scope) {
    throw new BadRequest('Scope and value should be provided to remove a tag')
  }

  return tagService.find({ query: { value, scope } })
  .then(result => {
    // If it already exist decrease counter and erase it if not used anymore
    if (result.total > 0) {
      let tag = result.data[0]
      hook.result = tag
      tag.count -= 1
      if (tag.count <= 0) {
        debug('Removing unused tag ' + tag.value + ' with scope ' + tag.scope)
        return tagService.remove(tag._id.toString())
      } else {
        debug('Decreasing tag ' + tag.value + ' count (' + tag.count + ') with scope ' + tag.scope)
        return tagService.patch(tag._id.toString(), { count: tag.count })
      }
    } else {
      // Should not be possible, this will skip DB call
      hook.result = null
      return Promise.resolve(hook)
    }
  })
  .then(() => {
    return hook
  })
}

export function tagResource (hook) {
  if (hook.type !== 'after') {
    throw new Error(`The 'tagResource' hook should only be used as a 'after' hook.`)
  }
  const tag = hook.result
  const params = hook.params
  const query = params.query
  const context = hook.service.context
  const resourcesService = params.resourcesService
  let resource = params.resource
  // If not already tagged
  if (!_.find(resource.tags, resourceTag => isTagEqual(resourceTag, tag))) {
    // Initialize on first tag
    if (!resource.tags) {
      resource.tags = []
    }
    // Add context because tags might come from different ones on the same target object
    if (context) {
      tag.context = (typeof context === 'object' ? context._id : context)
    }
    resource.tags.push(tag)
    return resourcesService.patch(resource._id.toString(), {
      tags: resource.tags
    }, {
      user: hook.params.user,
      // Forward query so that any update param could be processed as usual on resource
      // Delete own parameters from query otherwise it will be used to filter items
      query: _.omit(query, ['resource', 'resourcesService', 'scope', 'value', 'context'])
    })
    .then(subject => {
      debug('Tag ' + tag.value + ' set on resource ' + resource._id.toString() + ' with scope ' + tag.scope)
      return hook
    })
  } else {
    return Promise.resolve(hook)
  }
}

export function untagResource (hook) {
  if (hook.type !== 'after') {
    throw new Error(`The 'untagResource' hook should only be used as a 'after' hook.`)
  }

  const tag = hook.result
  const params = hook.params
  const query = params.query
  const resourcesService = params.resourcesService
  let resource = params.resource
  // If already tagged
  const tagIndex = _.findIndex(resource.tags, resourceTag => isTagEqual(resourceTag, tag))
  if (tagIndex >= 0) {
    _.pullAt(resource.tags, tagIndex)
    return resourcesService.patch(resource._id.toString(), {
      tags: resource.tags
    }, {
      user: params.user,
      // Forward query so that any update param could be processed as usual on resource
      // Delete own parameters from query otherwise it will be used to filter items
      query: _.omit(query, ['resource', 'resourcesService', 'scope', 'value', 'context'])
    })
    .then(subject => {
      debug('Tag ' + tag.value + ' unset on resource ' + resource._id.toString() + ' with scope ' + tag.scope)
      return hook
    })
  } else {
    return Promise.resolve(hook)
  }
}
<|endoftext|>


<commit_before>const Color = {
  primary: '#202A44',

  faded: '#CCC',

  positive: '#A1D884',
  warning: '#FC5A5D',

  background1: '#9AD1DC',
  background2: '#FFFFFF',
}

module.exports = Color<commit_msg>adding the faded colors from the screen mockups<commit_after>const Color = {
  primary: '#202A44',

  faded: '#CCC',

  positive: '#A1D884',
  warning: '#FC5A5D',

  background1: '#9AD1DC',
  background2: '#FFFFFF',

  fadedRed: '#FEABAB',
  fadedGreen: '#BDE3A7',
}

module.exports = Color
<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

var rules = require('./rules')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

slapp.message('set', ['mention', 'direct_message'], (msg) => {
  let id = 'test_id'
  let state = {
    foo: 'bar'
  }
  slapp.set(id, state, () => {
    //error callback
  })
  msg.say('test_id set')
})

slapp.message('start', ['mention', 'direct_message'], (msg) => {
  msg.say(rules.start_text)
})

slapp.message('^read (.*)', ['mention', 'direct_message'], (msg, text, entry ) => {
  var resp = ''
  switch(entry) {
    case 'r1':
      resp = rules.r1_text
      break;
    case 'r2':
      resp = rules.r2_text
      break;
    default:
      resp = 'Entry ' + entry + ' not found'
  }

  msg.say(resp)
})

// var HELP_TEXT = `
// I will respond to the following messages:
// \`help\` - to see this message.
// \`hi\` - to demonstrate a conversation that tracks state.
// \`thanks\` - to demonstrate a simple response.
// \`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
// \`attachment\` - to see a Slack attachment message.
// `

// //*********************************************
// // Setup different handlers for messages
// //*********************************************

// // response to the user typing "help"
// slapp.message('help', ['mention', 'direct_message'], (msg) => {
//   msg.say(HELP_TEXT)
// })

// // "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
// slapp
//   .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
//     msg
//       .say(`${text}, how are you?`)
//       // sends next event from user to this route, passing along state
//       .route('how-are-you', { greeting: text })
//   })
//   .route('how-are-you', (msg, state) => {
//     var text = (msg.body.event && msg.body.event.text) || ''

//     // user may not have typed text as their next action, ask again and re-route
//     if (!text) {
//       return msg
//         .say("Whoops, I'm still waiting to hear how you're doing.")
//         .say('How are you?')
//         .route('how-are-you', state)
//     }

//     // add their response to state
//     state.status = text

//     msg
//       .say(`Ok then. What's your favorite color?`)
//       .route('color', state)
//   })
//   .route('color', (msg, state) => {
//     var text = (msg.body.event && msg.body.event.text) || ''

//     // user may not have typed text as their next action, ask again and re-route
//     if (!text) {
//       return msg
//         .say("I'm eagerly awaiting to hear your favorite color.")
//         .route('color', state)
//     }

//     // add their response to state
//     state.color = text

//     msg
//       .say('Thanks for sharing.')
//       .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
//     // At this point, since we don't route anywhere, the "conversation" is over
//   })

// // Can use a regex as well
// slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
//   // You can provide a list of responses, and a random one will be chosen
//   // You can also include slack emoji in your responses
//   msg.say([
//     "You're welcome :smile:",
//     'You bet',
//     ':+1: Of course',
//     'Anytime :sun_with_face: :full_moon_with_face:'
//   ])
// })

// // demonstrate returning an attachment...
// slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
//   msg.say({
//     text: 'Check out this amazing attachment! :confetti_ball: ',
//     attachments: [{
//       text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
//       title: 'Slapp Library - Open Source',
//       image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
//       title_link: 'https://beepboophq.com/',
//       color: '#7CD197'
//     }]
//   })
// })

// // Catch-all for any other responses not handled above
// slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
//   // respond only 40% of the time
//   if (Math.random() < 0.4) {
//     msg.say([':wave:', ':pray:', ':raised_hands:'])
//   }
// })

// slapp.command('/choose', '(.*)', (msg, choice) => {
//   // `respond` is used for actions or commands and uses the `response_url` provided by the
//   // incoming request from Slack
//   msg.respond(choice)
// })

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>Movong set out of message.<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

var rules = require('./rules')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

  var test_id = 'test_id'
  var test_state = {
    foo: 'bar'
  }
  slapp.convo_store.set(test_id, test_state, () => {
    //error callback
  })

// slapp.message('set', ['mention', 'direct_message'], (msg) => {
//   let id = 'test_id'
//   let state = {
//     foo: 'bar'
//   }
//   slapp.set(id, state, () => {
//     //error callback
//   })
//   msg.say('test_id set')
// })

slapp.message('start', ['mention', 'direct_message'], (msg) => {
  msg.say(rules.start_text)
})

slapp.message('^read (.*)', ['mention', 'direct_message'], (msg, text, entry ) => {
  var resp = ''
  switch(entry) {
    case 'r1':
      resp = rules.r1_text
      break;
    case 'r2':
      resp = rules.r2_text
      break;
    default:
      resp = 'Entry ' + entry + ' not found'
  }

  msg.say(resp)
})

// var HELP_TEXT = `
// I will respond to the following messages:
// \`help\` - to see this message.
// \`hi\` - to demonstrate a conversation that tracks state.
// \`thanks\` - to demonstrate a simple response.
// \`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
// \`attachment\` - to see a Slack attachment message.
// `

// //*********************************************
// // Setup different handlers for messages
// //*********************************************

// // response to the user typing "help"
// slapp.message('help', ['mention', 'direct_message'], (msg) => {
//   msg.say(HELP_TEXT)
// })

// // "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
// slapp
//   .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
//     msg
//       .say(`${text}, how are you?`)
//       // sends next event from user to this route, passing along state
//       .route('how-are-you', { greeting: text })
//   })
//   .route('how-are-you', (msg, state) => {
//     var text = (msg.body.event && msg.body.event.text) || ''

//     // user may not have typed text as their next action, ask again and re-route
//     if (!text) {
//       return msg
//         .say("Whoops, I'm still waiting to hear how you're doing.")
//         .say('How are you?')
//         .route('how-are-you', state)
//     }

//     // add their response to state
//     state.status = text

//     msg
//       .say(`Ok then. What's your favorite color?`)
//       .route('color', state)
//   })
//   .route('color', (msg, state) => {
//     var text = (msg.body.event && msg.body.event.text) || ''

//     // user may not have typed text as their next action, ask again and re-route
//     if (!text) {
//       return msg
//         .say("I'm eagerly awaiting to hear your favorite color.")
//         .route('color', state)
//     }

//     // add their response to state
//     state.color = text

//     msg
//       .say('Thanks for sharing.')
//       .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
//     // At this point, since we don't route anywhere, the "conversation" is over
//   })

// // Can use a regex as well
// slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
//   // You can provide a list of responses, and a random one will be chosen
//   // You can also include slack emoji in your responses
//   msg.say([
//     "You're welcome :smile:",
//     'You bet',
//     ':+1: Of course',
//     'Anytime :sun_with_face: :full_moon_with_face:'
//   ])
// })

// // demonstrate returning an attachment...
// slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
//   msg.say({
//     text: 'Check out this amazing attachment! :confetti_ball: ',
//     attachments: [{
//       text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
//       title: 'Slapp Library - Open Source',
//       image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
//       title_link: 'https://beepboophq.com/',
//       color: '#7CD197'
//     }]
//   })
// })

// // Catch-all for any other responses not handled above
// slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
//   // respond only 40% of the time
//   if (Math.random() < 0.4) {
//     msg.say([':wave:', ':pray:', ':raised_hands:'])
//   }
// })

// slapp.command('/choose', '(.*)', (msg, choice) => {
//   // `respond` is used for actions or commands and uses the `response_url` provided by the
//   // incoming request from Slack
//   msg.respond(choice)
// })

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function<commit_msg>Re-commiting last<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function <|endoftext|>


<commit_before>
jQuery(document).ready(function() {
  for(var i=0,cnt=term_list.length;i<cnt;i++) {
    jQuery('#tag-'+term_list[i]+' .row-actions .delete').remove();
  }
});
<commit_msg>remove term checkbox and label<commit_after>
jQuery(document).ready(function() {
  for(var i=0,cnt=term_list.length;i<cnt;i++) {
    jQuery('#tag-'+term_list[i]+' .row-actions .delete').remove();
    jQuery('#tag-'+term_list[i]+' label').remove();
    jQuery('#tag-'+term_list[i]+' input').remove();
  }
});
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', messa<commit_msg>Fixed a typo<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', messag<|endoftext|>


<commit_before>'use strict';

/* Modules */

var express = require('express')
  , http    = require('http')
  , routes  = require('./routes')
  , db      = require('./models/schema');

/* Configure server */

var app = express();

app.set('port', process.env.PORT || 8888);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('test secret'));
app.use(app.router);
app.use(express.static('public'));
app.use(express.static('controllers'));
app.use(express.favicon('public/img/favicon.ico'));

/* Routes */

app.get('/', function(req, res) {
  res.render('index');
});

app.get('/signup', function(req, res) {
  // Render index until we make the sign up page
  res.render('index');
});

app.post('/login', function(req, res) {
  res.cookie('test', '1', { maxAge: 36000000, signed: true });
  res.render('index', {cookieValid: req.signedCookies.test === '1'});
});

app.get('/logout', function(req, res) {
  req.session = null;
  res.render('index');
});

// JSON endpoint for books
app.get('/books', function(req, res) {
  db.book.find(function(err, books) {
    if (err) { console.log('An error occurred.'); }
    res.json(books);
  });
});

// Handle errors
app.use(function(req, res) {
  res.render('404');
});

/* Start the server */

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

<commit_msg>fix cookie bug<commit_after>'use strict';

/* Modules */

var express = require('express')
  , http    = require('http')
  , routes  = require('./routes')
  , db      = require('./models/schema');

/* Configure server */

var app = express();

app.set('port', process.env.PORT || 8888);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('test secret'));
app.use(app.router);
app.use(express.static('public'));
app.use(express.static('controllers'));
app.use(express.favicon('public/img/favicon.ico'));

/* Routes */

app.get('/', function(req, res) {
  res.render('index', {cookieValid: req.signedCookies.test === '1'});
});

app.get('/signup', function(req, res) {
  // Render index until we make the sign up page
  res.render('index');
});

app.post('/login', function(req, res) {
  res.cookie('test', '1', { maxAge: 36000000, signed: true });
  res.redirect('/');
});

app.get('/logout', function(req, res) {
  req.session = null;
  res.render('index');
});

// JSON endpoint for books
app.get('/books', function(req, res) {
  db.book.find(function(err, books) {
    if (err) { console.log('An error occurred.'); }
    res.json(books);
  });
});

// Handle errors
app.use(function(req, res) {
  res.render('404');
});

/* Start the server */

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

<|endoftext|>