<commit_before>
// Return height/width of an SVG element
function getPosition(obj) {

  var height = obj.height.baseVal.value;
  // For some reason, with a width size of 100%, the value returns 0.
  var width = obj.width.baseVal.value;

  return [height, width];
}

// Takes in a percent and object, and places the object
// at the corresponding location on the window
// E.g: Percent = .5 would result in the object being
// in the center of the screen
function alterPosByPercent(xy_dim, percent, obj) {

  // xy_dim[0] corresponds to window height
  // xy_dim[1] corresponds to width

  var newPos_Y = xy_dim[0]*percent;
  var newPos_X = xy_dim[1]*percent;

  obj.style.cx = newPos_X;
  obj.style.cy = newPos_Y;
}

function initSim() {
  var svg = document.getElementById("cont");
  var sun = document.getElementById("sun");
  var moon = document.getElementById("moon");

  xy_dim = getPosition(svg);

  var sun_percent = .5;
  var moon_percent = .75;

  alterPosByPercent(xy_dim, sun_percent, sun);
  alterPosByPercent(xy_dim, moon_percent, moon);
}

// Jake, this fixes the issue you were seeing where when width was set to 100%
// you were getting a 0 value - this is because the code was executing before that
// svg element was actually rendered/had a width associated with it. This jQuery function
// below, $(document).ready takes a function as an argument and calls it when the document
// is ready, i.e. when that svg has a width associated with it.
//
// Also, it is better practice call your init methods from within your js file than from
// within your HTML, that is why I commented out this call in the HTML file.
$(document).ready(initSim);

// I think now is a good time to start working the view as a "class". This is because the
// view should have some properties associated with it, like the sun/moon objects. Also
// this results in ultimately cleaner code. JavaScript "classes" are actually functions.
// Here we define the View "class". Instances of it can be instantiated like this:
//
//  var view = new View();
//
function View()
{
    // $('#cont') is jQuery shorthand for document.getElementById("cont")
    // but returns an array - that is why we call get(0) on it, this is the same
    // as $('#cont')[0]
    this.window = $('#cont').get(0);
    this.sun    = $('#sun').get(0);
    this.moon   = $('#moon').get(0);
}

// These prototype functions act as methods of the class, i.e. they can be called like this:
//
//  var view = new View();
//  view.init();
//
View.prototype.init = function()
{
    this.position_body_at_percent_coords(this.sun, 50, 50);
    this.position_body_at_percent_coords(this.moon, 50, 50);
}

View.prototype.get_window_size = function()
{
    // This is a dictionary/object and can be accessed as follows:
    //
    //  var w = view.get_window_size().width
    //
    return {
        width:  this.window.width.baseVal.value,
        height: this.window.height.baseVal.value,
    }
}

View.prototype.position_body_at_percent_coords = function(body, x_percent, y_percent)
{
    // Jake please implement
}

<commit_msg>Implemented positioning function for view class<commit_after>function initSim() {
  var view = new View();

  view.init();

}

// Jake, this fixes the issue you were seeing where when width was set to 100%
// you were getting a 0 value - this is because the code was executing before that
// svg element was actually rendered/had a width associated with it. This jQuery function
// below, $(document).ready takes a function as an argument and calls it when the document
// is ready, i.e. when that svg has a width associated with it.
//
// Also, it is better practice call your init methods from within your js file than from
// within your HTML, that is why I commented out this call in the HTML file.
$(document).ready(initSim);

// I think now is a good time to start working the view as a "class". This is because the
// view should have some properties associated with it, like the sun/moon objects. Also
// this results in ultimately cleaner code. JavaScript "classes" are actually functions.
// Here we define the View "class". Instances of it can be instantiated like this:
//
//  var view = new View();
//
function View()
{
    // $('#cont') is jQuery shorthand for document.getElementById("cont")
    // but returns an array - that is why we call get(0) on it, this is the same
    // as $('#cont')[0]
    this.window = $('#cont').get(0);
    this.sun    = $('#sun').get(0);
    this.moon   = $('#moon').get(0);
}

// These prototype functions act as methods of the class, i.e. they can be called like this:
//
//  var view = new View();
//  view.init();
//
View.prototype.init = function()
{
    this.position_body_at_percent_coords(this.sun, 25, 50);
    this.position_body_at_percent_coords(this.moon, 50, 50);
}

View.prototype.get_window_size = function()
{
    // This is a dictionary/object and can be accessed as follows:
    //
    //  var w = view.get_window_size().width
    //
    return {
        width:  this.window.width.baseVal.value,
        height: this.window.height.baseVal.value,
    }
}

View.prototype.position_body_at_percent_coords = function(body, x_percent, y_percent)
{
    // Jake please implement
    body.style.cx = this.get_window_size().width*(x_percent/100);
    body.style.cy = this.get_window_size().height*(y_percent/100);
}
<|endoftext|>


<commit_before>var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var request = require('request')
var path = require('path')
var mime = require('mime')
var google = require('google-images')

// upload attachment to trello
var addAttachment = function (cardId, url, callback) {
  // get base name of the url
  var fileName = path.basename(url)
  // get content type of the url
  var contentType = mime.lookup(url, 'application/octet-stream')

  request.post({
    url: 'https://api.trello.com/1/cards/' + cardId + '/attachments',
    qs: {
      key: process.env.TRELLO_KEY,
      token: process.env.TRELLO_SECRET
    },
    formData: {
      url: url,
      name: fileName,
      mimeType: contentType
    }
  }, callback)
}

// use bodyParser to parse POST body
app.use(bodyParser.json())

// trello calls this in initialization
app.head('/', function (req, res) {
  res.end('hi webhook')
})

// trello calls this when things happened
app.post('/', function (req, res) {
  res.end('hi trello')

  // the datas we want are all in action
  var action = req.body.action
  var type = action.type
  var card = action.data.card

  console.log(action)

  // only deals with these types
  var supportType = ['createCard', 'updateCard', 'createCheckItem']
  // don't to anything if type is not in this array
  if (supportType.indexOf(type) < 0) {
    return
  }

  // use card name or check list item for keyword
  var text
  if (type === 'createCard' || type === 'updateCard') {
    text = card.name
  } else if (type === 'createCheckItem') {
    text = action.data.checkItem.name
  }

  // tokenize the words
  var tokens = text.split(' ')
  if (!tokens || !tokens.length) {
    return
  }

  // get one random word from tokens and append meme as query for google image
  var keyword = tokens[Math.floor(Math.random() * (tokens.length - 1))] + ' meme'
  google.search(keyword, function (err, images) {
    if (err) {
      return
    }

    if (!images || images.length <= 0) {
      return
    }

    // filter out urls without image extensino
    images.filter(function (item) {
      return item.url.indexOf('.png') > -1 || item.url.indexOf('.jpg') > -1 || item.url.indexOf('.jpeg') > -1 || item.url.indexOf('.gif') > -1
    })

    // check length again after filter
    if (images.length <= 0) {
      return
    }

    console.log('[%s] %s %s', keyword, text, images[0].url)

    // add attachment in this card
    addAttachment(card.id, images[0].url, function (err, res, body) {
      if (err) {
        return
      }

      console.log(body)
    })
  })
})
app.listen(process.env.PORT || 5000)
<commit_msg>Use file instead of url for image uploading<commit_after>var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var request = require('request')
var path = require('path')
var mime = require('mime')
var google = require('google-images')

// upload attachment to trello
var addAttachment = function (cardId, url, callback) {
  // get base name of the url
  var fileName = path.basename(url)
  // get content type of the url
  var contentType = mime.lookup(url, 'application/octet-stream')

  request.post({
    url: 'https://api.trello.com/1/cards/' + cardId + '/attachments',
    qs: {
      key: process.env.TRELLO_KEY,
      token: process.env.TRELLO_SECRET
    },
    formData: {
      file: request(url),
      name: fileName,
      mimeType: contentType
    }
  }, callback)
}

// use bodyParser to parse POST body
app.use(bodyParser.json())

// trello calls this in initialization
app.head('/', function (req, res) {
  res.end('hi webhook')
})

// trello calls this when things happened
app.post('/', function (req, res) {
  res.end('hi trello')

  // the datas we want are all in action
  var action = req.body.action
  var type = action.type
  var card = action.data.card

  console.log(action)

  // only deals with these types
  var supportType = ['createCard', 'updateCard', 'createCheckItem']
  // don't to anything if type is not in this array
  if (supportType.indexOf(type) < 0) {
    return
  }

  // use card name or check list item for keyword
  var text
  if (type === 'createCard' || type === 'updateCard') {
    text = card.name
  } else if (type === 'createCheckItem') {
    text = action.data.checkItem.name
  }

  // tokenize the words
  var tokens = text.split(' ')
  if (!tokens || !tokens.length) {
    return
  }

  // get one random word from tokens and append meme as query for google image
  var keyword = tokens[Math.floor(Math.random() * (tokens.length - 1))] + ' meme'
  google.search(keyword, function (err, images) {
    if (err) {
      return
    }

    if (!images || images.length <= 0) {
      return
    }

    // filter out urls without image extensino
    images.filter(function (item) {
      return item.url.indexOf('.png') > -1 || item.url.indexOf('.jpg') > -1 || item.url.indexOf('.jpeg') > -1 || item.url.indexOf('.gif') > -1
    })

    // check length again after filter
    if (images.length <= 0) {
      return
    }

    console.log('[%s] %s %s', keyword, text, images[0].url)

    // add attachment in this card
    addAttachment(card.id, images[0].url, function (err, res, body) {
      if (err) {
        return
      }

      console.log(body)
    })
  })
})
app.listen(process.env.PORT || 5000)
<|endoftext|>


<commit_before>'use strict';

import 'babel-polyfill';
import Aws from 'aws-sdk';
import path from 'path';
import fs from 'fs';
import ulid from 'ulid';

const gm = require('gm').subClass({ imageMagick: true });
const s3 = new Aws.S3();

const downloadImage = (params) => {
  return new Promise((resolve, reject) => {
    const destPath = path.join('/tmp', (new Date()).getTime().toString());
    s3.getObject(params).promise()
      .then(data => {
        fs.writeFileSync(destPath, data.Body);
        return resolve(destPath);
      })
      .catch(err => reject(err));
    });
};

const imageInfo = (imagePath) => {
  return new Promise((resolve, reject) => {
    gm(imagePath)
      .identify((err, info) => {
        return err ? reject(err) : resolve(info);
      });
  });
};

const resizeImage = (imagePath) => {
  return new Promise((resolve, reject) => {
    const resizeOpts = /^(\d+)x(\d+)([%@!<>])?$/g.exec(process.env.RESIZE_OPTION);

    gm(imagePath)
      .resize(resizeOpts[1], resizeOpts[2], resizeOpts[3])
      .toBuffer('png', (err, buffer) => {
        return err ? reject(err) : resolve(buffer);
      });
  });
};

const uploadImage = (buffer, info) => {
  return new Promise((resolve, reject) => {
    const params = {
      Bucket: process.env.DEST_S3_BUCKET_NAME,
      Key: `${process.env.DEST_S3_PREFIX}/${ulid()}.${info.format}`,
      Body: buffer,
      ContentType: info['Mime type'],
    };

    s3.putObject(params, (err, data) => {
      return err ? reject(err) : resolve(data);
    });
  });
};

export const handle = (event, context, callback) => {
  console.log('eventObject: %s', JSON.stringify(event, null, 2));

  const s3Event = event.Records[0].s3;
  const params = {
    Bucket: s3Event.bucket.name,
    Key: s3Event.object.key,
  };

  Promise.resolve()
    .then(() => downloadImage(params))
    .catch((err) => console.log(err));

  callback(null, event);
};
<commit_msg>Use upload instead of `pubObject`<commit_after>'use strict';

import 'babel-polyfill';
import Aws from 'aws-sdk';
import path from 'path';
import fs from 'fs';
import ulid from 'ulid';

const gm = require('gm').subClass({ imageMagick: true });
const s3 = new Aws.S3();

const downloadImage = (params) => {
  return new Promise((resolve, reject) => {
    const destPath = path.join('/tmp', (new Date()).getTime().toString());
    s3.getObject(params).promise()
      .then(data => {
        fs.writeFileSync(destPath, data.Body);
        return resolve(destPath);
      })
      .catch(err => reject(err));
    });
};

const imageInfo = (imagePath) => {
  return new Promise((resolve, reject) => {
    gm(imagePath)
      .identify((err, info) => {
        return err ? reject(err) : resolve(info);
      });
  });
};

const resizeImage = (imagePath) => {
  return new Promise((resolve, reject) => {
    const resizeOpts = /^(\d+)x(\d+)([%@!<>])?$/g.exec(process.env.RESIZE_OPTION);

    gm(imagePath)
      .resize(resizeOpts[1], resizeOpts[2], resizeOpts[3])
      .toBuffer('png', (err, buffer) => {
        return err ? reject(err) : resolve(buffer);
      });
  });
};

const uploadImage = (buffer, info) => {
  return new Promise((resolve, reject) => {
    const params = {
      Bucket: process.env.DEST_S3_BUCKET_NAME,
      Key: `${process.env.DEST_S3_PREFIX}/${ulid()}.${info.format}`,
      Body: buffer,
      ContentType: info['Mime type'],
    };

    s3.upload(params, (err, data) => {
      return err ? reject(err) : resolve(data);
    });
  });
};

export const handle = (event, context, callback) => {
  console.log('eventObject: %s', JSON.stringify(event, null, 2));

  const s3Event = event.Records[0].s3;
  const params = {
    Bucket: s3Event.bucket.name,
    Key: s3Event.object.key,
  };

  Promise.resolve()
    .then(() => downloadImage(params))
    .catch((err) => console.log(err));

  callback(null, event);
};
<|endoftext|>


<commit_before>#!/bin/env node

var
    http = require('http'),
    async= require('async'),
    request = require('request'),
    //inspect = require('eyes').inspector({maxLength:null, stream:null}),
    credentials = require(process.env.OPENSHIFT_DATA_DIR||'./' + 'credentials'),
    QueryStringToJSON= require('tools').QueryStringToJSON;
    ip = process.env.OPENSHIFT_NODEJS_IP||'127.0.0.1',
    port = process.env.OPENSHIFT_NODEJS_PORT||8080,
    data={};

http.createServer(function (req, res) {
    data.incoming="";
    req.on('data', function(d){  data.incoming+=d; })
    req.on('end',function(){
        async.series([
            function(next){
                if (data.incoming=="") next(1);
                data.inc=QueryStringToJSON(data.incoming);
                request.get('http://api.rottentomatoes.com/api/public/v1.0/movies.json?q='+data.inc.text+
                    '&page_limit=1&page=1&apikey='+credentials.rt_token,function(e,r){
                    e&&(data.error=!0,data.errmsg='Error searching movies!');
                    if(r){
                        data.search=JSON.parse(r.body);
                        if (data.search.total&&data.search.total>0) {
                            data.error=!1;
                        } else {
                            data.error=!0;
                            data.errmsg='No movies found!';
                        }
                    }
                    next();
                });
            },
            function(next){
                data.out={};
                if (!data.error)
                request.get('http://api.rottentomatoes.com/api/public/v1.0/movies/'+data.search.movies[0].id+
                    '.json?apikey='++credentials.rt_token,function(e,r){
                    e&&(data.error=!0,data.errmsg='Error retrieving movie details!');
                    if(r){
                        data.movie=JSON.parse(r.body);
                        data.out.channel='#'+data.inc.channel_name;
                        data.out.username=data.movie.title;
                        data.out.text=data.movie.year+'';
                        data.movie.genres&&(data.out.text+=',    ',data.movie.genres.forEach(function(g){data.out.text+=g+', '}));
                        data.movie.runtime&&(data.out.text+='   '+data.movie.runtime+' minutes');
                        data.out.text+='\n';
                        data.out.text+='Critics Score: '
                        data.movie.ratings||(data.movie.ratings={});
                        if (!data.movie.ratings.critics_score||data.movie.ratings.critics_score==-1)
                            data.out.text+='n/a';
                        else
                            data.out.text+=data.movie.ratings.critics_score+'%';
                        data.out.text+=',       Audience Score: '
                        if (!data.movie.ratings.audience_score||data.movie.ratings.audience_score==-1)
                            data.out.text+='n/a';
                        else
                            data.out.text+=data.movie.ratings.audience_score+'%';
                        data.out.text+='\n';
                        data.out.text+='Director(abr.): ';
                        data.movie.abridged_directors&&(data.movie.abridged_directors.forEach(function(d){data.out.text+=d.name+' '}));
                        data.movie.studio&&(data.out.text+='        Studio: '+data.movie.studio);
                        data.out.text+='\n';
                        data.out.text+='Cast(abr.): ';
                        data.movie.abridged_cast&&(data.movie.abridged_cast.forEach(function(c){data.out.text+=c.name+(c.characters?' as '+c.characters[0]:'')+', '}));
                        data.out.text=data.out.text.slice(0,-2)+'\n\n';
                        //data.movie.synopsis&&(data.out.text+=data.movie.synopsis);
                        data.out.text+='For more info go to <'+data.movie.links.alternate+'|the full RT page>';
                        data.movie.alternate_ids&&data.movie.alternate_ids.imdb
                            &&(data.out.text+=' or go to <http://www.imdb.com/title/tt'+data.movie.alternate_ids.imdb+'|this title on IMDB>');
                    }
                    next();
                });
                else next();
            },
            function(next){
                data.error&&(data.out.text=data.errmsg,data.out.channel='#'+data.inc.channel_name,data.out.username='Error');
                data.out.text+='\n\n'+data.inc.user_name+': '+data.inc.command+' '+data.inc.text.split('+').join(' ');
                request.post('https://aem.slack.com/services/hooks/incoming-webhook?token='+credentials.slack_token,{ json: data.out },
                    function(e,r){
                        next();
                    });
            }
            ], function(e) {
                res.writeHead(200, {'Content-Type': 'text/plain'});
                e&&(res.write('no POST'));
                res.end('');
            });
    })
}).listen(port, ip);
console.log('Server running at '+ip+':'+port);

<commit_msg>some fixes<commit_after>#!/bin/env node

var
    http = require('http'),
    async= require('async'),
    request = require('request'),
    //inspect = require('eyes').inspector({maxLength:null, stream:null}),
    credentials = require(process.env.OPENSHIFT_DATA_DIR||'./' + 'credentials'),
    QueryStringToJSON= require('./tools').QueryStringToJSON;
    ip = process.env.OPENSHIFT_NODEJS_IP||'127.0.0.1',
    port = process.env.OPENSHIFT_NODEJS_PORT||8080,
    data={};

http.createServer(function (req, res) {
    data.incoming="";
    req.on('data', function(d){  data.incoming+=d; })
    req.on('end',function(){
        async.series([
            function(next){
                if (data.incoming=="") next(1);
                data.inc=QueryStringToJSON(data.incoming);
                request.get('http://api.rottentomatoes.com/api/public/v1.0/movies.json?q='+data.inc.text+
                    '&page_limit=1&page=1&apikey='+credentials.rt_token,function(e,r){
                    e&&(data.error=!0,data.errmsg='Error searching movies!');
                    if(r){
                        data.search=JSON.parse(r.body);
                        if (data.search.total&&data.search.total>0) {
                            data.error=!1;
                        } else {
                            data.error=!0;
                            data.errmsg='No movies found!';
                        }
                    }
                    next();
                });
            },
            function(next){
                data.out={};
                if (!data.error)
                request.get('http://api.rottentomatoes.com/api/public/v1.0/movies/'+data.search.movies[0].id+
                    '.json?apikey='+credentials.rt_token,function(e,r){
                    e&&(data.error=!0,data.errmsg='Error retrieving movie details!');
                    if(r){
                        data.movie=JSON.parse(r.body);
                        data.out.channel='#'+data.inc.channel_name;
                        data.out.username=data.movie.title;
                        data.out.text=data.movie.year+'';
                        data.movie.genres&&(data.out.text+=',    ',data.movie.genres.forEach(function(g){data.out.text+=g+', '}));
                        data.movie.runtime&&(data.out.text+='   '+data.movie.runtime+' minutes');
                        data.out.text+='\n';
                        data.out.text+='Critics Score: '
                        data.movie.ratings||(data.movie.ratings={});
                        if (!data.movie.ratings.critics_score||data.movie.ratings.critics_score==-1)
                            data.out.text+='n/a';
                        else
                            data.out.text+=data.movie.ratings.critics_score+'%';
                        data.out.text+=',       Audience Score: '
                        if (!data.movie.ratings.audience_score||data.movie.ratings.audience_score==-1)
                            data.out.text+='n/a';
                        else
                            data.out.text+=data.movie.ratings.audience_score+'%';
                        data.out.text+='\n';
                        data.out.text+='Director(abr.): ';
                        data.movie.abridged_directors&&(data.movie.abridged_directors.forEach(function(d){data.out.text+=d.name+' '}));
                        data.movie.studio&&(data.out.text+='        Studio: '+data.movie.studio);
                        data.out.text+='\n';
                        data.out.text+='Cast(abr.): ';
                        data.movie.abridged_cast&&(data.movie.abridged_cast.forEach(function(c){data.out.text+=c.name+(c.characters?' as '+c.characters[0]:'')+', '}));
                        data.out.text=data.out.text.slice(0,-2)+'\n\n';
                        //data.movie.synopsis&&(data.out.text+=data.movie.synopsis);
                        data.out.text+='For more info go to <'+data.movie.links.alternate+'|the full RT page>';
                        data.movie.alternate_ids&&data.movie.alternate_ids.imdb
                            &&(data.out.text+=' or go to <http://www.imdb.com/title/tt'+data.movie.alternate_ids.imdb+'|this title on IMDB>');
                    }
                    next();
                });
                else next();
            },
            function(next){
                data.error&&(data.out.text=data.errmsg,data.out.channel='#'+data.inc.channel_name,data.out.username='Error');
                data.out.text+='\n\n'+data.inc.user_name+': '+data.inc.command+' '+data.inc.text.split('+').join(' ');
                request.post('https://aem.slack.com/services/hooks/incoming-webhook?token='+credentials.slack_token,{ json: data.out },
                    function(e,r){
                        next();
                    });
            }
            ], function(e) {
                res.writeHead(200, {'Content-Type': 'text/plain'});
                e&&(res.write('no POST'));
                res.end('');
            });
    })
}).listen(port, ip);
console.log('Server running at '+ip+':'+port);

<|endoftext|>


<commit_before>/**
Copyright 2012 Google Inc.

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.

Author: Renato Mangini (mangini@chromium.org)
Author: Luis Leao (luisleao@gmail.com)
Author: Gordon Williams (gw@pur3.co.uk)
**/

(function() {
  if (chrome.serial.getDevices===undefined) {
    // wrong chrome version
    console.log("Chrome does NOT have post-M33 serial API");
    return;
  }

  var connectionInfo;
  var readListener;
  var connectedPort; // unused?
  var connectionDisconnectCallback;

  // For throttled write
  var slowWrite = true;
  var writeData = undefined;
  var writeInterval = undefined;

  var startListening=function(callback) {
    var oldListener = readListener;
    readListener = callback;
    return oldListener;
  };

  var getPorts=function(callback) {
    chrome.serial.getDevices(function(devices) {
      callback(devices.map(function(device) {
        return device.path;
      }));
    });
  };

  var openSerial=function(serialPort, openCallback, disconnectCallback) {
    connectionDisconnectCallback = disconnectCallback;
    chrome.serial.connect(serialPort, {bitrate: 9600},
      function(cInfo) {
        if (!cInfo) {
          console.log("Unable to open device (connectionInfo="+cInfo+")");
          openCallback(undefined);
        } else {
          connectionInfo = cInfo;
          connectedPort = serialPort;
          console.log(cInfo);
          Espruino.callProcessor("connected", undefined, function() {
            openCallback(cInfo);
          });
        }
    });
  };

  var writeSerialDirect = function(str) {
    chrome.serial.send(connectionInfo.connectionId, str2ab(str), function() {});
  };

  var str2ab=function(str) {
    var buf=new ArrayBuffer(str.length);
    var bufView=new Uint8Array(buf);
    for (var i=0; i<str.length; i++) {
      bufView[i]=str.charCodeAt(i);
    }
    return buf;
  };

  var closeSerial=function(callback) {
   if (writeInterval!==undefined)
     clearInterval(writeInterval);
   writeInterval = undefined;
   writeData = undefined;

   connectionDisconnectCallback = undefined;
   if (connectionInfo) {
     chrome.serial.disconnect(connectionInfo.connectionId,
      function(result) {
        connectionInfo=null;
        Espruino.callProcessor("disconnected");
        if (callback) callback(result);
      });
    }
  };

  var isConnected = function() {
    return connectionInfo!=null && connectionInfo.connectionId>=0;
  };

  // Throttled serial write
  var writeSerial = function(data, showStatus) {
    if (!isConnected()) return; // throw data away
    if (showStatus===undefined) showStatus=true;

    /*var d = [];
    for (var i=0;i<data.length;i++) d.push(data.charCodeAt(i));
    console.log("Write "+data.length+" bytes - "+JSON.stringify(d));*/

    /* Here we queue data up to write out. We do this slowly because somehow
    characters get lost otherwise (compared to if we used other terminal apps
    like minicom) */
    if (writeData == undefined)
      writeData = data;
    else
      writeData += data;

    var blockSize = slowWrite ? 30 : 512; // not sure how, but v33 serial API seems to lose stuff if we don't sent it at once

    showStatus &= writeData.length>blockSize;
    if (showStatus) {
      //Espruino.Core.Status.setStatus("Sending...", writeData.length);
      console.log("Sending "+JSON.stringify(data));
    }

    if (writeInterval===undefined) {
      function sender() {
        if (writeData!=undefined) {
          var d = undefined;
          if (writeData.length>blockSize) {
            d = writeData.substr(0,blockSize);
            writeData = writeData.substr(blockSize);
          } else {
            d = writeData;
            writeData = undefined;
          }
          writeSerialDirect(d);
          if (showStatus)
            Espruino.Core.Status.incrementProgress(d.length);
        }
        if (writeData==undefined && writeInterval!=undefined) {
          clearInterval(writeInterval);
          writeInterval = undefined;
          if (showStatus)
            Espruino.Core.Status.setStatus("Sent");
        }
      }
      sender(); // send data instantly
      // if there was any more left, do it after a delay
      if (writeData!=undefined) {
        writeInterval = setInterval(sender, 100);
      } else {
        if (showStatus)
          Espruino.Core.Status.setStatus("Sent");
      }
    }
  };

  // ----------------------------------------------------------
  chrome.serial.onReceive.addListener(function(receiveInfo) {
    //var bytes = new Uint8Array(receiveInfo.data);
    if (readListener!==undefined) readListener(receiveInfo.data);
  });

  chrome.serial.onReceiveError.addListener(function(errorInfo) {
    console.log("RECEIVE ERROR:",JSON.stringify(errorInfo));
    connectionDisconnectCallback();
  });

  Espruino.Core.Serial = {
    "getPorts": getPorts,
    "open": openSerial,
    "isConnected": isConnected,
    "startListening": startListening,
    "write": writeSerial,
    "close": closeSerial,
	"isSlowWrite": function() { return slowWrite; },
	"setSlowWrite": function(isOn) {
          if (Espruino.Config.SERIAL_THROTTLE_SEND) {
            console.log("ForceThrottle option is set - set Slow Write = true");
            isOn = true;
          } else
  	    console.log("Set Slow Write = "+isOn);
	  slowWrite = isOn;
	},
  };
})();
<commit_msg>Fix #68 - that was easy<commit_after>/**
Copyright 2012 Google Inc.

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.

Author: Renato Mangini (mangini@chromium.org)
Author: Luis Leao (luisleao@gmail.com)
Author: Gordon Williams (gw@pur3.co.uk)
**/

(function() {
  if (chrome.serial.getDevices===undefined) {
    // wrong chrome version
    console.log("Chrome does NOT have post-M33 serial API");
    return;
  }

  var connectionInfo;
  var readListener;
  var connectedPort; // unused?
  var connectionDisconnectCallback;

  // For throttled write
  var slowWrite = true;
  var writeData = undefined;
  var writeInterval = undefined;

  var startListening=function(callback) {
    var oldListener = readListener;
    readListener = callback;
    return oldListener;
  };

  var getPorts=function(callback) {
    chrome.serial.getDevices(function(devices) {
      callback(devices.map(function(device) {
        return device.path;
      }));
    });
  };

  var openSerial=function(serialPort, openCallback, disconnectCallback) {
    connectionDisconnectCallback = disconnectCallback;
    chrome.serial.connect(serialPort, {bitrate: 9600},
      function(cInfo) {
        if (!cInfo) {
          console.log("Unable to open device (connectionInfo="+cInfo+")");
          openCallback(undefined);
        } else {
          connectionInfo = cInfo;
          connectedPort = serialPort;
          console.log(cInfo);
          Espruino.callProcessor("connected", undefined, function() {
            openCallback(cInfo);
          });
        }
    });
  };

  var writeSerialDirect = function(str) {
    chrome.serial.send(connectionInfo.connectionId, str2ab(str), function() {});
  };

  var str2ab=function(str) {
    var buf=new ArrayBuffer(str.length);
    var bufView=new Uint8Array(buf);
    for (var i=0; i<str.length; i++) {
      bufView[i]=str.charCodeAt(i);
    }
    return buf;
  };

  var closeSerial=function(callback) {
   if (writeInterval!==undefined)
     clearInterval(writeInterval);
   writeInterval = undefined;
   writeData = undefined;

   connectionDisconnectCallback = undefined;
   if (connectionInfo) {
     chrome.serial.disconnect(connectionInfo.connectionId,
      function(result) {
        connectionInfo=null;
        Espruino.callProcessor("disconnected");
        if (callback) callback(result);
      });
    }
  };

  var isConnected = function() {
    return connectionInfo!=null && connectionInfo.connectionId>=0;
  };

  // Throttled serial write
  var writeSerial = function(data, showStatus) {
    if (!isConnected()) return; // throw data away
    if (showStatus===undefined) showStatus=true;

    /*var d = [];
    for (var i=0;i<data.length;i++) d.push(data.charCodeAt(i));
    console.log("Write "+data.length+" bytes - "+JSON.stringify(d));*/

    /* Here we queue data up to write out. We do this slowly because somehow
    characters get lost otherwise (compared to if we used other terminal apps
    like minicom) */
    if (writeData == undefined)
      writeData = data;
    else
      writeData += data;

    var blockSize = slowWrite ? 30 : 512; // not sure how, but v33 serial API seems to lose stuff if we don't sent it at once

    showStatus &= writeData.length>blockSize;
    if (showStatus) {
      Espruino.Core.Status.setStatus("Sending...", writeData.length);
      console.log("Sending "+JSON.stringify(data));
    }

    if (writeInterval===undefined) {
      function sender() {
        if (writeData!=undefined) {
          var d = undefined;
          if (writeData.length>blockSize) {
            d = writeData.substr(0,blockSize);
            writeData = writeData.substr(blockSize);
          } else {
            d = writeData;
            writeData = undefined;
          }
          writeSerialDirect(d);
          if (showStatus)
            Espruino.Core.Status.incrementProgress(d.length);
        }
        if (writeData==undefined && writeInterval!=undefined) {
          clearInterval(writeInterval);
          writeInterval = undefined;
          if (showStatus)
            Espruino.Core.Status.setStatus("Sent");
        }
      }
      sender(); // send data instantly
      // if there was any more left, do it after a delay
      if (writeData!=undefined) {
        writeInterval = setInterval(sender, 100);
      } else {
        if (showStatus)
          Espruino.Core.Status.setStatus("Sent");
      }
    }
  };

  // ----------------------------------------------------------
  chrome.serial.onReceive.addListener(function(receiveInfo) {
    //var bytes = new Uint8Array(receiveInfo.data);
    if (readListener!==undefined) readListener(receiveInfo.data);
  });

  chrome.serial.onReceiveError.addListener(function(errorInfo) {
    console.log("RECEIVE ERROR:",JSON.stringify(errorInfo));
    connectionDisconnectCallback();
  });

  Espruino.Core.Serial = {
    "getPorts": getPorts,
    "open": openSerial,
    "isConnected": isConnected,
    "startListening": startListening,
    "write": writeSerial,
    "close": closeSerial,
	"isSlowWrite": function() { return slowWrite; },
	"setSlowWrite": function(isOn) {
          if (Espruino.Config.SERIAL_THROTTLE_SEND) {
            console.log("ForceThrottle option is set - set Slow Write = true");
            isOn = true;
          } else
  	    console.log("Set Slow Write = "+isOn);
	  slowWrite = isOn;
	},
  };
})();
<|endoftext|>


<commit_before>import { exec } from 'child_process'
import input from 'inquirer'
import anidb from './api/anidb'
import animeplanet from './api/animeplanet'
import anilist from './api/anilist'
import annict from './api/annict'
import kitsu from './api/kitsu'
import myanimelist from './api/myanimelist'
import { version } from './package'
import { log } from './util'

exec(`git log -1 --format="Tracker Killer ${version}%nUpdated %ar (%h by %an)`, (err, response) => {
  log(response)
  if (err) log(err)
  prompt()
})

function prompt () {
  input.prompt([
    {
      type: 'checkbox',
      name: 'service',
      message: 'Select services:',
      choices: [
        {
          name: 'AniDB',
          disabled: 'not implemented'
        },
        'AniList',
        {
          name: 'AnimePlanet',
          disabled: 'no api'
        },
        'Annict',
        'Kitsu',
        'MyAnimeList'
      ],
      validate: answer => {
        if (answer.length < 1) {
          return 'Pick at least one'
        }
        return true
      }
    },
    {
      type: 'checkbox',
      name: 'type',
      message: 'Select library types:',
      choices: [
        'Anime',
        'Manga'
      ],
      validate: answer => {
        if (answer.length < 1) {
          return 'Pick at least one'
        }
        return true
      }
    }
  ])
  .then(answer => {
    answer.service.forEach(service => {
      switch (service) {
        case ('AniDB'):
          answer.type.forEach(type => {
            anidb(service, type)
          })
          break
        case ('AniList'):
          answer.type.forEach(type => {
            anilist(service, type)
          })
          break
        case ('AnimePlanet'):
          answer.type.forEach(type => {
            animeplanet(service, type)
          })
          break
        case ('Annict'):
          answer.type.forEach(type => {
            annict(service, type)
          })
          break
        case ('Kitsu'):
          answer.type.forEach(type => {
            kitsu(service, type)
          })
          break
        case ('MyAnimeList'):
          answer.type.forEach(type => {
            myanimelist(service, type)
          })
          break
      }
    })
  })
}
<commit_msg>chore: disable services not fully implemented<commit_after>import { exec } from 'child_process'
import input from 'inquirer'
import anidb from './api/anidb'
import animeplanet from './api/animeplanet'
import anilist from './api/anilist'
import annict from './api/annict'
import kitsu from './api/kitsu'
import myanimelist from './api/myanimelist'
import { version } from './package'
import { log } from './util'

exec(`git log -1 --format="Tracker Killer ${version}%nUpdated %ar (%h by %an)`, (err, response) => {
  log(response)
  if (err) log(err)
  prompt()
})

function prompt () {
  input.prompt([
    {
      type: 'checkbox',
      name: 'service',
      message: 'Select services:',
      choices: [
        {
          name: 'AniDB',
          disabled: 'not implemented'
        },
        {
          name: 'AniList',
          disabled: 'not implemented'
        },
        {
          name: 'AnimePlanet',
          disabled: 'no api'
        },
        {
          name: 'Annict',
          disabled: 'not implemented'
        },
        'Kitsu',
        'MyAnimeList'
      ],
      validate: answer => {
        if (answer.length < 1) {
          return 'Pick at least one'
        }
        return true
      }
    },
    {
      type: 'checkbox',
      name: 'type',
      message: 'Select library types:',
      choices: [
        'Anime',
        'Manga'
      ],
      validate: answer => {
        if (answer.length < 1) {
          return 'Pick at least one'
        }
        return true
      }
    }
  ])
  .then(answer => {
    answer.service.forEach(service => {
      switch (service) {
        case ('AniDB'):
          answer.type.forEach(type => {
            anidb(service, type)
          })
          break
        case ('AniList'):
          answer.type.forEach(type => {
            anilist(service, type)
          })
          break
        case ('AnimePlanet'):
          answer.type.forEach(type => {
            animeplanet(service, type)
          })
          break
        case ('Annict'):
          answer.type.forEach(type => {
            annict(service, type)
          })
          break
        case ('Kitsu'):
          answer.type.forEach(type => {
            kitsu(service, type)
          })
          break
        case ('MyAnimeList'):
          answer.type.forEach(type => {
            myanimelist(service, type)
          })
          break
      }
    })
  })
}
<|endoftext|>


<commit_before>const Discord = require('discord.js');
module.exports = member => {
const modlog = member.guild.channels.find('name', 'pie-log');
const muteRole = member.guild.roles.find("name","SendMessage")
  //${member.user.username}
const embed = new Discord.RichEmbed()
  .setTimestamp()
  .setColor(0xffff00)
  .setTitle("User Joined")
  .setThumbnail(`${member.user.avatarURL}`)
  .setDescription(`\n`)
  .addField("Username:",`${member.user.username} (${member.user})`,true)
  .addField("Role Added:",`SendMessage`,false)
  .setFooter(`User: ${member.user.username}`,`${member.user.avatarURL}`);

member.guild.member(member.user).addRole(muteRole)
member.guild.channels.get(modlog.id).send({embed}).catch(console.error);

     member.user.sendMessage({embed: {
    color: 0xff0000,
    title: "Welcome to Opitimal Bureau discord!",
    description: ("\n\n:flag_sg: Welcome to the **𝔒𝔭𝔦𝔱𝔦𝔪𝔞𝔩 𝔅𝔲𝔯𝔢𝔞𝔲** discord! :flag_sg:"),
    fields:[{
      name: "A safe discord for everyone:",
      value: `Please follow the rules and regulations of discord and the server. Rules can be found under #rules.`,
      inline: true
    },{
      name: "Welcome to **𝔒𝔭𝔦𝔱𝔦𝔪𝔞𝔩 𝔅𝔲𝔯𝔢𝔞𝔲** discord once again!",
      value: `Have a great time here! :)`,
      inline: false
    }]
      }})

                             }
<commit_msg>Update guildMemberAdd.js<commit_after>const Discord = require('discord.js');
module.exports = member => {
const modlog = member.guild.channels.find('name', 'pie-log');
const muteRole = member.guild.roles.find("name","SendMessage")
  //${member.user.username}
member.guild.member(member.user).addRole(muteRole)

                             }
<|endoftext|>


<commit_before>/**
  @module ember-orbit
*/

import RecordArray from './record_arrays/record_array';
import FilteredRecordArray from './record_arrays/filtered_record_array';

var get = Ember.get,
    set = Ember.set;

var forEach = Ember.EnumerableUtils.forEach;

/**
  @class RecordArrayManager
  @namespace EO
  @private
  @extends Ember.Object
*/
var RecordArrayManager = Ember.Object.extend({
  init: function() {
    this.filteredRecordArrays = Ember.MapWithDefault.create({
      defaultValue: function() { return []; }
    });

    this.changedRecords = [];
  },

  recordDidChange: function(record) {
    if (this.changedRecords.push(record) !== 1) { return; }

    Ember.run.schedule('actions', this, this.updateRecordArrays);
  },

  recordArraysForRecord: function(record) {
    record._recordArrays = record._recordArrays || Ember.OrderedSet.create();
    return record._recordArrays;
  },

  /**
    This method is invoked whenever data is changed in the context.

    It updates all record arrays that a record belongs to.

    To avoid thrashing, it only runs at most once per run loop.

    @method updateRecordArrays
    @param {Class} type
    @param {Number|String} clientId
  */
  updateRecordArrays: function() {
    forEach(this.changedRecords, function(record) {
      if (get(record, 'isDeleted')) {
        this._recordWasDeleted(record);
      } else {
        this._recordWasChanged(record);
      }
    }, this);

    this.changedRecords.length = 0;
  },

  _recordWasDeleted: function (record) {
    var recordArrays = record._recordArrays;

    if (!recordArrays) { return; }

    forEach(recordArrays, function(array) {
      array.removeRecord(record);
    });

    this.context.unload(record);
  },

  _recordWasChanged: function (record) {
    var type = record.constructor.typeKey,
        recordArrays = this.filteredRecordArrays.get(type),
        filter;

    forEach(recordArrays, function(array) {
      filter = get(array, 'filterFunction');
      this.updateRecordArray(array, filter, type, record);
    }, this);
  },

  /**
    Update an individual filter.

    @method updateRecordArray
    @param {EO.FilteredRecordArray} array
    @param {Function} filter
    @param {Class} type
    @param {Number|String} clientId
  */
  updateRecordArray: function(array, filter, type, record) {
    var shouldBeInArray;

    if (!filter) {
      shouldBeInArray = true;
    } else {
      shouldBeInArray = filter(record);
    }

    var recordArrays = this.recordArraysForRecord(record);

    if (shouldBeInArray) {
      recordArrays.add(array);
      array.addRecord(record);
    } else if (!shouldBeInArray) {
      recordArrays.remove(array);
      array.removeRecord(record);
    }
  },

  /**
    This method is invoked if the `filterFunction` property is
    changed on a `EO.FilteredRecordArray`.

    It essentially re-runs the filter from scratch. This same
    method is invoked when the filter is created in th first place.

    @method updateFilter
    @param array
    @param type
    @param filter
  */
  updateFilter: function(array, type, filter) {
    var records = this.context.retrieve(type),
        record;

    for (var i=0, l=records.length; i<l; i++) {
      record = records[i];

      if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) {
        this.updateRecordArray(array, filter, type, record);
      }
    }
  },

  /**
    Create a `EO.RecordArray` for a type and register it for updates.

    @method createRecordArray
    @param {Class} type
    @return {EO.RecordArray}
  */
  createRecordArray: function(type) {
    var array = RecordArray.create({
      type: type,
      content: Ember.A(),
      context: this.context
    });

    this.registerFilteredRecordArray(array, type);

    return array;
  },

  /**
    Create a `EO.FilteredRecordArray` for a type and register it for updates.

    @method createFilteredRecordArray
    @param {Class} type
    @param {Function} filter
    @param {Object} query (optional
    @return {EO.FilteredRecordArray}
  */
  createFilteredRecordArray: function(type, filter, query) {
    var array = FilteredRecordArray.create({
      query: query,
      type: type,
      content: Ember.A(),
      context: this.context,
      manager: this,
      filterFunction: filter
    });

    this.registerFilteredRecordArray(array, type, filter);

    return array;
  },

  /**
    Register a RecordArray for a given type to be backed by
    a filter function. This will cause the array to update
    automatically when records of that type change attribute
    values or states.

    @method registerFilteredRecordArray
    @param {EO.RecordArray} array
    @param {Class} type
    @param {Function} filter
  */
  registerFilteredRecordArray: function(array, type, filter) {
    var recordArrays = this.filteredRecordArrays.get(type);
    recordArrays.push(array);

    this.updateFilter(array, type, filter);
  },

  // Internally, we maintain a map of all unloaded IDs requested by
  // a ManyArray. As the adapter loads data into the context, the
  // context notifies any interested ManyArrays. When the ManyArray's
  // total number of loading records drops to zero, it becomes
  // `isLoaded` and fires a `didLoad` event.
  registerWaitingRecordArray: function(record, array) {
    var loadingRecordArrays = record._loadingRecordArrays || [];
    loadingRecordArrays.push(array);
    record._loadingRecordArrays = loadingRecordArrays;
  },

  willDestroy: function(){
    this._super();

    flatten(values(this.filteredRecordArrays.values)).forEach(destroy);
  }
});

function values(obj) {
  var result = [];
  var keys = Ember.keys(obj);

  for (var i = 0; i < keys.length; i++) {
    result.push(obj[keys[i]]);
  }

  return result;
}

function destroy(entry) {
  entry.destroy();
}

function flatten(list) {
  var length = list.length;
  var result = Ember.A();

  for (var i = 0; i < length; i++) {
    result = result.concat(list[i]);
  }

  return result;
}

export default RecordArrayManager;
<commit_msg>Remove unneeded `registerWaitingRecordArray` method<commit_after>/**
  @module ember-orbit
*/

import RecordArray from './record_arrays/record_array';
import FilteredRecordArray from './record_arrays/filtered_record_array';

var get = Ember.get,
    set = Ember.set;

var forEach = Ember.EnumerableUtils.forEach;

/**
  @class RecordArrayManager
  @namespace EO
  @private
  @extends Ember.Object
*/
var RecordArrayManager = Ember.Object.extend({
  init: function() {
    this.filteredRecordArrays = Ember.MapWithDefault.create({
      defaultValue: function() { return []; }
    });

    this.changedRecords = [];
  },

  recordDidChange: function(record) {
    if (this.changedRecords.push(record) !== 1) { return; }

    Ember.run.schedule('actions', this, this.updateRecordArrays);
  },

  recordArraysForRecord: function(record) {
    record._recordArrays = record._recordArrays || Ember.OrderedSet.create();
    return record._recordArrays;
  },

  /**
    This method is invoked whenever data is changed in the context.

    It updates all record arrays that a record belongs to.

    To avoid thrashing, it only runs at most once per run loop.

    @method updateRecordArrays
    @param {Class} type
    @param {Number|String} clientId
  */
  updateRecordArrays: function() {
    forEach(this.changedRecords, function(record) {
      if (get(record, 'isDeleted')) {
        this._recordWasDeleted(record);
      } else {
        this._recordWasChanged(record);
      }
    }, this);

    this.changedRecords.length = 0;
  },

  _recordWasDeleted: function (record) {
    var recordArrays = record._recordArrays;

    if (!recordArrays) { return; }

    forEach(recordArrays, function(array) {
      array.removeRecord(record);
    });

    this.context.unload(record);
  },

  _recordWasChanged: function (record) {
    var type = record.constructor.typeKey,
        recordArrays = this.filteredRecordArrays.get(type),
        filter;

    forEach(recordArrays, function(array) {
      filter = get(array, 'filterFunction');
      this.updateRecordArray(array, filter, type, record);
    }, this);
  },

  /**
    Update an individual filter.

    @method updateRecordArray
    @param {EO.FilteredRecordArray} array
    @param {Function} filter
    @param {Class} type
    @param {Number|String} clientId
  */
  updateRecordArray: function(array, filter, type, record) {
    var shouldBeInArray;

    if (!filter) {
      shouldBeInArray = true;
    } else {
      shouldBeInArray = filter(record);
    }

    var recordArrays = this.recordArraysForRecord(record);

    if (shouldBeInArray) {
      recordArrays.add(array);
      array.addRecord(record);
    } else if (!shouldBeInArray) {
      recordArrays.remove(array);
      array.removeRecord(record);
    }
  },

  /**
    This method is invoked if the `filterFunction` property is
    changed on a `EO.FilteredRecordArray`.

    It essentially re-runs the filter from scratch. This same
    method is invoked when the filter is created in th first place.

    @method updateFilter
    @param array
    @param type
    @param filter
  */
  updateFilter: function(array, type, filter) {
    var records = this.context.retrieve(type),
        record;

    for (var i=0, l=records.length; i<l; i++) {
      record = records[i];

      if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) {
        this.updateRecordArray(array, filter, type, record);
      }
    }
  },

  /**
    Create a `EO.RecordArray` for a type and register it for updates.

    @method createRecordArray
    @param {Class} type
    @return {EO.RecordArray}
  */
  createRecordArray: function(type) {
    var array = RecordArray.create({
      type: type,
      content: Ember.A(),
      context: this.context
    });

    this.registerFilteredRecordArray(array, type);

    return array;
  },

  /**
    Create a `EO.FilteredRecordArray` for a type and register it for updates.

    @method createFilteredRecordArray
    @param {Class} type
    @param {Function} filter
    @param {Object} query (optional
    @return {EO.FilteredRecordArray}
  */
  createFilteredRecordArray: function(type, filter, query) {
    var array = FilteredRecordArray.create({
      query: query,
      type: type,
      content: Ember.A(),
      context: this.context,
      manager: this,
      filterFunction: filter
    });

    this.registerFilteredRecordArray(array, type, filter);

    return array;
  },

  /**
    Register a RecordArray for a given type to be backed by
    a filter function. This will cause the array to update
    automatically when records of that type change attribute
    values or states.

    @method registerFilteredRecordArray
    @param {EO.RecordArray} array
    @param {Class} type
    @param {Function} filter
  */
  registerFilteredRecordArray: function(array, type, filter) {
    var recordArrays = this.filteredRecordArrays.get(type);
    recordArrays.push(array);

    this.updateFilter(array, type, filter);
  },

  willDestroy: function(){
    this._super();

    flatten(values(this.filteredRecordArrays.values)).forEach(destroy);
  }
});

function values(obj) {
  var result = [];
  var keys = Ember.keys(obj);

  for (var i = 0; i < keys.length; i++) {
    result.push(obj[keys[i]]);
  }

  return result;
}

function destroy(entry) {
  entry.destroy();
}

function flatten(list) {
  var length = list.length;
  var result = Ember.A();

  for (var i = 0; i < length; i++) {
    result = result.concat(list[i]);
  }

  return result;
}

export default RecordArrayManager;
<|endoftext|>


<commit_before>const debug = require('debug')('dusgarage')
var express  = require('express');
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var app   = express();
var request = require('request')
var http = require('http');
var server = http.createServer(app);
var io    = require('socket.io').listen(server);
var cron  = require('node-cron');
var fs    = require("fs");
var env = process.env.DUSGARAGE_CFG || "/tmp/dusgarage_cfg.js";
var cfg = require(env);
//var sleep = require("sleep-async")();
var google = require('googleapis');
var plus = google.plus('v1');

var parkinglots;
var arrayOfStates;
var doorState = "UNKNOWN";
var isSecurityEnabled = cfg.SECURITY_ENABLED;
var fileSelfChanged = false;

// ------------- Init stuff ----------------
app.use(cookieParser());
app.use(bodyParser.json());

// ----------- BUSINESS LOGIC ----------
function getNextState(state) {
  debug("getNextState state=%j", state);

  for (i=0; i<arrayOfStates.length; i++ ) {
    if (state.name == arrayOfStates[i].name) {
      return arrayOfStates[(i+1) % arrayOfStates.length];
    }
  }

  // State not found: return first:
  return arrayOfStates[0];
}

function resetStates() {
  console.log('resetting all states to initial state %s', arrayOfStates[0].name);
  for (i=0; i<parkinglots.length; i++ ) {
    parkinglots[i].state = arrayOfStates[0];
  }
  parkinglotModified();
}

function parkinglotModified() {
  debug("Persisting state...")
  fileSelfChanged = true;

  fs.writeFile( cfg.CURRENT_STATE_FILE_PATH, JSON.stringify(parkinglots, null, 2), function(err) {
    fileSelfChanged = false;
     if (err) {
        return console.error(err);
     }
   });

   broadcastStateChange();
}

function checkDoorAvailability() {
  debug("checkDoorAvailability with URL %s", cfg.DOOR_URL_CHECK )

  var req = request.get(cfg.DOOR_URL_CHECK , {timeout: cfg.DOOR_TIMEOUT}, function(err, res, body) {
    debug('response');
    if (!err && res.statusCode == 200) {
      handleNewDoorState("ONLINE");
    } else{
      debug("err=%s", err)
      handleNewDoorState("OFFLINE");
    }
  });
}

function handleNewDoorState(newDoorState) {
  if (newDoorState !== doorState) {
    doorState = newDoorState;
    debug("Broadcast new door state %s to %s connected clients...", doorState, io.engine.clientsCount)
    io.sockets.emit('updateDoor', doorState);
  }

}

// ----------- REST SERVICES ----------

app.get('/parkinglots', function (req, res) {
    debug("get parkinglots")
    res.end( JSON.stringify(parkinglots));
})
app.get('/parkinglots/:id', function (req, res) {
  debug("get parkinglots id=%s", req.params.id)
  res.end( JSON.stringify(parkinglots[req.params.id]));
})

app.post('/parkinglots/:id', ensureAuthenticated, function (req, res) {
  debug("post parkinglots id=%s", req.params.id);
  parkinglot = parkinglots[req.params.id];
  oldState = parkinglot.state;
  newState = getNextState(oldState);
  modified = false;

  if (newState.name == "FREE") {
    // Only the current owner can free his parking lot:
    if (isSecurityEnabled==false || parkinglot.user == req.user) {
      parkinglot.user = "-nobody-";
      parkinglot.state = newState;
      modified = true;
    }
  } else if (newState.name == "RESERVED") {
    if (isSecurityEnabled) {
      parkinglot.user = req.user;
    } else {
      parkinglot.user = "-unknown-";
    }
    parkinglot.state = newState;
    modified = true;
  } else if (newState.name == "OCCUPIED") {
      // Only user with reservation can occupy:
      if (isSecurityEnabled==false || parkinglot.user == req.user) {
         parkinglot.state = newState;
         modified = true;
    }
  }

  if (modified)
    parkinglotModified();

  res.end( JSON.stringify(parkinglot));
});

app.post('/openDoor', ensureAuthenticated, function (req, resClient) {
  debug("post openDoor");
  var req = request.post(cfg.DOOR_URL_OPEN, {timeout: cfg.DOOR_TIMEOUT}, function(err, res, body) {
    debug('response');
    if (!err && res.statusCode == 200) {
      resClient.status(200).json({ message: "OK" });
      handleNewDoorState("ONLINE");
    } else{
      resClient.status("503").json({ message: err });
      handleNewDoorState("OFFLINE");
    }
    resClient.end();
  });

});

// ----------- PAGES SERVICES ----------

app.get('/', ensureAuthenticated, function (req, res) {
	res.sendFile(__dirname + '/client.html');
});
app.get('/error', function (req, res) {
	res.status("400").sendFile(__dirname + '/error.html');
});

app.get('/logout', function (req, res) {
  res.clearCookie("bearer");
  res.redirect("/");
});

app.get('/health', function(req, res){
  res.send('1');
});
app.get('/ready', function(req, res){
  res.send('1');
});

// ------------- Websocket stuff: ----------------

io.sockets.on('connection', function (socket) {
  debug("websocket client connected");
  // Send update to this client in case client was disconnected for a long time
  // and state has changed meanwhile:
  socket.emit('updateLots', parkinglots);
  socket.emit('updateDoor', doorState);

  socket.on('disconnect', function () {
    debug("websocket client disconnect");
  });
});

function broadcastStateChange() {
  debug("Broadcast state change to %s connected clients...", io.engine.clientsCount)
  io.sockets.emit('updateLots', parkinglots);
}

// ------------- Authentication stuff: ----------------
console.log("Setting up google authentication with security enabled = %s...", isSecurityEnabled);
";

var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(
  cfg.GOOGLE_CLIENT_ID,
  cfg.GOOGLE_CLIENT_SECRET,
  cfg.GOOGLE_CALLBACK_URL
);
var authurl = oauth2Client.generateAuthUrl({
  scope: [
    'https://www.googleapis.com/auth/plus.login',
    'https://www.googleapis.com/auth/plus.me',
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile'
  ],
  access_type: 'offline'
});

app.get('/auth/google', function(req, res){
  debug("auth/google: server side redirect to %s", authurl);
  res.redirect(authurl);
});

app.get('/oauth2callback', function(req, res){
  debug("oauth2callback");
  var code = req.query.code;
  debug("code = %s", code);

  oauth2Client.getToken(code, function(err, tokens) {
      debug("getToken: err=%s, tokens=%s", err, JSON.stringify(tokens));

      if (err) {
        msg = "getToken failed with error " +err;
        debug(msg);
        res.redirect("/error?msg="+msg);
      } else {
        if (tokens.refresh_token === undefined && tokens.access_token !== undefined) {
          debug("Handle Special case - use access_token");
          token = tokens.access_token;
        } else {
          debug("Handle Special case - use refresh_token");
          token = tokens.refresh_token;
        }

//      debug("Storing id token in bearer cookie");
//      res.cookie('bearer', tokens.id_token, { expires: new Date(Date.now() + 9999999), httpOnly:true });

        debug("Storing  token in bearer cookie: %s", token);
        res.cookie('bearer', token, { expires: new Date(Date.now() + 1000*60*60*24*365), httpOnly:true });

        // Send back the token to the client in URL
        res.redirect("/");
      }
  });
});

function ensureAuthenticated(req, res, next) {
  debug("ensureAuthenticated isSecurityEnabled=%s", isSecurityEnabled);

  if (isSecurityEnabled == true) {
    if (req.cookies.bearer) {
      debug("bearer cookie: %s", req.cookies.bearer);

      // Bearer token is a refresh_token
      // Use it to make a call to google plus API to retrieve user details
      oauth2Client.setCredentials({
        refresh_token: req.cookies.bearer
      });

      plus.people.get({
        userId: 'me',
        auth: oauth2Client}, function (err, response) {
          if (err) {
            msg = "Bearer Cookie validation failed with error" + err;
            debug(msg);
            res.redirect("/error?msg="+msg);
          } else {
            debug("Bearer Cookie validated! response=%s", JSON.stringify(response));
            req.user=response.displayName;

            return next();
          }
      });

/* First Version with id_token as bearer token:

      debug("Bearer Cookie found - need to validate it");
      oauth2Client.verifyIdToken(
        req.cookies.bearer,
        cfg.GOOGLE_CLIENT_ID,
        function(err, login) {
            if (err) {
              debug("Bearer Cookie validation failed with error %s", err);
              debug("Redirecting to login");
              res.redirect("/auth/google");
            } else {
              debug("Bearer Cookie validated!");
              var payload = login.getPayload();
              var email = payload['email'];
              var domain = payload['hd'];
              debug("domain=%s, email = %s", domain, email);

              req.user=email;

              return next();
            }
        }
      );
*/
    } else {
      msg = "No Bearer Cookie found";
      debug(msg);
      res.redirect("/error?msg="+msg);
    }
  } else {
    debug("security is disabled");
    return next();
  }
}

function readParkingLotsFromFile() {
  console.log("Reading parkinglots from "+cfg.CURRENT_STATE_FILE_PATH+"...")
  return fs.readFile( cfg.CURRENT_STATE_FILE_PATH, 'utf8', function (err, data) {
      if (err || data == null || data.length < 16) {
        console.log("... failed! err=%s, data=%s", err, data);
        return false;
      } else {
        parkinglots = JSON.parse(data)
        return true;
      }
  });
}

// ------------- INIT ----------------
readParkingLotsFromFile();

console.log("Watching parkinglots...");

fs.watch(cfg.CURRENT_STATE_FILE_PATH, function (event, filename) {
    debug('Parkinglots changed on disc. filename=%s, Event=%s, selfChanged=%s ',filename, event, fileSelfChanged);
    if (filename && event=="change" && !fileSelfChanged) {
        console.log("Parkingslots changed on disc - refreshing...");
        readParkingLotsFromFile();
        broadcastStateChange();
    }
});

console.log("Reading states...")
fs.readFile( __dirname + "/" + "states.json", 'utf8', function (err, data) {
    arrayOfStates = JSON.parse(data)
});

console.log("Creating server socket...")
server.listen(cfg.SERVER_PORT);

console.log("Scheduling cronjobs....")
 // ss mm hh day month dayOfWeek
cron.schedule(cfg.CRON_RESET_LOTS, function(){
  resetStates()
});

cron.schedule(cfg.CRON_DOOR_CHECK, function(){
  checkDoorAvailability()
});

console.log("Check door backend availability...");
//sleep.sleep(5000, checkDoorAvailability)

//console.log("Server startup completed! Listening at http://%s:%s", server.address().address, server.address().port)
<commit_msg>Security is now configurable<commit_after>const debug = require('debug')('dusgarage')
var express  = require('express');
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var app   = express();
var request = require('request')
var http = require('http');
var server = http.createServer(app);
var io    = require('socket.io').listen(server);
var cron  = require('node-cron');
var fs    = require("fs");
var env = process.env.DUSGARAGE_CFG || "/tmp/dusgarage_cfg.js";
var cfg = require(env);
//var sleep = require("sleep-async")();
var google = require('googleapis');
var plus = google.plus('v1');

var parkinglots;
var arrayOfStates;
var doorState = "UNKNOWN";
var isSecurityEnabled = cfg.SECURITY_ENABLED;
var fileSelfChanged = false;

// ------------- Init stuff ----------------
app.use(cookieParser());
app.use(bodyParser.json());

// ----------- BUSINESS LOGIC ----------
function getNextState(state) {
  debug("getNextState state=%j", state);

  for (i=0; i<arrayOfStates.length; i++ ) {
    if (state.name == arrayOfStates[i].name) {
      return arrayOfStates[(i+1) % arrayOfStates.length];
    }
  }

  // State not found: return first:
  return arrayOfStates[0];
}

function resetStates() {
  console.log('resetting all states to initial state %s', arrayOfStates[0].name);
  for (i=0; i<parkinglots.length; i++ ) {
    parkinglots[i].state = arrayOfStates[0];
  }
  parkinglotModified();
}

function parkinglotModified() {
  debug("Persisting state...")
  fileSelfChanged = true;

  fs.writeFile( cfg.CURRENT_STATE_FILE_PATH, JSON.stringify(parkinglots, null, 2), function(err) {
    fileSelfChanged = false;
     if (err) {
        return console.error(err);
     }
   });

   broadcastStateChange();
}

function checkDoorAvailability() {
  debug("checkDoorAvailability with URL %s", cfg.DOOR_URL_CHECK )

  var req = request.get(cfg.DOOR_URL_CHECK , {timeout: cfg.DOOR_TIMEOUT}, function(err, res, body) {
    debug('response');
    if (!err && res.statusCode == 200) {
      handleNewDoorState("ONLINE");
    } else{
      debug("err=%s", err)
      handleNewDoorState("OFFLINE");
    }
  });
}

function handleNewDoorState(newDoorState) {
  if (newDoorState !== doorState) {
    doorState = newDoorState;
    debug("Broadcast new door state %s to %s connected clients...", doorState, io.engine.clientsCount)
    io.sockets.emit('updateDoor', doorState);
  }

}

// ----------- REST SERVICES ----------

app.get('/parkinglots', function (req, res) {
    debug("get parkinglots")
    res.end( JSON.stringify(parkinglots));
})
app.get('/parkinglots/:id', function (req, res) {
  debug("get parkinglots id=%s", req.params.id)
  res.end( JSON.stringify(parkinglots[req.params.id]));
})

app.post('/parkinglots/:id', ensureAuthenticated, function (req, res) {
  debug("post parkinglots id=%s", req.params.id);
  parkinglot = parkinglots[req.params.id];
  oldState = parkinglot.state;
  newState = getNextState(oldState);
  modified = false;

  if (newState.name == "FREE") {
    // Only the current owner can free his parking lot:
    if (isSecurityEnabled==false || parkinglot.user == req.user) {
      parkinglot.user = "-nobody-";
      parkinglot.state = newState;
      modified = true;
    }
  } else if (newState.name == "RESERVED") {
    if (isSecurityEnabled) {
      parkinglot.user = req.user;
    } else {
      parkinglot.user = "-unknown-";
    }
    parkinglot.state = newState;
    modified = true;
  } else if (newState.name == "OCCUPIED") {
      // Only user with reservation can occupy:
      if (isSecurityEnabled==false || parkinglot.user == req.user) {
         parkinglot.state = newState;
         modified = true;
    }
  }

  if (modified)
    parkinglotModified();

  res.end( JSON.stringify(parkinglot));
});

app.post('/openDoor', ensureAuthenticated, function (req, resClient) {
  debug("post openDoor");
  var req = request.post(cfg.DOOR_URL_OPEN, {timeout: cfg.DOOR_TIMEOUT}, function(err, res, body) {
    debug('response');
    if (!err && res.statusCode == 200) {
      resClient.status(200).json({ message: "OK" });
      handleNewDoorState("ONLINE");
    } else{
      resClient.status("503").json({ message: err });
      handleNewDoorState("OFFLINE");
    }
    resClient.end();
  });

});

// ----------- PAGES SERVICES ----------

app.get('/', ensureAuthenticated, function (req, res) {
	res.sendFile(__dirname + '/client.html');
});
app.get('/error', function (req, res) {
	res.status("400").sendFile(__dirname + '/error.html');
});

app.get('/logout', function (req, res) {
  res.clearCookie("bearer");
  res.redirect("/");
});

app.get('/health', function(req, res){
  res.send('1');
});
app.get('/ready', function(req, res){
  res.send('1');
});

// ------------- Websocket stuff: ----------------

io.sockets.on('connection', function (socket) {
  debug("websocket client connected");
  // Send update to this client in case client was disconnected for a long time
  // and state has changed meanwhile:
  socket.emit('updateLots', parkinglots);
  socket.emit('updateDoor', doorState);

  socket.on('disconnect', function () {
    debug("websocket client disconnect");
  });
});

function broadcastStateChange() {
  debug("Broadcast state change to %s connected clients...", io.engine.clientsCount)
  io.sockets.emit('updateLots', parkinglots);
}

// ------------- Authentication stuff: ----------------
console.log("Setting up google authentication with security enabled = %s...", isSecurityEnabled);

var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(
  cfg.GOOGLE_CLIENT_ID,
  cfg.GOOGLE_CLIENT_SECRET,
  cfg.GOOGLE_CALLBACK_URL
);
var authurl = oauth2Client.generateAuthUrl({
  scope: [
    'https://www.googleapis.com/auth/plus.login',
    'https://www.googleapis.com/auth/plus.me',
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile'
  ],
  access_type: 'offline'
});

app.get('/auth/google', function(req, res){
  debug("auth/google: server side redirect to %s", authurl);
  res.redirect(authurl);
});

app.get('/oauth2callback', function(req, res){
  debug("oauth2callback");
  var code = req.query.code;
  debug("code = %s", code);

  oauth2Client.getToken(code, function(err, tokens) {
      debug("getToken: err=%s, tokens=%s", err, JSON.stringify(tokens));

      if (err) {
        msg = "getToken failed with error " +err;
        debug(msg);
        res.redirect("/error?msg="+msg);
      } else {
        if (tokens.refresh_token === undefined && tokens.access_token !== undefined) {
          debug("Handle Special case - use access_token");
          token = tokens.access_token;
        } else {
          debug("Handle Special case - use refresh_token");
          token = tokens.refresh_token;
        }

//      debug("Storing id token in bearer cookie");
//      res.cookie('bearer', tokens.id_token, { expires: new Date(Date.now() + 9999999), httpOnly:true });

        debug("Storing  token in bearer cookie: %s", token);
        res.cookie('bearer', token, { expires: new Date(Date.now() + 1000*60*60*24*365), httpOnly:true });

        // Send back the token to the client in URL
        res.redirect("/");
      }
  });
});

function ensureAuthenticated(req, res, next) {
  debug("ensureAuthenticated isSecurityEnabled=%s", isSecurityEnabled);

  if (isSecurityEnabled == true) {
    if (req.cookies.bearer) {
      debug("bearer cookie: %s", req.cookies.bearer);

      // Bearer token is a refresh_token
      // Use it to make a call to google plus API to retrieve user details
      oauth2Client.setCredentials({
        refresh_token: req.cookies.bearer
      });

      plus.people.get({
        userId: 'me',
        auth: oauth2Client}, function (err, response) {
          if (err) {
            msg = "Bearer Cookie validation failed with error" + err;
            debug(msg);
            res.redirect("/error?msg="+msg);
          } else {
            debug("Bearer Cookie validated! response=%s", JSON.stringify(response));
            req.user=response.displayName;

            return next();
          }
      });

/* First Version with id_token as bearer token:

      debug("Bearer Cookie found - need to validate it");
      oauth2Client.verifyIdToken(
        req.cookies.bearer,
        cfg.GOOGLE_CLIENT_ID,
        function(err, login) {
            if (err) {
              debug("Bearer Cookie validation failed with error %s", err);
              debug("Redirecting to login");
              res.redirect("/auth/google");
            } else {
              debug("Bearer Cookie validated!");
              var payload = login.getPayload();
              var email = payload['email'];
              var domain = payload['hd'];
              debug("domain=%s, email = %s", domain, email);

              req.user=email;

              return next();
            }
        }
      );
*/
    } else {
      msg = "No Bearer Cookie found";
      debug(msg);
      res.redirect("/error?msg="+msg);
    }
  } else {
    debug("security is disabled");
    return next();
  }
}

function readParkingLotsFromFile() {
  console.log("Reading parkinglots from "+cfg.CURRENT_STATE_FILE_PATH+"...")
  return fs.readFile( cfg.CURRENT_STATE_FILE_PATH, 'utf8', function (err, data) {
      if (err || data == null || data.length < 16) {
        console.log("... failed! err=%s, data=%s", err, data);
        return false;
      } else {
        parkinglots = JSON.parse(data)
        return true;
      }
  });
}

// ------------- INIT ----------------
readParkingLotsFromFile();

console.log("Watching parkinglots...");

fs.watch(cfg.CURRENT_STATE_FILE_PATH, function (event, filename) {
    debug('Parkinglots changed on disc. filename=%s, Event=%s, selfChanged=%s ',filename, event, fileSelfChanged);
    if (filename && event=="change" && !fileSelfChanged) {
        console.log("Parkingslots changed on disc - refreshing...");
        readParkingLotsFromFile();
        broadcastStateChange();
    }
});

console.log("Reading states...")
fs.readFile( __dirname + "/" + "states.json", 'utf8', function (err, data) {
    arrayOfStates = JSON.parse(data)
});

console.log("Creating server socket...")
server.listen(cfg.SERVER_PORT);

console.log("Scheduling cronjobs....")
 // ss mm hh day month dayOfWeek
cron.schedule(cfg.CRON_RESET_LOTS, function(){
  resetStates()
});

cron.schedule(cfg.CRON_DOOR_CHECK, function(){
  checkDoorAvailability()
});

console.log("Check door backend availability...");
//sleep.sleep(5000, checkDoorAvailability)

//console.log("Server startup completed! Listening at http://%s:%s", server.address().address, server.address().port)
<|endoftext|>


<commit_before>module.exports = function () {
  this.filter("cssnext", (source, options) => {
    try {
      return require("cssnext")(source, options)
     } catch (e) { throw e }
  })
}
<commit_msg>convert raw data to string<commit_after>module.exports = function () {
  this.filter("cssnext", (data, options) => {
    return require("cssnext")(data.toString(), options)
  })
}
<|endoftext|>


<commit_before>var http = require("http");
var express = require('express');
var app = express();
var request = require("request");
var string = require("string");

var config = require('getconfig');

app.listen(process.env.PORT);

app.all('/', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  next();
});

function parseYelp(restaurantName, zipcode) {
	return { "Yelp": true}
}

app.get('/get-restaurant', function(req, res){
  data = { "name": req.query.name, "zipcode": req.query.zipcode, "searchCompleted": true };
  res.json(data);
  res.end();
});

app.get('/get-opendata', function (req, res) {
    console.log('testing stuff');
    dataIn = { "name": req.query.name, "zip": req.query.zip };
    getOpenData(dataIn.name, dataIn.zip, res);
});

var getOpenData = function (name, zip, response) {
    var url = config.openData.url || process.env.openDataUrl + "collections/restaurants?q={ \"DBA Name\": " + name + ", Zip: " + zip + "}&apiKey=" + config.openData.apiKey || openDataApiKey;
    var openDataResults;
    request.get(url, function (e, r, openDataResults) {
        var data = JSON.parse(openDataResults);
        var firstData = data[0];

        var output =
        {
            "Name": firstData["DBA Name"],
            "Address1": firstData["Address"],
            "City": firstData["City"],
            "State": firstData["State"],
            "Zip": firstData["Zip"],
            "Risk": firstData["Risk"],
            "Results": firstData["Results"],
            "Latitude": firstData["Latitude"],
            "Longitude": firstData["Longitude"],
            "Location": firstData["Location"],
            "InspectionViolations": firstData["Violations"],
            "YelpRating": "",
            "YelpReviewCount": -1,
            "SearchCompleted": true,
        };
        console.log(output);
        response.json(output);
        response.end();
    });
};

var server = app.listen(3000, function() {
    console.log('Listening on port %d', server.address().port);
});<commit_msg>Updating heroku vars<commit_after>var http = require("http");
var express = require('express');
var app = express();
var request = require("request");
var string = require("string");

var config = require('getconfig');

app.listen(process.env.PORT);

app.all('/', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  next();
});

function parseYelp(restaurantName, zipcode) {
	return { "Yelp": true}
}

app.get('/get-restaurant', function(req, res){
  data = { "name": req.query.name, "zipcode": req.query.zipcode, "searchCompleted": true };
  res.json(data);
  res.end();
});

app.get('/get-opendata', function (req, res) {
    console.log('testing stuff');
    dataIn = { "name": req.query.name, "zip": req.query.zip };
    getOpenData(dataIn.name, dataIn.zip, res);
});

var getOpenData = function (name, zip, response) {
    var url = config.openData.url || process.env.openDataUrl + "collections/restaurants?q={ \"DBA Name\": " + name + ", Zip: " + zip + "}&apiKey=" + config.openData.apiKey || process.env.openDataApiKey;
    var openDataResults;
    request.get(url, function (e, r, openDataResults) {
        var data = JSON.parse(openDataResults);
        var firstData = data[0];

        var output =
        {
            "Name": firstData["DBA Name"],
            "Address1": firstData["Address"],
            "City": firstData["City"],
            "State": firstData["State"],
            "Zip": firstData["Zip"],
            "Risk": firstData["Risk"],
            "Results": firstData["Results"],
            "Latitude": firstData["Latitude"],
            "Longitude": firstData["Longitude"],
            "Location": firstData["Location"],
            "InspectionViolations": firstData["Violations"],
            "YelpRating": "",
            "YelpReviewCount": -1,
            "SearchCompleted": true,
        };
        console.log(output);
        response.json(output);
        response.end();
    });
};

var server = app.listen(3000, function() {
    console.log('Listening on port %d', server.address().port);
});<|endoftext|>


<commit_before>/*
 * Implements a user-facing modal confirmation when link has a
 * "data-confirm" attribute using bootstrap's modals. MIT license.
 *
 *   - vjt@openssl.it  Tue Jul  2 18:45:15 CEST 2013
 */
(function ($) {

  /**
   * Builds the markup for a [Bootstrap modal](http://twitter.github.io/bootstrap/javascript.html#modals)
   * for the given `element`. Uses the following `data-` parameters to
   * customize it:
   *
   *  * `data-confirm`: Contains the modal body text. HTML is allowed.
   *                    Separate multiple paragraphs using \n\n.
   *  * `data-commit`:  The 'confirm' button text. "Confirm" by default.
   *  * `data-verify`:  Adds a text input in which the user has to input
   *                    the text in this attribute value for the 'confirm'
   *                    button to be clickable. Optional.
   *
   * You can set global setting using `dataConfirmModal.setDefaults`, for example:
   *
   *    dataConfirmModal.setDefaults({
   *      title: 'Confirm your action',
   *      commit: 'Continue',
   *      cancel: 'Cancel'
   *    });
   *
   */

  var defaults = {
    title: 'Are you ABSOLUTELY sure?',
    commit: 'Confirm',
    cancel: 'Cancel'
  };

  var settings;

  window.dataConfirmModal = {
    setDefaults: function (newSettings) {
      settings = $.extend(settings, newSettings);
    },

    restoreDefaults: function () {
      settings = $.extend({}, defaults);
    }
  };

  dataConfirmModal.restoreDefaults();

  var buildModal = function (element) {
    var id = 'confirm-modal-' + String(Math.random()).slice(2, -1);

    var modal = $(
      '
' +
        '
' +
          '<button class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
          '

 ' +
        '
' +
        '

' +
        '
' +
          '<button class="btn" data-dismiss="modal" aria-hidden="true">' + settings.cancel + '</button>' +
          '<button class="btn btn-danger commit"></button>' +
        '
'+
      '
'
    );

    var title = element.attr('title') || element.data('original-title') || settings.title;

    modal.find('.modal-header h3').text(title);

    var body = modal.find('.modal-body');

    $.each(element.data('confirm').split(/\n{2}/), function (i, piece) {
      body.append($('
').html(piece));
    });

    var commit = modal.find('.commit');
    commit.text(element.data('commit') || settings.commit);

    if(element.data('remote')){
      commit.attr('data-dismiss', 'modal');
    }

    var verify = element.data('verify');
    if (verify) {
      commit.prop('disabled', true);

      var verification = $('<input/>', {type: 'text'}).on('keyup', function () {
        commit.prop('disabled', $(this).val() !== verify);
      });

      modal.on('shown', function () {
        verification.focus();
      });

      modal.on('hide', function () {
        verification.val('').trigger('keyup');
      });

      body.append(verification);
    }

    modal.data('confirmed', false);
    commit.on('click', function () {
      modal.data('confirmed', true);
      element.trigger('click');
      modal.modal('hide');
    });

    $('body').append(modal);

    return modal;
  };

  /**
   * Returns a modal already built for the given element or builds a new one,
   * caching it into the element's `confirm-modal` data attribute.
   */
  var getModal = function (element) {
    var modal = element.data('confirm-modal') || buildModal(element);

    if (modal && !element.data('confirm-modal'))
      element.data('confirm-modal', modal);

    return modal;
  }

  /**
   * Attaches to the Rails' UJS adapter 'confirm' event on links having a
   * `data-confirm` attribute. Temporarily overrides the `$.rails.confirm`
   * function with an anonymous one that returns the 'confirmed' status of
   * the modal.
   *
   * A modal is considered 'confirmed' when an user has successfully clicked
   * the 'confirm' button in it.
   */
  $(document).delegate('a[data-confirm]', 'confirm', function (e) {
    var element = $(this), modal = getModal(element);
    var confirmed = modal.data('confirmed');

    if (!confirmed && !modal.is(':visible')) {
      modal.modal('show');

      var confirm = $.rails.confirm;
      $.rails.confirm = function () { return modal.data('confirmed'); }
      modal.on('hide', function () { $.rails.confirm = confirm; });
    }

    return confirmed;
  });

})(jQuery);
<commit_msg>Enable data-confirm behaviour on buttons as well<commit_after>/*
 * Implements a user-facing modal confirmation when link has a
 * "data-confirm" attribute using bootstrap's modals. MIT license.
 *
 *   - vjt@openssl.it  Tue Jul  2 18:45:15 CEST 2013
 */
(function ($) {

  /**
   * Builds the markup for a [Bootstrap modal](http://twitter.github.io/bootstrap/javascript.html#modals)
   * for the given `element`. Uses the following `data-` parameters to
   * customize it:
   *
   *  * `data-confirm`: Contains the modal body text. HTML is allowed.
   *                    Separate multiple paragraphs using \n\n.
   *  * `data-commit`:  The 'confirm' button text. "Confirm" by default.
   *  * `data-verify`:  Adds a text input in which the user has to input
   *                    the text in this attribute value for the 'confirm'
   *                    button to be clickable. Optional.
   *
   * You can set global setting using `dataConfirmModal.setDefaults`, for example:
   *
   *    dataConfirmModal.setDefaults({
   *      title: 'Confirm your action',
   *      commit: 'Continue',
   *      cancel: 'Cancel'
   *    });
   *
   */

  var defaults = {
    title: 'Are you ABSOLUTELY sure?',
    commit: 'Confirm',
    cancel: 'Cancel'
  };

  var settings;

  window.dataConfirmModal = {
    setDefaults: function (newSettings) {
      settings = $.extend(settings, newSettings);
    },

    restoreDefaults: function () {
      settings = $.extend({}, defaults);
    }
  };

  dataConfirmModal.restoreDefaults();

  var buildModal = function (element) {
    var id = 'confirm-modal-' + String(Math.random()).slice(2, -1);

    var modal = $(
      '
' +
        '
' +
          '<button class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
          '

 ' +
        '
' +
        '

' +
        '
' +
          '<button class="btn" data-dismiss="modal" aria-hidden="true">' + settings.cancel + '</button>' +
          '<button class="btn btn-danger commit"></button>' +
        '
'+
      '
'
    );

    var title = element.attr('title') || element.data('original-title') || settings.title;

    modal.find('.modal-header h3').text(title);

    var body = modal.find('.modal-body');

    $.each(element.data('confirm').split(/\n{2}/), function (i, piece) {
      body.append($('
').html(piece));
    });

    var commit = modal.find('.commit');
    commit.text(element.data('commit') || settings.commit);

    if(element.data('remote')){
      commit.attr('data-dismiss', 'modal');
    }

    var verify = element.data('verify');
    if (verify) {
      commit.prop('disabled', true);

      var verification = $('<input/>', {type: 'text'}).on('keyup', function () {
        commit.prop('disabled', $(this).val() !== verify);
      });

      modal.on('shown', function () {
        verification.focus();
      });

      modal.on('hide', function () {
        verification.val('').trigger('keyup');
      });

      body.append(verification);
    }

    modal.data('confirmed', false);
    commit.on('click', function () {
      modal.data('confirmed', true);
      element.trigger('click');
      modal.modal('hide');
    });

    $('body').append(modal);

    return modal;
  };

  /**
   * Returns a modal already built for the given element or builds a new one,
   * caching it into the element's `confirm-modal` data attribute.
   */
  var getModal = function (element) {
    var modal = element.data('confirm-modal') || buildModal(element);

    if (modal && !element.data('confirm-modal'))
      element.data('confirm-modal', modal);

    return modal;
  }

  /**
   * Attaches to the Rails' UJS adapter 'confirm' event on links having a
   * `data-confirm` attribute. Temporarily overrides the `$.rails.confirm`
   * function with an anonymous one that returns the 'confirmed' status of
   * the modal.
   *
   * A modal is considered 'confirmed' when an user has successfully clicked
   * the 'confirm' button in it.
   */
  $(document).delegate('a[data-confirm], button[data-confirm]', 'confirm', function (e) {
    var element = $(this), modal = getModal(element);
    var confirmed = modal.data('confirmed');

    if (!confirmed && !modal.is(':visible')) {
      modal.modal('show');

      var confirm = $.rails.confirm;
      $.rails.confirm = function () { return modal.data('confirmed'); }
      modal.on('hide', function () { $.rails.confirm = confirm; });
    }

    return confirmed;
  });

})(jQuery);
<|endoftext|>


<commit_before>"use strict";

const DEFAULT_DELAY_TIME = 5;
const DEFAULT_FRAME_NUM = 10

const TEMP_DIRECTRY_PREFIX = 'kirakira';
const temp = require('temp').track();
const fs   = require('fs');
const util  = require('util');
const path = require('path');
const im = require('imagemagick');
const returnTrue = function(){return true};
const phaseImageEffecter = require('./phaseImageEffecter');

let program = require('commander');
program.version('0.0.1');
program.usage('-i <input file> [options]');
program.option('-i, --input <path>', 'input file');
program.option('-l --label <string>', 'label string');
program.option('-o, --output <path>', 'output path');
program.option('-s, --saturation <percent value>', 'saturation value');
program.option('-p, --plain', 'Do NOT Kirakira effect', returnTrue, 0);
program.option('-r  --resize <geometry>', 'resize the image');
program.option('--colors <value>', 'preferred number of colors in the image', parseInt);
program.option('--delay <time>', 'delay time', parseInt);
program.option('--fill <color>', 'color to use when filling a charactors primitive');
program.option('--font <font_file>', 'font file for label');
program.option('--framenum <integer>', 'frame number', parseInt);
program.option('--guruguru', 'enable guruguru effect', returnTrue, 0);
program.option('--reverse', 'Invert the effect time', returnTrue, 0);
program.parse(process.argv);
let input = program.input;
const label = program.label;
const fill = program.fill;
const font = program.font;
const output = program.output !== undefined ? program.output : "out";
const delay = program.delay !== undefined ? program.delay : DEFAULT_DELAY_TIME;
const frame_num  = program.framenum !== undefined ? program.framenum : DEFAULT_FRAME_NUM;

const doNothing = function(){};

const generateAnimatedGIF = function(filePaths){
    const ext = filePaths.length > 1 ? 'gif' : 'png';
    let imArgs = ['-dispose', 'Background',
                  '-delay', delay,
                  '-loop', '0'].concat(filePaths);
    imArgs.push(output.match(new RegExp("\\." + ext + "$")) === null ? output + "." + ext : output);
    im.convert(imArgs, function(err, stdout){
        if(err){
            console.error(err);
            return;
        }
    });
};

const onCompleteValidInput = function(input, workingDir){
    const options = {
        reverse: program.reverse,
        frame_num: program.framenum,
        saturation: program.saturation,
        resize: program.resize,
        shining: program.plain === undefined,
        colors: program.colors,
        rotation: program.guruguru !== undefined
    };
    phaseImageEffecter.createFrames(input, workingDir, frame_num, options, generateAnimatedGIF);
};

const generateLayerImage = function(images, outputPath, cb){
    // TODO: generate label on input image
    cb(images[0]);
};

const random24bitHex = function(){
    return Math.floor(Math.random()*16777216).toString(16);
};

const generateLabelImage = function(label, outputPath, cb){
    var pathname = path.join(outputPath, 'label.png');
    let imArgs = font !== undefined ? ['-font', font] : [];
    imArgs = imArgs.concat(['-pointsize', '128',
                            '-fill', (fill !== undefined? fill : '#' + random24bitHex()),
                            '-background', 'none',
                            'label:' + label +'',
                            '-geometry', '128x128!',
                            pathname
    ]);
    im.convert(imArgs, function(err, stdout){
        if(err){
            console.error(err);
            return;
        }
        cb(pathname);
    });
};

const varidateInputFile = function(input_file, cb){
    // TODO: check valid image format
    fs.open(input_file, 'r', function(err, fd){
        if(err){
            console.error(err);
            return;
        }
        cb();
        fs.close(fd);
    });
};

const onAllocatedTempDirectory = function(err, tempDirPath) {
    if (err) {
        // fail allocate temp working dir
        console.error(err);
        return;
    }
    if(label !== undefined){
        // if label exists create label image
        generateLabelImage(label, tempDirPath, function(labelImage){
            if(input === undefined){
                onCompleteValidInput(labelImage, tempDirPath);
            } else {
                varidateInputFile(input, function(){
                    generateLayerImage([input, label], tempDirPath, function(path){
                        onCompleteValidInput(path, tempDirPath);
                    });
                });
            }
        });
    } else {
        varidateInputFile(input, function(){
            onCompleteValidInput(input, tempDirPath);
        });
    }
};

module.exports = function(){
    if(input === undefined && label === undefined){
        console.error('input file or label is required');
        return;
    }
    // create temp working dir
    temp.mkdir(TEMP_DIRECTRY_PREFIX, onAllocatedTempDirectory);
};
<commit_msg>Fix the Node.js deprecation warning: `DEP0013`<commit_after>"use strict";

const DEFAULT_DELAY_TIME = 5;
const DEFAULT_FRAME_NUM = 10

const TEMP_DIRECTRY_PREFIX = 'kirakira';
const temp = require('temp').track();
const fs   = require('fs');
const util  = require('util');
const path = require('path');
const im = require('imagemagick');
const returnTrue = function(){return true};
const phaseImageEffecter = require('./phaseImageEffecter');

let program = require('commander');
program.version('0.0.1');
program.usage('-i <input file> [options]');
program.option('-i, --input <path>', 'input file');
program.option('-l --label <string>', 'label string');
program.option('-o, --output <path>', 'output path');
program.option('-s, --saturation <percent value>', 'saturation value');
program.option('-p, --plain', 'Do NOT Kirakira effect', returnTrue, 0);
program.option('-r  --resize <geometry>', 'resize the image');
program.option('--colors <value>', 'preferred number of colors in the image', parseInt);
program.option('--delay <time>', 'delay time', parseInt);
program.option('--fill <color>', 'color to use when filling a charactors primitive');
program.option('--font <font_file>', 'font file for label');
program.option('--framenum <integer>', 'frame number', parseInt);
program.option('--guruguru', 'enable guruguru effect', returnTrue, 0);
program.option('--reverse', 'Invert the effect time', returnTrue, 0);
program.parse(process.argv);
let input = program.input;
const label = program.label;
const fill = program.fill;
const font = program.font;
const output = program.output !== undefined ? program.output : "out";
const delay = program.delay !== undefined ? program.delay : DEFAULT_DELAY_TIME;
const frame_num  = program.framenum !== undefined ? program.framenum : DEFAULT_FRAME_NUM;

const doNothing = function(){};

const generateAnimatedGIF = function(filePaths){
    const ext = filePaths.length > 1 ? 'gif' : 'png';
    let imArgs = ['-dispose', 'Background',
                  '-delay', delay,
                  '-loop', '0'].concat(filePaths);
    imArgs.push(output.match(new RegExp("\\." + ext + "$")) === null ? output + "." + ext : output);
    im.convert(imArgs, function(err, stdout){
        if(err){
            console.error(err);
            return;
        }
    });
};

const onCompleteValidInput = function(input, workingDir){
    const options = {
        reverse: program.reverse,
        frame_num: program.framenum,
        saturation: program.saturation,
        resize: program.resize,
        shining: program.plain === undefined,
        colors: program.colors,
        rotation: program.guruguru !== undefined
    };
    phaseImageEffecter.createFrames(input, workingDir, frame_num, options, generateAnimatedGIF);
};

const generateLayerImage = function(images, outputPath, cb){
    // TODO: generate label on input image
    cb(images[0]);
};

const random24bitHex = function(){
    return Math.floor(Math.random()*16777216).toString(16);
};

const generateLabelImage = function(label, outputPath, cb){
    var pathname = path.join(outputPath, 'label.png');
    let imArgs = font !== undefined ? ['-font', font] : [];
    imArgs = imArgs.concat(['-pointsize', '128',
                            '-fill', (fill !== undefined? fill : '#' + random24bitHex()),
                            '-background', 'none',
                            'label:' + label +'',
                            '-geometry', '128x128!',
                            pathname
    ]);
    im.convert(imArgs, function(err, stdout){
        if(err){
            console.error(err);
            return;
        }
        cb(pathname);
    });
};

const varidateInputFile = function(input_file, cb){
    // TODO: check valid image format
    fs.open(input_file, 'r', function(err, fd){
        if(err){
            console.error(err);
            return;
        }
        cb();
        fs.closeSync(fd);
    });
};

const onAllocatedTempDirectory = function(err, tempDirPath) {
    if (err) {
        // fail allocate temp working dir
        console.error(err);
        return;
    }
    if(label !== undefined){
        // if label exists create label image
        generateLabelImage(label, tempDirPath, function(labelImage){
            if(input === undefined){
                onCompleteValidInput(labelImage, tempDirPath);
            } else {
                varidateInputFile(input, function(){
                    generateLayerImage([input, label], tempDirPath, function(path){
                        onCompleteValidInput(path, tempDirPath);
                    });
                });
            }
        });
    } else {
        varidateInputFile(input, function(){
            onCompleteValidInput(input, tempDirPath);
        });
    }
};

module.exports = function(){
    if(input === undefined && label === undefined){
        console.error('input file or label is required');
        return;
    }
    // create temp working dir
    temp.mkdir(TEMP_DIRECTRY_PREFIX, onAllocatedTempDirectory);
};
<|endoftext|>